Example usage for org.json XML toJSONObject

List of usage examples for org.json XML toJSONObject

Introduction

In this page you can find the example usage for org.json XML toJSONObject.

Prototype

public static JSONObject toJSONObject(String string) throws JSONException 

Source Link

Document

Convert a well-formed (but not necessarily valid) XML string into a JSONObject.

Usage

From source file:org.zaproxy.zap.extension.exportreport.Export.ReportExport.java

public static File JSON_EXPORT(ViewDelegate view, Logger logger, String absolutePath, String p_result,
        String p_source) {/*w  w w . j a  v a  2 s .co m*/
    int PRETTY_PRINT_INDENT_FACTOR = 4;

    File fXmlFile = new File(p_source);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = null;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        logger.error(e.getMessage(), e);
        view.showWarningDialog(Constant.messages.getString("exportreport.message.error.parser"));
    }
    Document doc = null;
    try {
        doc = dBuilder.parse(fXmlFile);
    } catch (SAXException e) {
        logger.error(e.getMessage(), e);
        view.showWarningDialog(Constant.messages.getString("exportreport.message.error.sax"));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        view.showWarningDialog(Constant.messages.getString("exportreport.message.error.io"));
    }
    String temp = getStringFromDoc(doc);
    String jsonPrettyPrintString = null;
    try {
        JSONObject xmlJSONObj = XML.toJSONObject(temp);
        jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
    } catch (JSONException e) {
        logger.error(e.getMessage(), e);
        view.showWarningDialog(Constant.messages.getString("exportreport.message.error.json"));
    }
    File f = null;
    try {
        f = write(p_result, jsonPrettyPrintString, false);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        view.showWarningDialog(Constant.messages.getString("exportreport.message.error.exception"));
    }
    return f;
}

From source file:org.entando.entando.plugins.jptrello.aps.system.services.trello.TrelloConfig.java

public TrelloConfig(String xml) {
    if (StringUtils.isNotBlank(xml)) {
        JSONObject json = XML.toJSONObject(xml);
        json = json.getJSONObject(CONFIG_ROOT);

        if (json.has(CONFIG_ORGANIZATION)) {
            _organization = json.getString(CONFIG_ORGANIZATION);
        }/* w  w w.  j ava 2  s .co  m*/
        if (json.has(CONFIG_KEY)) {
            _apiKey = json.getString(CONFIG_KEY);
        }
        if (json.has(CONFIG_SECRET)) {
            _apiSecret = json.getString(CONFIG_SECRET);
        }
        if (json.has(CONFIG_TOKEN)) {
            _token = json.getString(CONFIG_TOKEN);
        }
    }
}

From source file:com.serendio.streaming.StreamingService.java

