Example usage for java.io StringReader close

List of usage examples for java.io StringReader close

Introduction

In this page you can find the example usage for java.io StringReader close.

Prototype

public void close() 

Source Link

Document

Closes the stream and releases any system resources associated with it.

Usage

From source file:de.uzk.hki.da.grid.IrodsCommandLineConnector.java

/**
 * Parses parses result set for a given AVU 
 * @author Jens Peters//from   w w  w .j  a va  2  s.  c om
 * @param result
 * @param field
 * @return
 * @throws IOException
 */
private String parseResultForAVUField(String result, String field) throws IOException {
    String[] props = result.split("------------------------------------------------------------");
    for (int i = 0; i < props.length; i++) {
        Properties properties = new Properties();
        StringReader sr = new StringReader(props[i]);
        properties.load(sr);
        sr.close();
        if (properties.get(field) != null) {
            return properties.get(field).toString();
        }
    }
    return "";
}

From source file:com.ibm.domino.das.resources.DocumentResource.java

public Response updateDocumentByUnid(String requestEntity,
        @HeaderParam(HEADER_IF_UNMODIFIED_SINCE) final String ifUnmodifiedSince,
        @PathParam(PARAM_UNID) String unid, @QueryParam(PARAM_DOC_FORM) String form,
        @QueryParam(PARAM_DOC_COMPUTEWITHFORM) String computeWithForm, boolean put) {

    String jsonEntity = null;/*from w w w .  j av  a 2  s . c o  m*/
    Document document = null;

    try {
        // Write JSON content
        Database database = this.getDatabase(DB_ACCESS_VIEWS_DOCS);
        try {
            document = database.getDocumentByUNID(unid);
        } catch (NotesException e) {
            throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.NOT_FOUND));
        }
        ifUnmodifiedSince(document, ifUnmodifiedSince);
        JsonDocumentContent content = new JsonDocumentContent(document);
        JsonJavaObject jsonItems;
        JsonJavaFactory factory = JsonJavaFactory.instanceEx;
        try {
            StringReader reader = new StringReader(requestEntity);
            try {
                jsonItems = (JsonJavaObject) JsonParser.fromJson(factory, reader);
            } finally {
                reader.close();
            }
        } catch (Exception ex) {
            throw new ServiceException(ex, "Error while parsing the JSON content"); // $NLX-DocumentResource.ErrorwhileparsingtheJSONcontent-1$
        }
        // Handle parameters.
        if (StringUtil.isNotEmpty(form)) {
            document.replaceItemValue(ITEM_FORM, form);
        }
        content.updateFields(jsonItems, put);
        if (computeWithForm != null && computeWithForm.compareToIgnoreCase(PARAM_VALUE_TRUE) == 0) {
            document.computeWithForm(true, true);
        }
        document.save();
    } catch (NotesException e) {
        throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.BAD_REQUEST));
    } catch (ServiceException e) {
        throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.BAD_REQUEST));
    } finally {
        if (document != null) {
            try {
                document.recycle();
            } catch (NotesException e) {
                // Ignore
            }
        }
    }

    ResponseBuilder builder = Response.ok();
    builder.type(MediaType.APPLICATION_JSON_TYPE).entity(jsonEntity);

    Response response = builder.build();

    return response;
}

From source file:fr.ortolang.diffusion.runtime.engine.task.ImportReferentialEntityTask.java

private String extractField(String jsonContent, String fieldName) {
    String fieldValue = null;/*w  w  w . j  a v  a 2  s  .  c  o m*/
    StringReader reader = new StringReader(jsonContent);
    JsonReader jsonReader = Json.createReader(reader);
    try {
        JsonObject jsonObj = jsonReader.readObject();
        fieldValue = jsonObj.getString(fieldName);
    } catch (IllegalStateException | NullPointerException | ClassCastException | JsonException e) {
        LOGGER.log(Level.WARNING, "No property '" + fieldName + "' in json object", e);
    } finally {
        jsonReader.close();
        reader.close();
    }

    return fieldValue;
}

