Example usage for org.json.simple JSONArray toString

List of usage examples for org.json.simple JSONArray toString

Introduction

In this page you can find the example usage for org.json.simple JSONArray toString.

Prototype

@Override
    public String toString() 

Source Link

Usage

From source file:gov.nih.nci.rembrandt.web.ajax.DynamicListHelper.java

public static String getGeneAliasesList(String commaGenes) {
    //accepts a single gene, or a comma delim list of strings
    JSONArray aliases = new JSONArray();
    commaGenes = commaGenes.replace(" ", "");
    List<String> geneList = Arrays.asList(commaGenes.split(","));
    try {//from  w w w .  j ava 2s. c o  m
        Map<String, List<AllGeneAliasLookup>> validMap = DataValidator.searchGeneKeyWordList(geneList);
        if (validMap != null) {
            for (String symbol : geneList) {
                JSONObject a = new JSONObject();
                a.put("original", symbol);

                if (DataValidator.isGeneSymbolFound(symbol)) {
                    //valid, no aliases
                    a.put("status", "valid");
                } else {
                    List<AllGeneAliasLookup> allGeneAliasLookupList = validMap.get(symbol);
                    if (allGeneAliasLookupList != null) {
                        JSONArray ala = new JSONArray();
                        a.put("status", "hasAliases");
                        for (AllGeneAliasLookup allGeneAliasLookup : allGeneAliasLookupList) {
                            JSONObject alo = new JSONObject();
                            alo.put("symbol",
                                    (allGeneAliasLookup.getApprovedSymbol() != null)
                                            ? allGeneAliasLookup.getApprovedSymbol()
                                            : "N/A");
                            alo.put("name",
                                    (allGeneAliasLookup.getApprovedName() != null)
                                            ? allGeneAliasLookup.getApprovedName()
                                            : "N/A");
                            alo.put("alias",
                                    (allGeneAliasLookup.getAlias() != null) ? allGeneAliasLookup.getAlias()
                                            : "N/A");
                            ala.add(alo);
                        }
                        a.put("aliases", ala);
                    } else { //no symbol found
                        a.put("status", "invalid");
                        //                     System.out.println("Symbol:"+symbol+"\t"+ "Invalid symbol or not in the database."+"\n");   
                    }
                }
                aliases.add(a);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return aliases.toString();
}

From source file:hoot.services.controllers.ingest.CustomScriptResource.java

/**
 * <NAME>Custom Script Service Delete Script</NAME>
 * <DESCRIPTION>Deletes the specified script.</DESCRIPTION>
 * <PARAMETERS>/*  www  .  j av a2s.c  o m*/
 * <SCRIPT_NAME>
 * Name of the script to delete.
 * </SCRIPT_NAME>
 * </PARAMETERS>
 * <OUTPUT>
 *    JSON Array containing JSON of name and description of deleted scripts
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/ingest/customscript/deletescript?SCRIPT_NAME=My Test6</URL>
 *    <REQUEST_TYPE>GET</REQUEST_TYPE>
 *    <INPUT>
 * </INPUT>
 * <OUTPUT>
 * [{"NAME":"My Test6","DESCRIPTION":"my description"}]
 * </OUTPUT>
 * </EXAMPLE>
* @param scriptName
* @return
*/
@GET
@Path("/deletescript")
@Produces(MediaType.TEXT_PLAIN)
public Response deleteScript(@QueryParam("SCRIPT_NAME") final String scriptName) {
    JSONArray delArr = new JSONArray();
    try {
        List<File> files = getFilesInScriptDir();
        if (files == null) {
            throw new Exception("Script directory does not exist.");
        }

        for (int i = 0; i < files.size(); i++) {
            try {
                File f = files.get(i);
                String content = FileUtils.readFileToString(f, "UTF-8");
                JSONObject oScript = getScriptObject(content);

                if (oScript != null) {
                    JSONObject header = (JSONObject) oScript.get("HEADER");
                    if (header.get("NAME").toString().equalsIgnoreCase(scriptName)) {
                        delArr.add(header);
                        f.delete();
                        break;
                    }
                }
            } catch (Exception e) {
                log.error("Failed to read file header: " + e.getMessage());
            }
        }
    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Error deleting script: " + scriptName + " Error: " + ex.getMessage(),
                Status.INTERNAL_SERVER_ERROR, log);
    }

    return Response.ok(delArr.toString(), MediaType.TEXT_PLAIN).build();
}

From source file:de.themoep.chestshoptools.ShopInfoCommand.java

public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
    if (args.length > 0) {
        return false;
    }/*from   w  w w. ja  va2 s.com*/
    if (!(sender instanceof Player)) {
        sender.sendMessage(ChatColor.RED + "This command can only be run by a player!");
        return true;
    }
    Block lookingAt = ((Player) sender).getTargetBlock((Set<Material>) null, 10);
    if (lookingAt == null) {
        sender.sendMessage(
                ChatColor.RED + "Please look at a shop sign or chest!" + ChatColor.DARK_GRAY + " (0)");
        return true;
    }
    Sign shopSign = null;
    if (lookingAt.getState() instanceof Chest) {
        shopSign = uBlock.getConnectedSign((Chest) lookingAt.getState());
    } else if (lookingAt.getState() instanceof Sign && ChestShopSign.isValid(lookingAt)) {
        shopSign = (Sign) lookingAt.getState();
    }
    if (shopSign == null) {
        sender.sendMessage(
                ChatColor.RED + "Please look at a shop sign or chest!" + ChatColor.DARK_GRAY + " (1)");
        return true;
    }

    String name = shopSign.getLine(ChestShopSign.NAME_LINE);
    String quantity = shopSign.getLine(ChestShopSign.QUANTITY_LINE);
    String prices = shopSign.getLine(ChestShopSign.PRICE_LINE);
    String material = shopSign.getLine(ChestShopSign.ITEM_LINE);

    String ownerName = NameManager.getFullNameFor(NameManager.getUUIDFor(name));
    ItemStack item = MaterialUtil.getItem(material);

    if (item == null || !NumberUtil.isInteger(quantity)) {
        sender.sendMessage(Messages.prefix(Messages.INVALID_SHOP_DETECTED));
        return true;
    }

    sender.sendMessage(Messages.prefix(ChatColor.GREEN + "Besitzer: " + ChatColor.WHITE + ownerName));
    if (plugin.getShowItem() == null) {
        sender.sendMessage(Messages.prefix(ChatColor.GREEN + "Item: " + ChatColor.WHITE + material));
    } else {
        String itemJson = plugin.getShowItem().getItemConverter().itemToJson(item, Level.FINE);

        String icon = "";
        if (plugin.getShowItem().useIconRp()) {
            icon = plugin.getShowItem().getIconRpMap().getIcon(item, true);
        }

        JSONArray textJson = new JSONArray();

        textJson.add(new JSONObject(ImmutableMap.of("text", Messages.prefix(ChatColor.GREEN + "Item: "))));

        JSONObject hoverJson = new JSONObject();
        hoverJson.put("action", "show_item");
        hoverJson.put("value", itemJson);
        ChatColor nameColor = plugin.getShowItem().getItemConverter().getNameColor(item);

        if (plugin.getShowItem().useIconRp()) {
            JSONObject iconJson = new JSONObject();
            iconJson.put("text", icon);
            iconJson.put("hoverEvent", hoverJson);

            textJson.add(iconJson);
        }

        JSONObject typeJson = new JSONObject();
        typeJson.put("translate", plugin.getShowItem().getItemConverter().getTranslationKey(item));
        JSONArray translateWith = new JSONArray();
        translateWith.addAll(plugin.getShowItem().getItemConverter().getTranslateWith(item));
        if (!translateWith.isEmpty()) {
            typeJson.put("with", translateWith);
        }

        typeJson.put("hoverEvent", hoverJson);
        typeJson.put("color", nameColor.name().toLowerCase());

        textJson.add(typeJson);

        String itemName = plugin.getShowItem().getItemConverter().getCustomName(item);
        if (!itemName.isEmpty()) {
            textJson.add(new JSONObject(ImmutableMap.of("text", ": ", "color", "green")));

            JSONObject nameJson = new JSONObject();
            nameJson.put("text", itemName);
            nameJson.put("hoverEvent", hoverJson);
            nameJson.put("color", nameColor.name().toLowerCase());

            textJson.add(nameJson);
        }

        plugin.getShowItem().tellRaw((Player) sender, textJson.toString());
    }
    sender.sendMessage(Messages.prefix(ChatColor.GREEN + "Anzahl: " + ChatColor.WHITE + quantity));
    sender.sendMessage(Messages.prefix(ChatColor.GREEN + "Preis: " + ChatColor.WHITE + prices));

    return true;
}

From source file:com.mobicage.rogerthat.registration.RegistrationActivity2.java

@SuppressWarnings("unchecked")
private void postFinishRegistration(final String username, final String password, final String invitorCode,
        final String invitorSecret) throws ClientProtocolException, IOException {
    T.REGISTRATION();/*from  w ww. ja va 2  s .c  o  m*/
    final String mobileInfo = getMobileInfo();
    HttpClient httpClient = HTTPUtil.getHttpClient();
    final HttpPost httpPost = new HttpPost(CloudConstants.REGISTRATION_FINISH_URL);
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    List<NameValuePair> formParams = new ArrayList<NameValuePair>();
    formParams.add(new BasicNameValuePair("mobileInfo", mobileInfo));
    formParams.add(new BasicNameValuePair("account", username));
    formParams.add(new BasicNameValuePair("password", password));
    formParams.add(new BasicNameValuePair("app_id", CloudConstants.APP_ID));
    org.json.simple.JSONArray accounts = new org.json.simple.JSONArray();
    if (mAccounts != null) {
        for (Account acc : mAccounts) {
            Map<String, String> jacc = new LinkedHashMap<String, String>();
            jacc.put("type", acc.type);
            jacc.put("name", acc.name);
            accounts.add(jacc);
        }
    }
    formParams.add(new BasicNameValuePair("accounts", accounts.toString()));

    formParams.add(new BasicNameValuePair("invitor_code", invitorCode));
    formParams.add(new BasicNameValuePair("invitor_secret", invitorSecret));

    org.json.simple.JSONArray beacons = new org.json.simple.JSONArray();
    for (BeaconDiscoveredRequestTO bdr : mWiz.getDetectedBeacons()) {
        beacons.add(bdr.toJSONMap());
    }
    formParams.add(new BasicNameValuePair("beacons", beacons.toString()));

    httpPost.setEntity(new UrlEncodedFormEntity(formParams, HTTP.UTF_8));
    L.d("before http final post");
    HttpResponse response = httpClient.execute(httpPost);
    L.d("after http final post");
    final int responseCode = response.getStatusLine().getStatusCode();
    if (responseCode != HttpStatus.SC_OK) {
        throw new IOException("HTTP request resulted in status code " + responseCode);
    }

    L.d("finish_registration call sent");
    HttpEntity httpEntity = response.getEntity();
    if (httpEntity == null) {
        throw new IOException("Response of '/unauthenticated/mobi/registration/finish' was null");
    }

    final Map<String, Object> responseMap = (Map<String, Object>) JSONValue
            .parse(new InputStreamReader(httpEntity.getContent()));
    if (responseMap == null) {
        throw new IOException("HTTP request responseMap was null");
    }

    JSONArray beaconRegions = (JSONArray) responseMap.get("discovered_beacons");
    if (beaconRegions != null && beaconRegions.size() > 0) {
        mDiscoveredBeacons = JSONValue.toJSONString(beaconRegions);
    } else {
        mDiscoveredBeacons = null;
    }
}

From source file:com.caspida.plugins.graph.EntityGraphNeo4jPlugin.java

@Name(EntityGraphConstants.API_GET_USER_PST)
@Description("Get a users's PST model")
@PluginTarget(GraphDatabaseService.class)
public String getUserPst(@Source GraphDatabaseService graphDb,
        @Description("user id ") @Parameter(name = "userId") String userId) {
    JSONArray nodes = new JSONArray();
    Node node = null;/* w w  w .jav  a2s .co  m*/
    Label pstLabel = DynamicLabel.label("PST___Root");

    logger.error("Got user id {}", userId);

    try (Transaction txn = graphDb.beginTx()) {

        // find the node
        // use the label first
        ResourceIterable<Node> iterableNodes = graphDb.findNodesByLabelAndProperty(pstLabel,
                EntityGraphConstants.REQ_USER_ID_TAG, userId);
        if (iterableNodes != null) {
            ResourceIterator<Node> it = iterableNodes.iterator();
            if (it.hasNext()) {
                node = it.next();
            }
        }
        logger.debug("Found node {}", node);

        if (node == null) {
            logger.error("Can not find node with id {}", userId);
            return nodes.toString();
        }

        Iterable<Relationship> rels = node.getRelationships();
        for (Relationship rel : rels) {
            Node childNode = (rel.getStartNode().getId() == node.getId()) ? rel.getEndNode()
                    : rel.getStartNode();
            Object key = childNode.getProperty(EntityGraphConstants.NODE_NAME);
            if (key == null) {
                continue;
            }

            JSONObject childInfo = walkPSTGraph(childNode, node, rel);

            if (childInfo != null) {
                nodes.add(childInfo);
            }
        }
    }
    return nodes.toJSONString();
}

From source file:gov.nih.nci.caintegrator.application.lists.ajax.CommonListFunctions.java

public static String getAllLists(List<String> listTypeList) {

    UserListBeanHelper helper = new UserListBeanHelper();
    JSONArray listContainerArray = new JSONArray();
    for (String listType : listTypeList) {
        Collection<String> myLists = new ArrayList<String>();

        JSONObject listContainer = new JSONObject();

        JSONArray myJSONLists = new JSONArray();

        listContainer.put("listType", listType);
        //which do we want to display differently in the UI

        myLists = helper.getGenericListNames(ListType.valueOf(listType));

        for (String listName : myLists) {
            UserList ul = helper.getUserList(listName);
            DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm aaa", Locale.US);
            if (ul != null) {
                String listSubType = "";
                if (ul.getListSubType() != null) {
                    listSubType = "Subtype: " + ul.getListSubType().toString() + " - ";
                }//  w ww  .j av a2  s.  c  o m

                JSONObject jsonListName = new JSONObject();
                String listNotes = ul.getNotes();
                if (ul.getNotes() != null) {
                    if (listNotes.length() > 100) {
                        listNotes = listNotes.substring(0, 99);
                    }
                }

                String style = "";
                if (ul.getListOrigin() != null) {
                    jsonListName.put("origin", ul.getListOrigin().toString());
                    if (ul.getListOrigin().equals(ListOrigin.Default)) {
                        style = "color:#000000";
                        jsonListName.put("highlightType", style);
                    }
                    if (ul.getListOrigin().equals(ListOrigin.Custom)) {
                        style = "color:#A90101";
                        jsonListName.put("highlightType", style);
                    }

                } else {
                    jsonListName.put("highlightType", style);
                }

                jsonListName.put("author", ul.getAuthor());

                jsonListName.put("notes", listNotes);

                jsonListName.put("listSubType", listSubType);
                jsonListName.put("listName", ul.getName());
                if (ul.getDateCreated() != null) {
                    jsonListName.put("listDate", dateFormat.format(ul.getDateCreated()).toString());
                }
                jsonListName.put("itemCount", String.valueOf(ul.getItemCount()));
                jsonListName.put("invalidItems", String.valueOf(ul.getInvalidList().size()));

                String commas = StringUtils.join(ul.getList().toArray(), ", ");
                jsonListName.put("listItems", commas);
                myJSONLists.add(jsonListName);
            }

        }
        listContainer.put("listItems", myJSONLists);
        listContainerArray.add(listContainer);
    }
    return listContainerArray.toString();
}

From source file:com.caspida.plugins.graph.EntityGraphNeo4jPlugin.java

@Name(EntityGraphConstants.API_GET_ENTITY_PST)
@Description("Get an entity's PST model")
@PluginTarget(GraphDatabaseService.class)
public String getEntityPst(@Source GraphDatabaseService graphDb,
        @Description("entity id and entity type") @Parameter(name = "entityId") String entityId,
        @Parameter(name = "entityType") String entityType) {
    JSONArray nodes = new JSONArray();
    Node node = null;/*  ww  w .j  a va2s.c o m*/
    Label pstLabel = DynamicLabel.label("PST___Root");

    logger.error("Got entity id {}", entityId);

    String property = EntityGraphConstants.REQ_USER_ID_TAG;
    logger.error("Got property  {}", property);

    try (Transaction txn = graphDb.beginTx()) {

        // find the node
        // use the label first
        ResourceIterable<Node> iterableNodes = graphDb.findNodesByLabelAndProperty(pstLabel, property,
                entityId);
        if (iterableNodes != null) {
            ResourceIterator<Node> it = iterableNodes.iterator();
            if (it.hasNext()) {
                node = it.next();
            }
        }
        logger.debug("Found node {}", node);

        if (node == null) {
            logger.error("Can not find node with id {}", entityId);
            return nodes.toString();
        }

        Iterable<Relationship> rels = node.getRelationships();
        for (Relationship rel : rels) {
            Node childNode = (rel.getStartNode().getId() == node.getId()) ? rel.getEndNode()
                    : rel.getStartNode();
            Object key = childNode.getProperty(EntityGraphConstants.NODE_NAME);
            if (key == null) {
                continue;
            }

            JSONObject childInfo = walkPSTGraph(childNode, node, rel);

            if (childInfo != null) {
                nodes.add(childInfo);
            }
        }
    }
    return nodes.toJSONString();
}

From source file:gov.nih.nci.ispy.web.ajax.IdLookup.java

public String lookup(String ids) {

    String results = "";
    //clean the input and validate
    String inputString = ids.trim().replace(" ", "");
    String[] st = StringUtils.split(inputString, ",");
    //construct the inputlist
    List<String> inputList = new ArrayList<String>();
    inputList = Arrays.asList(st);

    //pass the input list to the service
    List<RegistrantInfo> entries = idMapper.getMapperEntriesForIds(inputList);

    //process the results for return to presentation
    //Document document = DocumentHelper.createDocument();
    //Element container = document.addElement("div");

    JSONArray regs = new JSONArray(); //make an array of registrants
    regs.add(inputString);//from www.ja v  a 2 s  .c om

    //Element report = document.addElement( "table" ).addAttribute("name", inputString);
    for (RegistrantInfo entry : entries) {
        //Element reg = report.addElement( "registrant" ).addAttribute("regId", entry.getRegistrationId());

        //for each registrant make an array of samples
        JSONArray sams = new JSONArray();

        for (SampleInfo sampleInfo : entry.getAssociatedSamples()) {

            JSONObject sam = new JSONObject();
            sam.put("regId", entry.getRegistrationId());
            sam.put("labtrackId", sampleInfo.getLabtrackId());
            sam.put("timePoint", String.valueOf(sampleInfo.getTimepoint()));
            sam.put("coreType", String.valueOf(sampleInfo.getCoreType()));
            sam.put("sectionInfo", String.valueOf(sampleInfo.getSectionInfo()));

            /*
            Element row = reg.addElement( "sample" );
                    
            Element cell = row.addElement( "regId" );
                    
            cell.addText(entry.getRegistrationId());
              cell = null;
            cell = row.addElement( "labtrackId" );
            cell.addText(sampleInfo.getLabtrackId());
              cell = null;
            cell = row.addElement( "timePoint" );
            cell.addText(String.valueOf(sampleInfo.getTimepoint()));
              cell = null;
            cell = row.addElement( "coreType" );
            cell.addText(String.valueOf(sampleInfo.getCoreType()));
              cell = null;
            cell = row.addElement( "sectionInfo" );
            cell.addText(String.valueOf(sampleInfo.getSectionInfo()));
                    
            */

            sams.add(sam);
        }

        regs.add(sams);
    }

    /*
    for (RegistrantInfo entry:entries) {
       results += "[\"" + entry.getRegistrationId() + "\"," ;
       for(SampleInfo sampleInfo : entry.getAssociatedSamples())   {
            
       }         
    }
    */

    //return document;
    return regs.toString();

}

From source file:hoot.services.controllers.ingest.CustomScriptResource.java

/**
 * <NAME>Custom Script Service Get Scripts List</NAME>
 * <DESCRIPTION>Gets the list of available scripts.</DESCRIPTION>
 * <PARAMETERS>//w ww . j a va 2  s  .  c  o  m
 * </PARAMETERS>
 * <OUTPUT>
 *    JSON Array containing JSON of name and description of all available scripts
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/ingest/customscript/getlist</URL>
 *    <REQUEST_TYPE>GET</REQUEST_TYPE>
 *    <INPUT>
 * </INPUT>
 * <OUTPUT>[{"NAME":"MyTest","DESCRIPTION":"my description"}]</OUTPUT>
 * </EXAMPLE>
* @return
*/
@GET
@Path("/getlist")
@Produces(MediaType.TEXT_PLAIN)
public Response getScriptsList() {

    JSONArray retList = new JSONArray();
    Map<String, JSONObject> sortedScripts = new TreeMap<String, JSONObject>();
    JSONArray filesList = new JSONArray();

    try {
        File scriptsDir = new File(scriptFolder);
        if (scriptsDir.exists()) {
            String[] exts = new String[1];
            exts[0] = "js";
            List<File> files = (List<File>) FileUtils.listFiles(scriptsDir, exts, false);

            for (int i = 0; i < files.size(); i++) {
                File f = files.get(i);
                String content = FileUtils.readFileToString(f, "UTF-8");
                JSONObject oScript = getScriptObject(content);

                if (oScript != null) {
                    JSONObject header = (JSONObject) oScript.get("HEADER");
                    if (header.get("CANEXPORT") == null) {
                        boolean canExport = validateExport(oScript.get("BODY").toString());
                        header.put("CANEXPORT", canExport);
                    }
                    filesList.add(header);
                }
            }
        }
        filesList.addAll(_getDefaultList());

        // sort the list
        for (Object o : filesList) {
            JSONObject cO = (JSONObject) o;
            String sName = cO.get("NAME").toString();
            sortedScripts.put(sName.toUpperCase(), cO);
        }

        retList.addAll(sortedScripts.values());

    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Error getting scripts list: " + ex.getMessage(),
                Status.INTERNAL_SERVER_ERROR, log);
    }

    return Response.ok(retList.toString(), MediaType.TEXT_PLAIN).build();
}

