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:org.waarp.openr66.database.data.DbHostConfiguration.java

/**
 * Shortcut to add all paths element from source into set
 * /*w ww  .j a va 2s .  c o m*/
 * @param source
 * @param path
 * @param set
 * @return True if ok
 */
private boolean updateSet(String source, String path, HashSet<String> set) {
    if (source != null && !source.isEmpty()) {
        Document document = null;
        StringReader reader = null;
        if (source != null && !source.isEmpty()) {
            try {
                reader = new StringReader(source);
                document = new SAXReader().read(reader);
            } catch (DocumentException e) {
                logger.error("Unable to read the XML Config " + path + " string: " + source, e);
                if (reader != null) {
                    reader.close();
                }
                return false;
            }
            if (document == null) {
                logger.error("Unable to read the XML Config " + path + " string: " + source);
                if (reader != null) {
                    reader.close();
                }
                return false;
            }
            @SuppressWarnings("unchecked")
            List<Element> list = document.selectNodes(path);
            for (Element element : list) {
                String sval = element.getText().trim();
                if (sval.isEmpty()) {
                    continue;
                }
                set.add(sval.trim());
            }
            list.clear();
            document.clearContent();
            document = null;
            if (reader != null) {
                reader.close();
                reader = null;
            }
        }
    }
    return true;
}

From source file:org.waarp.openr66.database.data.DbHostConfiguration.java

/**
 * Shortcut to add all paths element with key and value from source into map
 * //  w w w .j  a  v a 2  s  .c  o  m
 * @param source
 * @param path
 * @param keypath
 * @param valpath
 * @param split
 * @param map
 * @return True if ok
 */
private boolean updateMap(String source, String path, String keypath, String valpath, String split,
        HashMap<String, HashSet<String>> map) {
    if (source != null && !source.isEmpty()) {
        Document document = null;
        StringReader reader = null;
        if (source != null && !source.isEmpty()) {
            try {
                reader = new StringReader(source);
                document = new SAXReader().read(reader);
            } catch (DocumentException e) {
                logger.error("Unable to read the XML Config " + path + " string: " + source, e);
                if (reader != null) {
                    reader.close();
                }
                return false;
            }
            if (document == null) {
                logger.error("Unable to read the XML Config " + path + " string: " + source);
                if (reader != null) {
                    reader.close();
                }
                return false;
            }
            @SuppressWarnings("unchecked")
            List<Element> list = document.selectNodes(path);
            for (Element element : list) {
                Element nodeid = (Element) element.selectSingleNode(keypath);
                if (nodeid == null) {
                    continue;
                }
                Element nodeset = (Element) element.selectSingleNode(valpath);
                if (nodeset == null) {
                    continue;
                }
                String refHostId = nodeid.getText();
                String aliasesid = nodeset.getText();
                String[] aliasid = aliasesid.split(split);
                HashSet<String> set = null;
                if (map.containsKey(refHostId)) {
                    set = map.get(refHostId);
                } else {
                    set = new HashSet<String>();
                }
                for (String namealias : aliasid) {
                    set.add(namealias);
                }
                map.put(refHostId, set);
            }
            list.clear();
            document.clearContent();
            document = null;
            if (reader != null) {
                reader.close();
                reader = null;
            }
        }
    }
    return true;
}

From source file:op.controlling.PnlControlling.java

private Properties load(String text) {
    Properties props = new Properties();
    try {//from www. j a v  a  2s .com
        StringReader reader = new StringReader(text);
        props.load(reader);
        reader.close();
    } catch (IOException ex) {
        OPDE.fatal(ex);
    }
    return props;
}

From source file:org.kalypso.simulation.core.ant.GMLWeightingOperation.java