From source file:com.taobao.diamond.domain.Aggregation.java

@SuppressWarnings("unchecked")
public static List<ConfigInfo> parse(String aggregation) {
    List<ConfigInfo> result = new ArrayList<ConfigInfo>();
    StringReader reader = null;
    try {/*www  .  j  av  a 2s  .c  o  m*/
        reader = new StringReader(aggregation);
        List<String> lines = IOUtils.readLines(reader);
        for (int i = 0; i < lines.size(); i++) {
            String line = lines.get(i);
            if (line.startsWith(LINE_HEAD)) {
                ConfigInfo configInfo = new ConfigInfo();
                if (++i < lines.size()) {
                    configInfo.setDataId(lines.get(i));
                }
                if (++i < lines.size()) {
                    configInfo.setGroup(lines.get(i));
                }
                if (++i < lines.size()) {
                    if (!lines.get(i).equals(""))
                        configInfo.setMd5(lines.get(i));
                }
                String content = "";
                int innerIndex = 0;
                while (++i < lines.size()) {
                    line = lines.get(i);
                    if (line.equals(LINE_END))
                        break;
                    if (innerIndex++ > 0)
                        content += lineSeparator;
                    content += line;
                }
                if (!content.equals("")) {
                    configInfo.setContent(content);
                }
                result.add(configInfo);
            }
        }
    } catch (IOException e) {
        return parseAfterException(aggregation);
    } finally {
        reader.close();
    }

    return result;
}

From source file:org.lnicholls.galleon.apps.internetSlideshows.InternetSlideshows.java

public static List getPhotoDescriptions(String url) {

    List photoDescriptions = new ArrayList();

    PersistentValue persistentValue = PersistentValueManager
            .loadPersistentValue(InternetSlideshows.class.getName() + "."

                    + url);/*from  www .ja v a  2  s  .  c o  m*/

    String content = persistentValue == null ? null : persistentValue.getValue();

    if (PersistentValueManager.isAged(persistentValue)) {

        try {

            String page = Tools.getPage(new URL(url));

            if (page != null && page.length() > 0)

                content = page;

        } catch (Exception ex) {

            Tools.logException(InternetSlideshows.class, ex, "Could not cache listing: " + url);

        }

    }

    if (content != null) {

        try {

            SAXReader saxReader = new SAXReader();

            StringReader stringReader = new StringReader(content);

            // Document document = saxReader.read(new

            // File("d:/galleon/itunes2.rss.xml"));

            Document document = saxReader.read(stringReader);

            stringReader.close();

            stringReader = null;

            Element root = document.getRootElement(); // check for errors

            if (root != null && root.getName().equals("rss")) {

                Element channel = root.element("channel");

                if (channel != null) {

                    for (Iterator i = channel.elementIterator("item"); i.hasNext();) {

                        Element item = (Element) i.next();

                        String value = null;

                        String title = null;

                        String link = null;

                        if ((value = Tools.getAttribute(item, "title")) != null) {

                            title = value;

                        }

                        if ((value = Tools.getAttribute(item, "description")) != null) {

                            title = Tools.cleanHTML(value);

                        }

                        Element contentElement = item.element("content");

                        if (contentElement != null) {

                            if ((value = contentElement.attributeValue("url")) != null) {

                                link = value;

                                if (url.startsWith("http://rss.news.yahoo.com"))

                                {

                                    URL location = new URL(link);

                                    photoDescriptions.add(new PhotoDescription(location.getProtocol() + "://"
                                            + location.getHost() + location.getPath(), title));

                                }

                                else

                                    photoDescriptions.add(new PhotoDescription(link, title));

                            }

                        }

                        Element enclosureElement = item.element("enclosure");

                        if (enclosureElement != null) {

                            if ((value = enclosureElement.attributeValue("url")) != null) {

                                link = value;

                                if (url.startsWith("http://rss.news.yahoo.com"))

                                {

                                    URL location = new URL(link);

                                    photoDescriptions.add(new PhotoDescription(location.getProtocol() + "://"
                                            + location.getHost() + location.getPath(), title));

                                }

                                else

                                    photoDescriptions.add(new PhotoDescription(link, title));

                            }

                        }

                    }

                }

            }

            document.clearContent();

            document = null;

            if (PersistentValueManager.isAged(persistentValue)) {

                PersistentValueManager.savePersistentValue(InternetSlideshows.class.getName() + "." + url,

                        content, 60);

            }

        } catch (Exception ex) {

            Tools.logException(InternetSlideshows.class, ex, "Could not download listing: " + url);

            return null;

        }

    }

    return photoDescriptions;

}

