001/*
002 * Sonar, open source software quality management tool.
003 * Copyright (C) 2008-2012 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * Sonar is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * Sonar is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public
017 * License along with Sonar; if not, write to the Free Software
018 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
019 */
020package org.sonar.plugins.design.batch;
021
022import org.sonar.api.design.Dependency;
023import org.sonar.api.resources.Resource;
024import org.sonar.graph.Dsm;
025import org.sonar.graph.DsmCell;
026
027public final class DsmSerializer {
028
029  private Dsm dsm;
030  private StringBuilder json;
031
032  private DsmSerializer(Dsm<Resource> dsm) {
033    this.dsm = dsm;
034    this.json = new StringBuilder();
035  }
036
037  private String serialize() {
038    json.append('[');
039    serializeRows();
040    json.append(']');
041    return json.toString();
042  }
043
044  private void serializeRows() {
045    for (int y = 0; y < dsm.getDimension(); y++) {
046      if (y > 0) {
047        json.append(',');
048      }
049      serializeRow(y);
050    }
051  }
052
053  private void serializeRow(int y) {
054    Resource resource = (Resource) dsm.getVertex(y);
055
056    json.append("{");
057    if (resource != null) {
058      json.append("\"i\":");
059      json.append(resource.getId());
060      json.append(",\"n\":\"");
061      json.append(resource.getName());
062      json.append("\",\"q\":\"");
063      json.append(resource.getQualifier());
064      json.append("\",\"v\":[");
065      for (int x = 0; x < dsm.getDimension(); x++) {
066        if (x > 0) {
067          json.append(',');
068        }
069        serializeCell(y, x);
070      }
071      json.append("]");
072    }
073    json.append("}");
074  }
075
076  private void serializeCell(int y, int x) {
077    DsmCell cell = dsm.getCell(x, y);
078    json.append('{');
079    if (cell.getEdge() != null && cell.getWeight() > 0) {
080      Dependency dep = (Dependency) cell.getEdge();
081      json.append("\"i\":");
082      json.append(dep.getId());
083      json.append(",\"w\":");
084      json.append(cell.getWeight());
085    }
086    json.append('}');
087  }
088
089  public static String serialize(Dsm<Resource> dsm) {
090    return new DsmSerializer(dsm).serialize();
091  }
092}