private void addSourceSummands(final Feature weightFE, final double factor, final Feature[] sourceFeatures,
        final List<JAXBElement<? extends AbstractFilterType>> offsetSummands)
        throws GMLXPathException, SensorException, JAXBException {
    final GMLXPath sourceZMLPath = asPath(m_data.getSourceZMLProperty());
    final GMLXPath sourceIsUsedPath = asPath(m_data.getSourceIsUsedProperty());
    final String sourceFilter = m_data.getSourceFilter();

    // 8. loop source features
    for (final Feature sourceFE : sourceFeatures) {
        if (sourceFE == null) {
            m_logger.log(Level.WARNING, -1, "Linked source feature missing in Feature: " + weightFE.getId());

            // IMPORTANT: just skips this weight; leads probably to wrong results
            continue;
        }/*from www  .  ja va2  s . c  o m*/

        // 9. resolve property that is source zml reference
        final TimeseriesLinkType zmlLink = GMLXPathUtilities.query(sourceZMLPath, sourceFE);
        final Boolean useThisSource;
        if (sourceIsUsedPath != null)
            useThisSource = GMLXPathUtilities.query(sourceIsUsedPath, sourceFE);
        else
            useThisSource = Boolean.TRUE;

        if (!useThisSource.booleanValue()) {
            m_logger.log(Level.INFO, LoggerUtilities.CODE_NONE, "Ignoriere: " + sourceFE.getId());
            continue;
        }

        if (zmlLink == null) {
            m_logger.log(Level.WARNING, LoggerUtilities.CODE_SHOW_DETAILS,
                    "Linked timeserie link missing in Feature: " + weightFE.getId()); //$NON-NLS-1$

            // IMPORTANT: just skips this weight; leads probably to wrong results
            continue;
        }

        // 10. build operation filter with parameters from gml
        final OperationFilterType filter = FilterFactory.OF_FILTER.createOperationFilterType();
        offsetSummands.add(FilterFactory.OF_FILTER.createOperationFilter(filter));
        filter.setOperator("*"); //$NON-NLS-1$
        filter.setOperand(Double.toString(factor));

        /* Innermost filter part */
        final ZmlFilterType zmlFilter = FilterFactory.OF_FILTER.createZmlFilterType();
        final SimpleLinkType simpleLink = m_linkFac.createSimpleLinkType();
        final String sourceHref = zmlLink.getHref();
        simpleLink.setHref(sourceHref);
        zmlFilter.setZml(simpleLink);

        if (sourceFilter != null) {
            final String strFilterXml = FilterFactory.getFilterPart(sourceFilter);

            final StringReader sr = new StringReader(strFilterXml);
            final Unmarshaller unmarshaller = ZmlFactory.JC.createUnmarshaller();
            final JAXBElement<?> filterElement = (JAXBElement<?>) unmarshaller.unmarshal(new InputSource(sr));
            if (filterElement == null
                    || !AbstractFilterType.class.isAssignableFrom(filterElement.getDeclaredType()))
                throw new UnsupportedOperationException(
                        "Filter must start with an AbstractFilterType element."); //$NON-NLS-1$

            @SuppressWarnings("unchecked")
            final JAXBElement<AbstractFilterType> af = (JAXBElement<AbstractFilterType>) filterElement;
            filter.setFilter(af);

            // HACK
            final AbstractFilterType abstractFilter = af.getValue();
            if (abstractFilter instanceof InterpolationFilterType)
                ((InterpolationFilterType) abstractFilter)
                        .setFilter(FilterFactory.OF_FILTER.createZmlFilter(zmlFilter));
            else
                throw new UnsupportedOperationException(
                        "Only InterpolationFilter as source-filter supported at the moment."); //$NON-NLS-1$

            sr.close();
        } else
            filter.setFilter(FilterFactory.OF_FILTER.createZmlFilter(zmlFilter));
    }
}

From source file:org.ecoinformatics.seek.R.RExpression.java

private String _writeDataFile(String dat) {
    String fn = "";
    try {//  w  w w.jav  a2  s  . c  o m
        String home = System.getProperty("user.home");
        home = home.replace('\\', '/');
        fn = home + "/" + _getUniqueFileName("dat") + cntr;
        File dataFile = new File(fn);
        StringReader is = new StringReader(dat);
        FileWriter os = new FileWriter(dataFile);
        int c;
        while ((c = is.read()) != -1) {
            os.write(c);
        }
        is.close();
        os.close();
    } catch (Exception exc) {
        log.error("error writing data file! - RExpression");
    }
    cntr++;
    return fn;
}