From source file:hoot.services.controllers.ogr.TranslatorResource.java

/**
 * <NAME>OGR-LTDS Translation Service Translate TDS to OSM</NAME>
 * <DESCRIPTION>//w w  w  .ja  v a  2  s  . co  m
 * WARNING: THIS END POINT WILL BE DEPRECATED SOON
 * Translate TDS to OSM
 *  http://localhost:8080/hoot-services/ogr/ltds/translate/tds/{OSM element id}?translation={translation script}
 * </DESCRIPTION>
 * <PARAMETERS>
 * <translation>
 *    relative path of translation script
 * </translation>
 * </PARAMETERS>
 * <OUTPUT>
 *    TDS output
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/ogr/ltds/translate/-1669795?translation=MGCP.js</URL>
 *    <REQUEST_TYPE>POST</REQUEST_TYPE>
 *    <INPUT>
 * {"attrs":{"FCODE":"AP030","HCT":"0","UID":"d9c4b1df-066c-4ece-a583-76fec0056b58"},"tableName":"LAP030"}
 *   </INPUT>
 * <OUTPUT>OSM XML output</OUTPUT>
 * </EXAMPLE>
* @param id
* @param translation
* @param osmXml
* @return
*/
@POST
@Path("/ltds/translate/tds/{id}")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Response translateTdsToOsm(@PathParam("id") String id,
        @QueryParam("translation") final String translation, String osmXml) {
    String outStr = "unknown";
    PostMethod mpost = new PostMethod("http://localhost:" + currentPort + "/tdstoosm");
    try {

        try {

            String ogrxml = osmXml.replace('"', '\'');

            JSONObject requestParams = new JSONObject();
            requestParams.put("command", "translate");
            requestParams.put("uid", id);
            requestParams.put("input", ogrxml);
            requestParams.put("script", homeFolder + "/translations" + translation);
            requestParams.put("direction", "toogr");
            String postData = requestParams.toJSONString();
            StringEntity se = new StringEntity(requestParams.toJSONString());
            StringRequestEntity requestEntity = new StringRequestEntity(requestParams.toJSONString(),
                    "text/plain", "UTF-8");
            mpost.setRequestEntity(requestEntity);

            mclient.executeMethod(mpost);
            String response = mpost.getResponseBodyAsString();

            JSONParser par = new JSONParser();
            JSONObject transRes = (JSONObject) par.parse(response);
            String tdsOSM = transRes.get("output").toString();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            StringReader strReader = new StringReader(tdsOSM);
            InputSource is = new InputSource(strReader);

            Document document = builder.parse(is);
            strReader.close();

            JSONObject attrib = new JSONObject();
            NodeList nodeList = document.getDocumentElement().getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node instanceof Element) {
                    NodeList childNodes = node.getChildNodes();
                    for (int j = 0; j < childNodes.getLength(); j++) {
                        Node cNode = childNodes.item(j);
                        if (cNode instanceof Element) {
                            String k = ((Element) cNode).getAttribute("k");
                            String v = ((Element) cNode).getAttribute("v");
                            attrib.put(k, v);

                        }
                    }
                }
            }

            JSONObject ret = new JSONObject();
            ret.put("tablenName", "");
            ret.put("attrs", attrib);
            outStr = ret.toJSONString();

        } catch (Exception ee) {
            ResourceErrorHandler.handleError("Failed upload: " + ee.toString(), Status.INTERNAL_SERVER_ERROR,
                    log);
        } finally {
            log.debug("postJobRequest Closing");
            mpost.releaseConnection();
        }

    } catch (Exception e) {
        ResourceErrorHandler.handleError("Translation error: " + e.toString(), Status.INTERNAL_SERVER_ERROR,
                log);
    }

    return Response.ok(outStr, MediaType.APPLICATION_JSON).build();
}