From source file:com.mycompany.demos.Servlet2.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Set response content type
    //response.setContentType("text/html");

    // Actual logic goes here.
    //      PrintWriter out = response.getWriter();
    //      out.println( "test");
    String[][] info = new String[5][];

    for (int i = 0; i < 5; i++) {
        info[i] = request.getParameterValues("data[" + i + "][]");

    }/* w  ww  .j  av a 2s .  c om*/

    double[][] coordinates = new double[5][2];
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 2; j++) {
            System.out.println(info[i][j]);
            coordinates[i][j] = Double.parseDouble(info[i][j]);

        }
        System.out.print("\n");
    }

    VehicleType type = VehicleTypeImpl.Builder.newInstance("type").addCapacityDimension(0, 2).build();
    VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle").setStartLocation(Location.newInstance("0"))
            .setType(type).setReturnToDepot(true).build();

    Service[] services = new Service[5];
    for (int i = 0; i < 4; i++) {
        services[i] = Service.Builder.newInstance(Integer.toString(i + 1)).addSizeDimension(0, 0)
                .setLocation(Location.newInstance(Integer.toString(i + 1))).build();
    }

    GHRequest Grequest = null;
    GHResponse route = null;
    double[][] DistanceMatrix = new double[5][5];

    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            Grequest = new GHRequest(Double.parseDouble(info[i][0]), Double.parseDouble(info[i][1]),
                    Double.parseDouble(info[j][0]), Double.parseDouble(info[j][1]));
            Grequest.setWeighting("fastest");
            Grequest.setVehicle("car");
            route = graphHopper.route(Grequest);
            try (PrintWriter out = new PrintWriter(
                    "C:\\Users\\panikas\\Desktop\\diploma\\code\\Demos\\target\\Demos-1.0-SNAPSHOT\\file" + i
                            + j + ".gpx")) {
                out.print(route.getBest().getInstructions().createGPX("Graphhopper", new Date().getTime(),
                        false, false, true, false));
            } catch (FileNotFoundException ex) {
                System.out.println("exception filenotfound");
            }
            DistanceMatrix[i][j] = route.getBest().getDistance();

        }
    }

    VehicleRoutingTransportCostsMatrix.Builder costMatrixBuilder = VehicleRoutingTransportCostsMatrix.Builder
            .newInstance(false);
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            //costMatrixBuilder.addTransportTime(Integer.toString(i), Integer.toString(j), dMatrixtime[i][j]);
            costMatrixBuilder.addTransportDistance(Integer.toString(i), Integer.toString(j),
                    DistanceMatrix[i][j]);
        }
    }

    VehicleRoutingTransportCosts costMatrix = costMatrixBuilder.build();
    VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
    vrpBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE).setRoutingCost(costMatrix)
            .addVehicle(vehicle);
    for (int i = 0; i < 4; i++) {
        vrpBuilder.addJob(services[i]);
    }

    VehicleRoutingProblem vrp = vrpBuilder.build();
    VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp);
    Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
    SolutionPrinter.print(vrp, Solutions.bestOf(solutions), SolutionPrinter.Print.VERBOSE);

    int i;
    int j;
    int counter = 0;
    JSONObject point;
    JSONArray tspRoute = new JSONArray();
    for (VehicleRoute jroute : Solutions.bestOf(solutions).getRoutes()) {
        TourActivity prevAct = jroute.getStart();
        //            System.out.println(prevAct.getLocation().getId());
        for (TourActivity act : jroute.getActivities()) {
            i = Integer.parseInt(prevAct.getLocation().getId());
            j = Integer.parseInt(act.getLocation().getId());
            point = new JSONObject();
            point.put("id", i);
            //System.out.println(prevAct.getLocation());
            //                System.out.println(Integer.parseInt(act.getLocation().getId()));

            Grequest = new GHRequest(coordinates[i][0], coordinates[i][1], coordinates[j][0],
                    coordinates[j][1]);
            Grequest.setWeighting("fastest");
            Grequest.setVehicle("car");
            route = graphHopper.route(Grequest);
            System.out.println(counter);
            try (PrintWriter out = new PrintWriter(
                    "C:\\Users\\panikas\\Desktop\\diploma\\code\\Demos\\target\\Demos-1.0-SNAPSHOT\\file"
                            + counter + ".gpx")) {
                out.print(route.getBest().getInstructions().createGPX("Graphhopper", new Date().getTime(),
                        false, false, true, false));
            } catch (FileNotFoundException ex) {
                System.out.println("exception filenotfound");
            }
            prevAct = act;
            counter++;
            tspRoute.add(point);
        }
        //             System.out.println(jroute.getEnd().getLocation().getId());
        i = Integer.parseInt(prevAct.getLocation().getId());
        j = Integer.parseInt(jroute.getEnd().getLocation().getId());

        point = new JSONObject();
        point.put("id", i);
        tspRoute.add(point);

        Grequest = new GHRequest(coordinates[i][0], coordinates[i][1], coordinates[j][0], coordinates[j][1]);
        Grequest.setWeighting("fastest");
        Grequest.setVehicle("car");
        route = graphHopper.route(Grequest);
        System.out.println(counter);
        try (PrintWriter out = new PrintWriter(
                "C:\\Users\\panikas\\Desktop\\diploma\\code\\Demos\\target\\Demos-1.0-SNAPSHOT\\file" + counter
                        + ".gpx")) {
            out.print(route.getBest().getInstructions().createGPX("Graphhopper", new Date().getTime(), false,
                    false, true, false));
        } catch (FileNotFoundException ex) {
            System.out.println("exception filenotfound");
        }
        counter++;
    }

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(tspRoute.toString());

    System.out.println("done");

}