From source file:org.ght.tc.esb.orchestration.process_actions.TransformExternalMessage.java

public void execute(ExecutionContext exCtx) throws Exception {
    Document docIn;//  ww  w .  ja v a2  s.c o  m
    StringReader readerIn = null;
    Token token = exCtx.getToken();

    String incidentType = "";
    String incidentSeverity = "";
    String incidentAction = "";
    String TicketType = "";
    String SocOwner = "";
    ContextInstance context = token.getProcessInstance().getContextInstance();
    String theBody = (String) context.getVariable("theBody", token);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = factory.newDocumentBuilder();

    StringReader reader = new StringReader(theBody);
    InputSource inputSource = new InputSource(reader);
    Document doc = parser.parse(inputSource);
    //System.out.println("TransformExternalMessage:doc.getElementsByTagName(return):"+Integer.toString(doc.getElementsByTagName("return").getLength()));
    incidentType = doc.getElementsByTagName("incidentType").item(0).getTextContent();
    incidentSeverity = doc.getElementsByTagName("incidentSeverity").item(0).getTextContent();
    if (doc.getElementsByTagName("incidentAction").getLength() > 0) {
        incidentAction = doc.getElementsByTagName("incidentAction").item(0).getTextContent();
    } else {
        incidentAction = "";
    }
    if (doc.getElementsByTagName("TicketType").getLength() > 0) {
        TicketType = doc.getElementsByTagName("TicketType").item(0).getTextContent();
    } else {
        TicketType = "";
    }
    if (doc.getElementsByTagName("SocOwner").getLength() > 0) {
        SocOwner = doc.getElementsByTagName("SocOwner").item(0).getTextContent();
    } else {
        SocOwner = "";
    }
    String newTheBody = "<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'><env:Header></env:Header><env:Body>";
    newTheBody += "<incidentType>" + incidentType + "</incidentType>";
    newTheBody += "<incidentSeverity>" + incidentSeverity + "</incidentSeverity>";
    newTheBody += "<TicketType>" + TicketType + "</TicketType>";
    newTheBody += "<SocOwner>" + SocOwner + "</SocOwner>";
    newTheBody += "</env:Body></env:Envelope>";
    reader.close();
    if (readerIn != null) {
        readerIn.close();
    }
    System.out.println("TransformExternalMessage:newTheBody:" + newTheBody);
    context.setVariable("theBody", newTheBody, token);
    //context.setVariable("incidentSeverity", "101");
    context.createVariable("incidentSeverity", incidentSeverity, token);
    context.createVariable("incidentType", incidentType, token);
    context.createVariable("incidentAction", incidentAction, token);
    context.createVariable("TicketType", TicketType, token);
    context.createVariable("SocOwner", SocOwner, token);

}

From source file:org.opencastproject.capture.impl.SchedulerImpl.java

/**
 * A helper function to wrap the configuration of an event. This function writes the attached files to disk and
 * generates the initial {@code Mediapackage}.
 * /* www.  ja v  a2  s  .  c  o m*/
 * @param attachments
 *          The {@code PropertyList} of the capture. This contains all of the attachments and such needed to setup the
 *          directory structure.
 * @param props
 *          The system {@code Properties} for the job. This can be overridden by the properties attached to the event.
 * @param job
 *          The {@code JobDetail} instance itself. This is what everything gets attached to so that Quartz can run
 *          properly.
 * @throws org.opencastproject.util.ConfigurationException
 * @throws MediaPackageException
 * @throws MalformedURLException
 * @throws ParseException
 */