From source file:hoot.services.controllers.ogr.TranslatorResource.java

/**
 * <NAME>OGR-LTDS Translation Service</NAME>
 * <DESCRIPTION>// w w w . j a va2  s . c  o m
 *    WARNING: THIS END POINT WILL BE DEPRECATED SOON
 * To translate osm element into OGR/LTDS format 2 services are available
 *  http://localhost:8080/hoot-services/ogr/ltds/translate/{OSM element id}?translation={translation script}
 * </DESCRIPTION>
 * <PARAMETERS>
 * <translation>
 *    relative path of translation script
 * </translation>
 * </PARAMETERS>
 * <OUTPUT>
 *    TDS output
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/ogr/ltds/translate/-1669795?translation=MGCP.js</URL>
 *    <REQUEST_TYPE>POST</REQUEST_TYPE>
 *    <INPUT>
 * {some OSM XML}
 *   </INPUT>
 * <OUTPUT>{"attrs":{"FCODE":"AP030","HCT":"0","UID":"d9c4b1df-066c-4ece-a583-76fec0056b58"},"tableName":"LAP030"}</OUTPUT>
 * </EXAMPLE>
* @param id
* @param translation
* @param osmXml
* @return
*/
@POST
@Path("/ltds/translate/{id}")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Response translateOsm(@PathParam("id") String id, @QueryParam("translation") final String translation,
        String osmXml) {
    String outStr = "unknown";

    try {
        PostMethod mpost = new PostMethod("http://localhost:" + currentPort + "/osmtotds");
        try {

            osmXml = osmXml.replace('"', '\'');
            JSONObject requestParams = new JSONObject();
            requestParams.put("command", "translate");
            requestParams.put("uid", id);
            requestParams.put("input", osmXml);
            requestParams.put("script", homeFolder + "/translations" + translation);
            requestParams.put("direction", "toogr");

            StringRequestEntity requestEntity = new StringRequestEntity(requestParams.toJSONString(),
                    "text/plain", "UTF-8");
            mpost.setRequestEntity(requestEntity);

            mclient.executeMethod(mpost);
            String response = mpost.getResponseBodyAsString();
            //r = client.execute(post);

            // String response = EntityUtils.toString(r.getEntity());
            JSONParser par = new JSONParser();
            JSONObject transRes = (JSONObject) par.parse(response);
            String tdsOSM = transRes.get("output").toString();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            StringReader strReader = new StringReader(tdsOSM);
            InputSource is = new InputSource(strReader);

            Document document = builder.parse(is);
            strReader.close();

            String sFCode = null;
            JSONObject attrib = new JSONObject();
            NodeList nodeList = document.getDocumentElement().getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node instanceof Element) {
                    NodeList childNodes = node.getChildNodes();
                    for (int j = 0; j < childNodes.getLength(); j++) {
                        Node cNode = childNodes.item(j);
                        if (cNode instanceof Element) {
                            String k = ((Element) cNode).getAttribute("k");
                            String v = ((Element) cNode).getAttribute("v");
                            attrib.put(k, v);
                            if (k.equalsIgnoreCase("Feature Code")) {
                                String[] parts = v.split(":");
                                sFCode = parts[0].trim();
                            }
                        }
                    }
                }
            }
            String sFields = getFields(sFCode);
            JSONObject ret = new JSONObject();
            ret.put("tablenName", "");
            ret.put("attrs", attrib);
            ret.put("fields", sFields);
            outStr = ret.toJSONString();

        } catch (Exception ee) {
            ResourceErrorHandler.handleError("Failed upload: " + ee.toString(), Status.INTERNAL_SERVER_ERROR,
                    log);
        } finally {
            mpost.releaseConnection();

        }
    } catch (Exception e) {
        ResourceErrorHandler.handleError("Translation error: " + e.toString(), Status.INTERNAL_SERVER_ERROR,
                log);
    }

    return Response.ok(outStr, MediaType.APPLICATION_JSON).build();
}