@Listener({ "/service/itb" })
protected void handleItbMessage(final ServerSession client, final ServerMessage message) {
    //System.out.println("handle itb a service message " + this.toString());
    //System.out.println("Arg session is " + client.toString());
    //System.out.println("Member server session is "+ _session.toString());
    //System.out.println("Member server local session is "+ _session.getLocalSession().toString());
    //System.out.println("is arg local session " + client.isLocalSession());
    //System.out.println("is member server local session " + _session.isLocalSession());

    System.out.println("Publish Message " + "\"" + message.toString() + "\", from client \"" + client.getId()
            + "\", server \"" + _session.getId() + "\" on threadId " + Thread.currentThread().getId());

    handleMembership(client, message);// w  w w  . j a va2  s.c  o  m

    new Thread() {
        public void run() {
            boolean HBase = true;

            Map<String, Object> data = message.getDataAsMap();
            String exp = (String) data.get("phrase");

            // Default settings
            String type = (String) (data.get("type") != null ? data.get("type") : "json");
            int resultLimit = data.get("limit") != null ? Integer.valueOf((String) data.get("limit")) : 10;
            int delay = data.get("delay") != null ? Integer.valueOf((String) data.get("delay")) : 2;
            int validity = data.get("validity") != null ? Integer.valueOf((String) data.get("validity")) : 0;

            if (delay < 0) {
                System.out.println("Delay value can't negative, passed val is  " + delay);
                return;
            }

            if (HBase) {
                // TODO Hard coded the table name for now
                SearchHBase search = new SearchHBase("test");
                List<Map<String, Object>> posts = search.searchByExpression(exp, resultLimit, type, validity);
                if (posts.size() != 0) {
                    for (Map<String, Object> post : posts) {
                        try {
                            if (delay > 0) {
                                deliverMessage(client, message, post);
                                Thread.sleep(delay * 1000);
                            }
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                } else {
                    // When no post is found.
                    deliverMessage(client, message, null);
                }
            } else {
                String output = "<Sentiment_Analysis> <language>en</language>"
                        + "<product_name>ford focus</product_name>" + "<weighted_score>0</weighted_score>"
                        + "<unweighted_score>0</unweighted_score>" + "<Features>" + "<feature>"
                        + "<feature_name>unknown feature</feature_name>" + "<sentiment>positive</sentiment>"
                        + "<negative_probability>0</negative_probability>" + "<negative_words/>"
                        + "<positive_probability>1</positive_probability>"
                        + "<positive_words>sentimentword, pleas</positive_words>" + "</feature>" + "</Features>"
                        + "<timestamp>" + "<exit_timestamp>15:25:57.356957</exit_timestamp>"
                        + "<start_timestamp>15:25:57.321322</start_timestamp>"
                        + "<elapsed_time>35635</elapsed_time>" + "</timestamp>"
                        + "<ElapsedTime>483.0 msec</ElapsedTime>" + "</Sentiment_Analysis>";
                Map<String, Object> post = new HashMap<String, Object>();
                if (!type.equalsIgnoreCase("json")) {
                    post.put("Sentiment_Analysis", output);
                } else {
                    try {
                        post.put("Sentiment_Analysis", XML.toJSONObject(output));
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                deliverMessage(client, message, post);
            }
        }
    }.start();

}

From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java

/**
 * MetaWeblog requests processing./* w  w  w. j  av  a 2  s.c  om*/
 * 
 * @param request the specified http servlet request
 * @param response the specified http servlet response
 * @param context the specified http request context
 */
@RequestProcessing(value = "/apis/metaweblog", method = HTTPRequestMethod.POST)
public void metaWeblog(final HttpServletRequest request, final HttpServletResponse response,
        final HTTPRequestContext context) {
    final TextXMLRenderer renderer = new TextXMLRenderer();
    context.setRenderer(renderer);

    String responseContent = null;
    try {
        final ServletInputStream inputStream = request.getInputStream();
        final String xml = IOUtils.toString(inputStream, "UTF-8");
        final JSONObject requestJSONObject = XML.toJSONObject(xml);

        final JSONObject methodCall = requestJSONObject.getJSONObject(METHOD_CALL);
        final String methodName = methodCall.getString(METHOD_NAME);
        LOGGER.log(Level.INFO, "MetaWeblog[methodName={0}]", methodName);

        final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param");

        if (METHOD_DELETE_POST.equals(methodName)) {
            params.remove(0); // Removes the first argument "appkey"
        }

        final String userEmail = params.getJSONObject(INDEX_USER_EMAIL).getJSONObject("value")
                .getString("string");
        final JSONObject user = userQueryService.getUserByEmail(userEmail);
        if (null == user) {
            throw new Exception("No user[email=" + userEmail + "]");
        }

        final String userPwd = params.getJSONObject(INDEX_USER_PWD).getJSONObject("value").getString("string");
        if (!user.getString(User.USER_PASSWORD).equals(userPwd)) {
            throw new Exception("Wrong password");
        }

        if (METHOD_GET_USERS_BLOGS.equals(methodName)) {
            responseContent = getUsersBlogs();
        } else if (METHOD_GET_CATEGORIES.equals(methodName)) {
            responseContent = getCategories();
        } else if (METHOD_GET_RECENT_POSTS.equals(methodName)) {
            final int numOfPosts = params.getJSONObject(INDEX_NUM_OF_POSTS).getJSONObject("value")
                    .getInt("int");
            responseContent = getRecentPosts(numOfPosts);
        } else if (METHOD_NEW_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail);
            addArticle(article);

            final StringBuilder stringBuilder = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><string>")
                            .append(article.getString(Keys.OBJECT_ID))
                            .append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_GET_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value")
                    .getString("string");
            responseContent = getPost(postId);
        } else if (METHOD_EDIT_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value")
                    .getString("string");
            article.put(Keys.OBJECT_ID, postId);

            article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail);
            final JSONObject updateArticleRequest = new JSONObject();
            updateArticleRequest.put(Article.ARTICLE, article);
            articleMgmtService.updateArticle(updateArticleRequest);

            final StringBuilder stringBuilder = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><string>")
                            .append(postId).append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_DELETE_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value")
                    .getString("string");
            articleMgmtService.removeArticle(postId);

            final StringBuilder stringBuilder = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><boolean>")
                            .append(true).append("</boolean></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else {
            throw new UnsupportedOperationException("Unsupported method[name=" + methodName + "]");
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);

        responseContent = "";
        final StringBuilder stringBuilder = new StringBuilder(
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><fault><value><struct>")
                        .append("<member><name>faultCode</name><value><int>500</int></value></member>")
                        .append("<member><name>faultString</name><value><string>").append(e.getMessage())
                        .append("</string></value></member></struct></value></fault></methodResponse>");
        responseContent = stringBuilder.toString();
    }

    renderer.setContent(responseContent);
}

From source file:org.loklak.api.iot.NOAAAlertServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Query post = RemoteAccess.evaluate(request);

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;//  w ww.  j  av a2  s  .c o  m
    }

    String content = new String(Files.readAllBytes(Paths.get(DAO.conf_dir + "/iot/scripts/counties.xml")));
    try {
        // Conversion of the XML Layers through PERL into the required JSON for well structured XML
        /*
        <resources>
        <string-array name="preference_county_entries_us">
            <item>Entire Country</item>
        </string-array>
        <string-array name="preference_county_entryvalues_us">
            <item>https://alerts.weather.gov/cap/us.php?x=0</item>
        </string-array>
        .
        .
        .
        Similarly every 2 DOM elements together in <resources> constitute a pair.
        </resources>
        */
        JSONObject json = XML.toJSONObject(content);
        PrintWriter sos = response.getWriter();
        JSONObject resourceObject = json.getJSONObject("resources");
        JSONArray stringArray = resourceObject.getJSONArray("string-array");
        JSONObject result = new JSONObject(true);

        // Extract and map the itemname and the url strings
        /*
        {
        "item": "Entire Country",
        "name": "preference_county_entries_us"
        },
        {
        "item": "https://alerts.weather.gov/cap/us.php?x=0",
        "name": "preference_county_entryvalues_us"
        }
        */
        for (int i = 0; i < stringArray.length(); i += 2) {
            JSONObject keyJSONObject = stringArray.getJSONObject(i);
            JSONObject valueJSONObject = stringArray.getJSONObject(i + 1);
            Object kItemObj = keyJSONObject.get("item");
            Object vItemObj = valueJSONObject.get("item");

            // Since instances are variable, we need to check if they're Arrays or Strings
            // The processing for the Key : Value mappings will change for each type of instance
            if (kItemObj instanceof JSONArray) {
                if (vItemObj instanceof JSONArray) {
                    JSONArray kArray = keyJSONObject.getJSONArray("item");
                    JSONArray vArray = valueJSONObject.getJSONArray("item");
                    for (int location = 0; location < kArray.length(); location++) {
                        String kValue = kArray.getString(location);
                        String vValue = vArray.getString(location);
                        result.put(kValue, vValue);
                    }
                }
            } else {
                // They are plain strings
                String kItemValue = keyJSONObject.getString("item");
                String vItemValue = valueJSONObject.getString("item");
                result.put(kItemValue, vItemValue);
            }

        }
        // Sample response in result has to be something like
        /*
        {
        "Entire Country": "https://alerts.weather.gov/cap/us.php?x=0",
        "Entire State": "https://alerts.weather.gov/cap/wy.php?x=0",
        "Autauga": "https://alerts.weather.gov/cap/wwaatmget.php?x=ALC001&y=0",
        "Baldwin": "https://alerts.weather.gov/cap/wwaatmget.php?x=GAC009&y=0",
        "Barbour": "https://alerts.weather.gov/cap/wwaatmget.php?x=WVC001&y=0",
        "Bibb": "https://alerts.weather.gov/cap/wwaatmget.php?x=GAC021&y=0",
        .
        .
        .
        And so on.
        }
        */

        sos.print(result.toString(2));
        sos.println();
    } catch (IOException e) {
        Log.getLog().warn(e);
        JSONObject json = new JSONObject(true);
        json.put("error", "Looks like there is an error in the conversion");
        json.put("type", "Error");
        PrintWriter sos = response.getWriter();
        sos.print(json.toString(2));
        sos.println();
    }

}

From source file:io.swagger.client.ApiClient.java

/**
 * Deserialize response body to Java object, according to the return type and
 * the Content-Type response header.//  w ww.j a v a  2 s.  com
 *
 * @param <T> Type
 * @param response HTTP response
 * @param returnType The type of the Java object
 * @return The deserialized Java object
 * @throws ApiException If fail to deserialize response body, i.e. cannot read response body
 *   or the Content-Type of the response is not supported.
 */
@SuppressWarnings("unchecked")
public <T> T deserialize(Response response, Type returnType) throws ApiException, IOException {
    if (response == null || returnType == null) {
        return null;
    }

    if ("byte[]".equals(returnType.toString())) {
        // Handle binary response (byte array).
        try {
            return (T) response.body().bytes();
        } catch (IOException e) {
            throw new ApiException(e);
        }
    } else if (returnType.equals(File.class)) {
        // Handle file downloading.
        return (T) downloadFileFromResponse(response);
    }

    String respBody;
    try {
        if (response.body() != null)
            respBody = response.body().string();
        else
            respBody = null;
    } catch (IOException e) {
        throw new ApiException(e);
    }

    if (respBody == null || "".equals(respBody)) {
        return null;
    }

    String contentType = response.headers().get("Content-Type");
    if (contentType == null) {
        // ensuring a default content type
        contentType = "application/json";
    } else if (contentType.equals("application/xml")) {
        if (XML.toJSONObject(respBody).has("TaskList")) {
            JSONObject rootElement = (JSONObject) XML.toJSONObject(respBody).get("TaskList");
            return this.json.deserialize(
                    ((JSONArray) ((JSONObject) rootElement.get("Tasks")).get("Tasks")).toString(), returnType);
        }
    }
    if (isJsonMime(contentType)) {
        if (new JSONObject(respBody).has("Tasks")) {
            return json.deserialize(new JSONObject(respBody).get("Tasks").toString(), returnType);
        } else {
            return json.deserialize(respBody, returnType);
        }
    } else if (returnType.equals(String.class)) {
        // Expecting string, return the raw response body.
        return (T) respBody;
    } else {
        throw new ApiException("Content type \"" + contentType + "\" is not supported for type: " + returnType,
                response.code(), response.headers().toMultimap(), respBody);
    }
}

From source file:edu.ucsd.ccdb.cil.xml2json.XML2JsonUtil.java

public String xml2Json(String xml) throws Exception {
    String jsonPrettyPrintString = "";
    try {/* w  ww .  j  a va2 s  . c o m*/
        JSONObject xmlJSONObj = XML.toJSONObject(xml);
        jsonPrettyPrintString = xmlJSONObj.toString();
        //System.out.println(jsonPrettyPrintString);
    } catch (JSONException je) {
        System.out.println(je.toString());
    }
    return jsonPrettyPrintString;
}

From source file:fi.csc.emrex.smp.model.VerifiedReport.java

public void setReport(String report) {
    //System.out.println(report);
    JSONObject json = XML.toJSONObject(report);
    //System.out.println(json.toString());
    this.report = json.toString();
}

From source file:dhbw.RaplaCalGenerator.HTMLCleaner.java

public ArrayList<Course> generateCourses(String location) {
    try {//w w w .  jav a  2  s.  c o  m

        head.add(html.indexOf("<head"));
        head.add(html.indexOf("/head") + 6);
        html.delete(head.get(0), head.get(1));
        int index = 0;
        while (html.indexOf("<br>", index) != -1) { //kill <br>
            int actualBr = html.indexOf("<br>");
            html.delete(actualBr, actualBr + 4);
            index = actualBr;
        }
        index = 0;
        while (html.indexOf("", index) != -1) { //kill <br>
            int actual = html.indexOf("");
            html.replace(actual, actual + 2, "");
            index = actual + 10;
            //System.out.println("Another  deleted: " + html.substring(actual - 5, actual +20));
        }
        index = 0;
        while (html.indexOf("", index) != -1) { //kill <br>
            int actual = html.indexOf("");
            html.replace(actual, actual + 2, "");
            index = actual + 10;
            //System.out.println("Another  deleted: " + html.substring(actual - 5, actual +20));
        }
        index = 0;
        while (html.indexOf("", index) != -1) { //kill <br>
            int actual = html.indexOf("");
            html.replace(actual, actual + 2, "");
            index = actual + 10;
            //System.out.println("Another  deleted: " + html.substring(actual - 5, actual +20));
        }
        JSONObject myJSON = XML.toJSONObject(html.toString());
        JSONArray coursesL1 = myJSON.getJSONObject("html").getJSONObject("body").getJSONArray("div")
                .getJSONObject(1).getJSONObject("table").getJSONObject("tbody").getJSONArray("tr");
        JSONObject itemsO = coursesL1.getJSONObject(4).getJSONArray("td").getJSONObject(0);
        //System.out.println(itemsO.keySet());
        for (int i = 2; i < coursesL1.length(); i++) {
            JSONArray tds = coursesL1.getJSONObject(i).getJSONArray("td");
            for (int j = 0; j < tds.length(); j++) {
                JSONObject entry = tds.getJSONObject(j);
                Set<String> contents = entry.keySet();
                if (contents.contains("a")) {
                    Course newCourse = new Course();
                    JSONObject actualCourse = entry.getJSONObject("a");

                    JSONArray courseContent = actualCourse.getJSONArray("content");
                    newCourse.setTitle(courseContent.getString(1));
                    String courseTimes = actualCourse.getJSONObject("span").getJSONArray("div").getString(1);
                    String[] splits = courseTimes.split(" ");
                    String day = splits[1].substring(0, 2);
                    String month = splits[1].substring(3, 5);
                    String year = splits[1].substring(6, 8);

                    String[] times = splits[2].split("-");
                    String[] startTime = times[0].split(":");
                    String[] endTime = times[1].split(":");
                    int i_day = Integer.parseInt(day);
                    int i_month = Integer.parseInt(month);
                    int i_year = Integer.parseInt(year) + 2000;
                    int i_startHours = Integer.parseInt(startTime[0]);
                    int i_startMinutes = Integer.parseInt(startTime[1]);
                    int i_endHours = Integer.parseInt(endTime[0]);
                    int i_endMinutes = Integer.parseInt(endTime[1]);
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm");
                    Date startDate = format.parse(
                            i_year + "-" + i_month + "-" + i_day + " " + i_startHours + "-" + i_startMinutes);
                    Date endDate = format.parse(
                            i_year + "-" + i_month + "-" + i_day + " " + i_endHours + "-" + i_endMinutes);
                    newCourse.setStartDate(startDate);
                    newCourse.setEndDate(endDate);
                    courses.add(newCourse);
                }
            }
        }
        return this.courses;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.portfolio.rest.RestServicePortfolio.java

@Path("/portfolios/portfolio/{portfolio-id}")
@GET// www.jav  a2s.  c  om
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "application/zip",
        MediaType.APPLICATION_OCTET_STREAM })
public Object getPortfolio(@CookieParam("user") String user, @CookieParam("credential") String token,
        @QueryParam("group") int groupId, @PathParam("portfolio-id") String portfolioUuid,
        @Context ServletConfig sc, @Context HttpServletRequest httpServletRequest,
        @HeaderParam("Accept") String accept, @QueryParam("user") Integer userId,
        @QueryParam("group") Integer group, @QueryParam("resources") String resource,
        @QueryParam("files") String files, @QueryParam("export") String export,
        @QueryParam("lang") String lang) {
    UserInfo ui = checkCredential(httpServletRequest, user, token, null);

    Response response = null;
    try {
        String portfolio = dataProvider.getPortfolio(new MimeType("text/xml"), portfolioUuid, ui.userId, 0,
                this.label, resource, "", ui.subId).toString();

        if ("faux".equals(portfolio)) {
            response = Response.status(403).build();
        }

        if (response == null) {
            Date time = new Date();
            Document doc = DomUtils.xmlString2Document(portfolio, new StringBuffer());
            NodeList codes = doc.getDocumentElement().getElementsByTagName("code");
            // Le premier c'est celui du root
            Node codenode = codes.item(0);
            String code = "";
            if (codenode != null)
                code = codenode.getTextContent();

            if (export != null) {
                response = Response.ok(portfolio).header("content-disposition",
                        "attachment; filename = \"" + code + "-" + time + ".xml\"").build();
            } else if (resource != null && files != null) {
                //// Cas du renvoi d'un ZIP

                /// Temp file in temp directory
                File tempDir = new File(System.getProperty("java.io.tmpdir", null));
                File tempZip = File.createTempFile(portfolioUuid, ".zip", tempDir);

                FileOutputStream fos = new FileOutputStream(tempZip);
                ZipOutputStream zos = new ZipOutputStream(fos);
                //               BufferedOutputStream bos = new BufferedOutputStream(zos);

                /// zos.setComment("Some comment");

                /// Write xml file to zip
                ZipEntry ze = new ZipEntry(portfolioUuid + ".xml");
                zos.putNextEntry(ze);

                byte[] bytes = portfolio.getBytes("UTF-8");
                zos.write(bytes);

                zos.closeEntry();

                /// Find all fileid/filename
                XPath xPath = XPathFactory.newInstance().newXPath();
                String filterRes = "//asmResource/fileid";
                NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

                /// Direct link to data
                // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";

                /*
                String langatt = "";
                if( lang != null )
                   langatt = "?lang="+lang;
                else
                   langatt = "?lang=fr";
                //*/

                /// Fetch all files
                for (int i = 0; i < nodelist.getLength(); ++i) {
                    Node res = nodelist.item(i);
                    Node p = res.getParentNode(); // resource -> container
                    Node gp = p.getParentNode(); // container -> context
                    Node uuidNode = gp.getAttributes().getNamedItem("id");
                    String uuid = uuidNode.getTextContent();

                    String filterName = "./filename[@lang and text()]";
                    NodeList textList = (NodeList) xPath.compile(filterName).evaluate(p,
                            XPathConstants.NODESET);
                    String filename = "";
                    if (textList.getLength() != 0) {
                        Element fileNode = (Element) textList.item(0);
                        filename = fileNode.getTextContent();
                        lang = fileNode.getAttribute("lang");
                        if ("".equals(lang))
                            lang = "fr";
                    }

                    String servlet = httpServletRequest.getRequestURI();
                    servlet = servlet.substring(0, servlet.indexOf("/", 7));
                    String server = httpServletRequest.getServerName();
                    int port = httpServletRequest.getServerPort();
                    //                  "http://"+ server + /resources/resource/file/ uuid ? lang= size=
                    // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";
                    String url = "http://" + server + ":" + port + servlet + "/resources/resource/file/" + uuid
                            + "?lang=" + lang;
                    HttpGet get = new HttpGet(url);

                    // Transfer sessionid so that local request still get security checked
                    HttpSession session = httpServletRequest.getSession(true);
                    get.addHeader("Cookie", "JSESSIONID=" + session.getId());

                    // Send request
                    CloseableHttpClient client = HttpClients.createDefault();
                    CloseableHttpResponse ret = client.execute(get);
                    HttpEntity entity = ret.getEntity();

                    // Put specific name for later recovery
                    if ("".equals(filename))
                        continue;
                    int lastDot = filename.lastIndexOf(".");
                    if (lastDot < 0)
                        lastDot = 0;
                    String filenameext = filename.substring(0); /// find extension
                    int extindex = filenameext.lastIndexOf(".");
                    filenameext = uuid + "_" + lang + filenameext.substring(extindex);

                    // Save it to zip file
                    //                  int length = (int) entity.getContentLength();
                    InputStream content = entity.getContent();

                    //                  BufferedInputStream bis = new BufferedInputStream(entity.getContent());

                    ze = new ZipEntry(filenameext);
                    try {
                        int totalread = 0;
                        zos.putNextEntry(ze);
                        int inByte;
                        byte[] buf = new byte[4096];
                        //                     zos.write(bytes,0,inByte);
                        while ((inByte = content.read(buf)) != -1) {
                            totalread += inByte;
                            zos.write(buf, 0, inByte);
                        }
                        System.out.println("FILE: " + filenameext + " -> " + totalread);
                        content.close();
                        //                     bis.close();
                        zos.closeEntry();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    EntityUtils.consume(entity);
                    ret.close();
                    client.close();
                }

                zos.close();
                fos.close();

                /// Return zip file
                RandomAccessFile f = new RandomAccessFile(tempZip.getAbsoluteFile(), "r");
                byte[] b = new byte[(int) f.length()];
                f.read(b);
                f.close();

                response = Response.ok(b, MediaType.APPLICATION_OCTET_STREAM)
                        .header("content-disposition", "attachment; filename = \"" + code + "-" + time + ".zip")
                        .build();

                // Temp file cleanup
                tempZip.delete();
            } else {
                //try { this.userId = userId; } catch(Exception ex) { this.userId = -1; };
                //              String returnValue = dataProvider.getPortfolio(new MimeType("text/xml"),portfolioUuid,this.userId, this.groupId, this.label, resource, files).toString();
                if (portfolio.equals("faux")) {

                    throw new RestWebApplicationException(Status.FORBIDDEN,
                            "Vous n'avez pas les droits necessaires");
                }

                if (accept.equals(MediaType.APPLICATION_JSON)) {
                    portfolio = XML.toJSONObject(portfolio).toString();
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_JSON).build();
                } else
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_XML).build();

                logRestRequest(httpServletRequest, null, portfolio, Status.OK.getStatusCode());
            }
        }
    } catch (RestWebApplicationException ex) {
        throw new RestWebApplicationException(Status.FORBIDDEN, ex.getResponse().getEntity().toString());
    } catch (SQLException ex) {
        logRestRequest(httpServletRequest, null, "Portfolio " + portfolioUuid + " not found",
                Status.NOT_FOUND.getStatusCode());

        throw new RestWebApplicationException(Status.NOT_FOUND, "Portfolio " + portfolioUuid + " not found");
    } catch (Exception ex) {
        ex.printStackTrace();
        logRestRequest(httpServletRequest, null, ex.getMessage() + "\n\n" + ex.getStackTrace(),
                Status.INTERNAL_SERVER_ERROR.getStatusCode());

        throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    } finally {
        if (dataProvider != null)
            dataProvider.disconnect();
    }

    return response;
}