@SuppressWarnings("unchecked")
private void setupEvent(PropertyList attachments, Properties props, JobDetail job)
        throws org.opencastproject.util.ConfigurationException, MediaPackageException, MalformedURLException,
        ParseException {
    MediaPackage pack = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder().createNew();
    pack.setIdentifier(new IdImpl(props.getProperty(CaptureParameters.RECORDING_ID)));

    // Create the directory we'll be capturing into
    File captureDir = new File(configService.getItem(CaptureParameters.CAPTURE_FILESYSTEM_CAPTURE_CACHE_URL),
            props.getProperty(CaptureParameters.RECORDING_ID));
    if (!captureDir.exists()) {
        try {
            FileUtils.forceMkdir(captureDir);
        } catch (IOException e) {
            log.error("IOException creating required directory {}, skipping capture.", captureDir.toString());
            return;
        }
    }

    ListIterator<Property> iter = (ListIterator<Property>) attachments.listIterator();
    // For each attachment
    while (iter.hasNext()) {
        Property p = iter.next();
        // TODO: Make this not hardcoded? Make this not depend on Apple's idea of rfc 2445?
        String filename = p.getParameter("X-APPLE-FILENAME").getValue();
        if (filename == null) {
            log.warn("No filename given for attachment, skipping.");
            continue;
        }
        // Get the contents of the attachment. Note that this assumes the attachment is a string of some sorts
        // This breaks with binary files (probably)
        String contents = propertyToString(p);

        // Handle any attachments
        try {
            // If the event has properties
            if (filename.equals(CaptureParameters.RECORDING_PROPERTIES)) {
                // Load the properties
                Properties jobProps = new Properties();
                StringReader s = new StringReader(contents);
                jobProps.load(s);
                s.close();
                // Merge them overtop of the system properties
                jobProps.putAll(props);
                // Attach the properties to the job itself
                job.getJobDataMap().put(JobParameters.CAPTURE_PROPS, jobProps);
                // And attach the properties file to the mediapackage
                pack.add(new URI(filename));
                // Handle the episode metadata
            } else if ("episode.xml".equals(filename)) {
                pack.add(new URI(filename), MediaPackageElement.Type.Catalog, MediaPackageElements.EPISODE);
                // Handle the series metadata
            } else if ("series.xml".equals(filename)) {
                pack.add(new URI(filename), MediaPackageElement.Type.Catalog, MediaPackageElements.SERIES);
            } else {
                pack.add(new URI(filename));
            }
        } catch (IOException e) {
            log.error("Unable to read properties file attached to event {}!",
                    props.getProperty(CaptureParameters.RECORDING_ID));
        } catch (URISyntaxException e) {
            log.error("Unable to add file {} to mediapackage: {}.", filename, e);
        }
        job.getJobDataMap().put(JobParameters.MEDIA_PACKAGE, pack);
        // Note that we overwrite any pre-existing files with this. In other words, if there is a file called foo.txt in
        // the
        // captureDir directory and there is an attachment called foo.txt then we will overwrite the one on disk with the
        // one from the ical
        URL u = new File(captureDir, filename).toURI().toURL();
        try {
            IoSupport.writeUTF8File(u, contents);
        } catch (IOException e) {
            log.error("Unable to write to {}, IOException occurred", u.toString());
        }
    }

    job.getJobDataMap().put(JobParameters.CAPTURE_AGENT, captureAgent);
    job.getJobDataMap().put(JobParameters.JOB_SCHEDULER, scheduler);
}

From source file:org.globus.mds.bigindex.impl.database.xml.xindice.XindiceDriver.java

/**
 * Adds a Document to a collection, where the input Document is in String form.
 * @param parentCol - name of the parent collection
 * @param docstr - String representation of the Document to add
 * @param docName - name of the document
 * @return String - the document ID./*  w  w  w  .  ja va2  s. co m*/
 */