From source file:org.bonitasoft.engine.api.internal.servlet.HttpAPIServletCall.java

@SuppressWarnings("unchecked")
private <T> T fromXML(final String object, final XStream xstream) {
    final StringReader xmlReader = new StringReader(object);
    ObjectInputStream in = null;/*from  w  w w.  ja v a2 s.c  om*/

    try {
        in = xstream.createObjectInputStream(xmlReader);
        try {
            return (T) in.readObject();
        } catch (final IOException e) {
            throw new BonitaRuntimeException("unable to deserialize object " + object, e);
        } catch (final ClassNotFoundException e) {
            throw new BonitaRuntimeException("unable to deserialize object " + object, e);
        } finally {
            in.close();
            xmlReader.close();
        }
    } catch (final IOException e) {
        throw new BonitaRuntimeException("unable to deserialize object " + object, e);
    }
}

From source file:com.jiangyifen.ec2.ui.mgr.system.tabsheet.SystemLicence.java

/**
 * added by chb 20140520/*from w  w w  . j  av  a  2s  .c  om*/
 * @return
 */
private VerticalLayout updateLicenseComponent() {
    VerticalLayout licenseUpdateLayout = new VerticalLayout();
    final VerticalLayout textAreaPlaceHolder = new VerticalLayout();
    final HorizontalLayout buttonPlaceHolder = new HorizontalLayout();
    buttonPlaceHolder.setSpacing(true);

    //
    final Button updateButton = new Button("License");
    updateButton.setData("show");

    //
    final Button cancelButton = new Button("?");

    //
    final TextArea licenseTextArea = new TextArea();
    licenseTextArea.setColumns(30);
    licenseTextArea.setRows(5);
    licenseTextArea.setWordwrap(true);
    licenseTextArea.setInputPrompt("??");

    //Layout
    buttonPlaceHolder.addComponent(updateButton);
    licenseUpdateLayout.addComponent(textAreaPlaceHolder);
    licenseUpdateLayout.addComponent(buttonPlaceHolder);

    //
    cancelButton.addListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            textAreaPlaceHolder.removeAllComponents();
            buttonPlaceHolder.removeComponent(cancelButton);
            updateButton.setData("show");
            updateButton.setCaption("License");
        }
    });

    updateButton.addListener(new Button.ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            if (((String) event.getButton().getData()).equals("show")) {
                textAreaPlaceHolder.removeAllComponents();
                textAreaPlaceHolder.addComponent(licenseTextArea);
                buttonPlaceHolder.addComponent(cancelButton);
                event.getButton().setData("updateAndHide");
                event.getButton().setCaption("??");
            } else if (((String) event.getButton().getData()).equals("updateAndHide")) {
                StringReader stringReader = new StringReader(
                        StringUtils.trimToEmpty((String) licenseTextArea.getValue()));
                Properties props = new Properties();
                try {
                    props.load(stringReader);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                stringReader.close();
                //               Boolean isValidvalidateLicense(licenseTextArea.getValue());
                String license_date = props.getProperty(LicenseManager.LICENSE_DATE);
                String license_count = props.getProperty(LicenseManager.LICENSE_COUNT);
                String license_localmd5 = props.getProperty(LicenseManager.LICENSE_LOCALMD5);
                //
                Boolean isMatch = regexMatchCheck(license_date, license_count, license_localmd5);
                if (isMatch) {

                    Map<String, String> licenseMap = new HashMap<String, String>();
                    //??
                    //                  String license_count = (String)props.get(LicenseManager.LICENSE_COUNT);
                    license_count = license_count == null ? "" : license_count;
                    licenseMap.put(LicenseManager.LICENSE_COUNT, license_count);

                    //?
                    //                  String license_date = (String)props.get(LicenseManager.LICENSE_DATE);
                    license_date = license_date == null ? "" : license_date;
                    licenseMap.put(LicenseManager.LICENSE_DATE, license_date);

                    //???
                    //                  String license_localmd5 = (String)props.get(LicenseManager.LICENSE_LOCALMD5);
                    license_localmd5 = license_localmd5 == null ? "" : license_localmd5;
                    licenseMap.put(LicenseManager.LICENSE_LOCALMD5, license_localmd5);

                    //?License
                    Map<String, String> resultMap = LicenseManager.licenseValidate(licenseMap);

                    String validateResult = resultMap.get(LicenseManager.LICENSE_VALIDATE_RESULT);
                    if (LicenseManager.LICENSE_VALID.equals(validateResult)) {
                        //continue
                    } else {
                        NotificationUtil.showWarningNotification(SystemLicence.this,
                                "License ?License");
                        return;
                    }

                    try {
                        URL resourceurl = SystemLicence.class.getResource(LicenseManager.LICENSE_FILE);
                        //System.err.println("chb: SystemLicense"+resourceurl.getPath());
                        OutputStream fos = new FileOutputStream(resourceurl.getPath());
                        props.store(fos, "license");
                    } catch (Exception e) {
                        e.printStackTrace();
                        NotificationUtil.showWarningNotification(SystemLicence.this, "License ");
                        return;
                    }
                    textAreaPlaceHolder.removeAllComponents();
                    buttonPlaceHolder.removeComponent(cancelButton);
                    updateButton.setData("show");
                    updateButton.setCaption("License");
                    LicenseManager.loadLicenseFile(LicenseManager.LICENSE_FILE.substring(1));
                    //                  LicenseManager.loadLicenseFile(licenseFilename)
                    refreshLicenseInfo();
                    NotificationUtil.showWarningNotification(SystemLicence.this,
                            "License ?,?");
                } else {
                    NotificationUtil.showWarningNotification(SystemLicence.this,
                            "License ??");
                }
            }
        }

        /**
         * license ?
         * @param license_date
         * @param license_count
         * @param license_localmd5
         * @return
         */
        private Boolean regexMatchCheck(String license_date, String license_count, String license_localmd5) {
            if (StringUtils.isEmpty(license_date) || StringUtils.isEmpty(license_count)
                    || StringUtils.isEmpty(license_localmd5)) {
                return false;
            }
            String date_regex = "^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}$"; //?
            String count_regex = "^\\d+$"; //?
            String md5_32_regex = "^\\w{32}$"; //?
            return license_localmd5.matches(md5_32_regex) && license_date.matches(date_regex)
                    && license_count.matches(count_regex);
        }
    });

    return licenseUpdateLayout;
}

From source file:com.taobao.diamond.server.service.task.processor.UpdateConfigInfoTaskProcessor.java

@SuppressWarnings("unchecked")
private String generateNewContentByIdentity(String oldContent, String appendant, String appendantIdentity) {
    StringBuilder sb = new StringBuilder();
    StringReader reader = null;
    try {/*from   w ww  .  j av a 2s  . c om*/
        reader = new StringReader(oldContent);
        List<String> lines = IOUtils.readLines(reader);
        for (String line : lines) {
            if (!line.contains(appendantIdentity)) {
                sb.append(line);
                sb.append(Constants.DIAMOND_LINE_SEPARATOR);
            }
        }
        sb.append(appendant);

        return sb.toString();
    } catch (Exception e) {
        log.error("", e);
        return oldContent;
    } finally {
        reader.close();
    }
}