public String addDocumentString(String parentCol, String docstr, String docName) throws Exception {
    checkInitialized();

    Collection col = null;
    String docID = null;
    try {
        if (this.isProfiling) {
            this.performanceLogger.start();
        }

        // Create a collection instance
        String colURI = normalizeCollectionURI(parentCol, this.isLocal);
        col = DatabaseManager.getCollection(colURI);
        if (col == null) {
            String err = "XINDICE ERROR: Collection not found! " + colURI;
            if (logger.isDebugEnabled()) {
                logger.debug(err);
            }
            throw new Exception(err);
        }

        // Parse in XML using Xerces
        StringReader reader = new StringReader(docstr);

        SAXParserFactory spf = javax.xml.parsers.SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);

        XMLReader saxReader = spf.newSAXParser().getXMLReader();
        StringSerializer ser = new StringSerializer(null);

        saxReader.setContentHandler(ser);
        saxReader.setProperty("http://xml.org/sax/properties/lexical-handler", ser);
        saxReader.parse(new InputSource(reader));
        reader.close();

        // Create the XMLResource and store the document
        XMLResource resource = (XMLResource) col.createResource(docName, "XMLResource");
        resource.setContent(ser.toString());
        col.storeResource(resource);
        docID = resource.getId();

        if (logger.isDebugEnabled()) {
            logger.debug("STORED Document: " + colURI + "/" + docID);
        }
        resource = null;
    } finally {
        if (col != null) {
            col.close();
        }
        col = null;

        if (this.isProfiling) {
            this.performanceLogger.stop("addDocumentString");
        }
    }
    return docID;
}

From source file:org.pentaho.di.job.entries.spark.JobEntrySparkSubmit.java

/**
 * Parse a string into arguments as if it were provided on the command line.
 *
 * @param commandLineString A command line string.
 * @return List of parsed arguments/*  www.j a v  a  2  s  .c o  m*/
 * @throws IOException when the command line could not be parsed
 */
public List<String> parseCommandLine(String commandLineString) throws IOException {
    List<String> args = new ArrayList<String>();
    StringReader reader = new StringReader(commandLineString);
    try {
        StreamTokenizer tokenizer = new StreamTokenizer(reader);
        // Treat a dash as an ordinary character so it gets included in the token
        tokenizer.ordinaryChar('-');
        tokenizer.ordinaryChar('.');
        tokenizer.ordinaryChars('0', '9');
        // Treat all characters as word characters so nothing is parsed out
        tokenizer.wordChars('\u0000', '\uFFFF');

        // Re-add whitespace characters
        tokenizer.whitespaceChars(0, ' ');

        // Use " and ' as quote characters
        tokenizer.quoteChar('"');
        tokenizer.quoteChar('\'');

        // Add all non-null string values tokenized from the string to the argument list
        while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
            if (tokenizer.sval != null) {
                String s = tokenizer.sval;
                s = environmentSubstitute(s);
                args.add(s);
            }
        }
    } finally {
        reader.close();
    }

    return args;
}

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

protected boolean validateExport(String script) {

    boolean canExport = false;
    org.mozilla.javascript.Context context = org.mozilla.javascript.Context.enter();
    try {//from  w  w w . j a  va  2 s .  c  om
        // initialize Rhino

        org.mozilla.javascript.ScriptableObject scope = context.initStandardObjects();
        context.setOptimizationLevel(-1);

        scope.put("context", scope, context);
        scope.put("scope", scope, scope);
        scope.put("APP_ROOT", scope, homeFolder);

        FileReader frHeader = new FileReader(jsHeaderScriptPath);
        BufferedReader jsHeader = new BufferedReader(frHeader);
        context.evaluateReader(scope, jsHeader, "jsHeader", 1, null);

        StringReader sr = new StringReader(script);
        BufferedReader translation_script = new BufferedReader(sr);
        context.evaluateReader(scope, translation_script, "translation_script", 1, null);

        // call getDbSchema call any required preloading functions
        Object getSchemaObj = scope.get("getDbSchema", scope);
        Object translateToOgr = scope.get("translateToOgr", scope);

        boolean getDbSchemaExist = false;
        if (getSchemaObj != null) {
            // If not exist then will return Tag instead of function
            if (getSchemaObj instanceof Function) {
                getDbSchemaExist = true;
            }
        }

        boolean translateToOgrExist = false;
        if (translateToOgr != null) {
            // If not exist then will return Tag instead of function
            if (translateToOgr instanceof Function) {
                translateToOgrExist = true;
            }
        }

        canExport = getDbSchemaExist && translateToOgrExist;

        frHeader.close();
        jsHeader.close();
        sr.close();
        translation_script.close();

    } catch (Exception ex) {
        log.error(ex.getMessage());
    } finally {
        context.exit();
    }
    return canExport;
}