Example usage for org.apache.commons.io IOUtils toInputStream

List of usage examples for org.apache.commons.io IOUtils toInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils toInputStream.

Prototype

public static InputStream toInputStream(String input, String encoding) throws IOException 

Source Link

Document

Convert the specified string to an input stream, encoded as bytes using the specified character encoding.

Usage

From source file:ch.entwine.weblounge.common.impl.content.image.LazyImageResourceImpl.java

/**
 * Loads the image header only./*w  w w  . j  a  v  a 2  s  .  c o  m*/
 */
protected void loadImageHeader() {
    try {

        // Get a hold of the image reader
        ImageResourceReader reader = (readerRef != null) ? readerRef.get() : null;
        if (reader == null) {
            reader = new ImageResourceReader();
            readerRef = new WeakReference<ImageResourceReader>(reader);
        }

        // If no separate header was given, then we need to load the whole thing
        // instead.
        if (headerXml == null) {
            loadImage();
            return;
        }

        // Load the image header
        image = reader.readHeader(IOUtils.toInputStream(headerXml, "utf-8"), uri.getSite());
        isHeaderLoaded = true;
        if (isHeaderLoaded && isBodyLoaded)
            cleanupAfterLoading();
        else
            headerXml = null;

    } catch (Throwable e) {
        logger.error("Failed to lazy-load header of {}", uri);
        throw new IllegalStateException(e);
    }
}

From source file:mitm.common.security.ca.CSVRequestConverterTest.java

@Test(expected = RequestConverterException.class)
public void testExceedMaxLines() throws Exception {
    String input = "email, organisation, COMMONNAME, firstname, lastname\r\n"
            + "test1@example.com,org,  cn1  , firstname1, lastname1\r\n"
            + "test2@example.com,org,  cn1  , firstname1, lastname1\r\n"
            + "test3@example.com,org2,cn2,firstname2,lastname2";

    CSVRequestConverter converter = new CSVRequestConverter();

    converter.setMaxLines(2);/* w ww. j a  v  a  2 s  .c  o m*/

    converter.convertCSV(IOUtils.toInputStream(input, CharacterEncoding.US_ASCII));
}

From source file:com.mmounirou.spotirss.spotify.tracks.SpotifyHrefQuery.java

private static List<XTracks> parseResult(String strResult) throws IOException, SAXException {
    Digester digester = new Digester();
    List<XTracks> result = Lists.newArrayList();
    digester.push(result);//from   w  ww.  j  a  v a2s .c  om
    addRules(digester);
    digester.parse(IOUtils.toInputStream(strResult, Charsets.UTF_8));
    return result;
}

From source file:com.github.thesmartenergy.cnr.ChargingPlanSubscriber.java

@Override
public void run() {
    LOG.info("Starting worker.");
    while (!Thread.currentThread().isInterrupted()) {
        try {// w w  w . ja va2s  .  c  om
            ReceiveQueueMessageResult result = service.receiveQueueMessage(queue, opts);
            BrokeredMessage message = result.getValue();
            if (message == null) {
                continue;
            }

            System.out.println(message.getContentType());
            System.out.println(message.getCorrelationId());
            System.out.println(message.getDate());
            System.out.println(message.getDeliveryCount());
            System.out.println(message.getLabel());
            System.out.println(message.getLockLocation());
            System.out.println(message.getLockToken());
            System.out.println(message.getLockedUntilUtc());
            System.out.println(message.getMessageId());
            System.out.println(message.getMessageLocation());
            System.out.println(message.getPartitionKey());
            System.out.println(message.getProperties());
            System.out.println(message.getReplyTo());
            System.out.println(message.getSessionId());

            // SCP response
            String id = message.getMessageId();
            if (id == null) {
                LOG.log(Level.WARNING, "received message with null id. Try to delete:");
                try {
                    service.deleteMessage(message);
                } catch (Exception ex) {
                    LOG.warning("error while trying to delete message: " + ex.getMessage());
                    ex.printStackTrace();
                    LOG.warning("this was the content:");
                    System.out.println(IOUtils.toString(message.getBody(), "UTF-8"));
                }
                continue;
            } else {
                LOG.info("received response " + id);
            }

            byte[] body = IOUtils.toByteArray(message.getBody());
            String bodyAsString = IOUtils.toString(body, "UTF-8");
            LOG.info(bodyAsString);

            // strangely, string starts with "@strin3http://schemas.microsoft.com/2003/10/Serialization/?f<s:Envelope ..." on this side, 
            // although it starts with  "<?xml version="1.0" encoding="UTF-8"?> <s:Envelope ..." on the other side
            // so ... ugly hack
            bodyAsString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                    + bodyAsString.substring(64, bodyAsString.length() - 1);

            ResourceDescription presentation = new ResourceDescription(DEV_BASE + "outputGraph");
            Model output;
            try {
                PresentationUtils presentationUtils = new PresentationUtils();
                SPARQLGenerateHandler lifter = new SPARQLGenerateHandler(BASE, presentationUtils);
                output = lifter.lift(MediaType.APPLICATION_XML_TYPE, presentation,
                        IOUtils.toInputStream(bodyAsString, "UTF-8"));
            } catch (RDFPException ex) {
                throw new PEPException("error while lifting output", ex);
            }

            ProcessExecution processExecution = smartChargingProvider.find(id);
            processExecution = new ProcessExecutionImpl(BASE, processExecution.getContainerPath(),
                    processExecution.getId(), processExecution.getInput(),
                    CompletableFuture.completedFuture(output));
            smartChargingProvider.update(processExecution);

            // Delete message from queue
            service.deleteMessage(message);

        } catch (ServiceException | IOException | PEPException ex) {
            LOG.log(Level.WARNING, "error while processing input ", ex);
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }
    LOG.info("Stopping worker.");
}

From source file:ch.entwine.weblounge.common.impl.content.file.LazyFileResourceImpl.java

/**
 * Loads the file header only./*from   ww w.jav a  2  s.c om*/
 */
protected void loadFileHeader() {
    try {

        // Get a hold of the file reader
        FileResourceReader reader = (readerRef != null) ? readerRef.get() : null;
        if (reader == null) {
            reader = new FileResourceReader();
            readerRef = new WeakReference<FileResourceReader>(reader);
        }

        // If no separate header was given, then we need to load the whole thing
        // instead.
        if (headerXml == null) {
            loadPage();
            return;
        }

        // Load the file header
        file = reader.readHeader(IOUtils.toInputStream(headerXml, "utf-8"), uri.getSite());
        isHeaderLoaded = true;
        if (isHeaderLoaded && isBodyLoaded)
            cleanupAfterLoading();
        else
            headerXml = null;

    } catch (Throwable e) {
        logger.error("Failed to lazy-load header of {}", uri);
        throw new IllegalStateException(e);
    }
}

From source file:de.tu_dortmund.ub.data.util.TPUUtil.java

public static JsonObject doInit(final String resourceWatchFolder, final String initResourceFileName,
        final String serviceName, final Integer engineThreads, final Properties config, final int cnt)
        throws Exception {

    final String initResourceFile = resourceWatchFolder + File.separatorChar + initResourceFileName;

    final String initResultJSONString = TPUUtil.executeInit(initResourceFile, serviceName, engineThreads,
            config, cnt);//from  ww w .  j av a 2s.  c o m

    if (initResultJSONString == null) {

        final String message = "couldn't create data model";

        LOG.error(message);

        throw new Exception(message);
    }

    final JsonReader initResultJsonReader = Json
            .createReader(IOUtils.toInputStream(initResultJSONString, UTF_8));
    final JsonObject initResultJSON = initResultJsonReader.readObject();

    if (initResultJSON == null) {

        final String message = "couldn't create data model";

        LOG.error(message);

        throw new Exception(message);
    }

    return initResultJSON;
}

From source file:dpfmanager.shell.modules.periodic.core.ControllerWindows.java

public PeriodicCheck parseXmlString(String xmlTask, String uuid) {
    try {//from w  ww  .  j a  v  a2  s.c  om
        boolean preIssue250 = true;

        InputStream is = IOUtils.toInputStream(xmlTask, "UTF-16");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(is);

        // Parse input & configuration
        String arguments = doc.getDocumentElement().getElementsByTagName("Arguments").item(0).getTextContent();
        if (arguments.startsWith("\"")) {
            preIssue250 = false;
            arguments = arguments.substring(arguments.substring(1).indexOf("\"") + 3, arguments.length());
        }
        String input = getInputFromArguments(arguments);
        String configuration = getConfigurationFromArguments(arguments);

        // Parse periodicity
        Periodicity periodicity = new Periodicity();
        Periodicity.Mode mode;
        NodeList schDay = doc.getDocumentElement().getElementsByTagName("ScheduleByDay");
        NodeList schWeek = doc.getDocumentElement().getElementsByTagName("ScheduleByWeek");
        NodeList schMonth = doc.getDocumentElement().getElementsByTagName("ScheduleByMonth");
        if (schDay.getLength() > 0) {
            periodicity.setMode(Periodicity.Mode.DAILY);
        } else if (schWeek.getLength() > 0) {
            periodicity.setMode(Periodicity.Mode.WEEKLY);
            Element elemWeek = (Element) schWeek.item(0);
            Node node = elemWeek.getElementsByTagName("DaysOfWeek").item(0);
            NodeList childs = node.getChildNodes();
            for (int i = 0; i < childs.getLength(); i++) {
                Node child = childs.item(i);
                if (child.getNodeType() == Node.ELEMENT_NODE) {
                    Element elem = (Element) child;
                    periodicity.addDaysOfWeek(parseDayName(elem.getTagName()));
                }
            }
        } else if (schMonth.getLength() > 0) {
            periodicity.setMode(Periodicity.Mode.MONTHLY);
            Element elem = (Element) schMonth.item(0);
            String dayStr = elem.getElementsByTagName("Day").item(0).getTextContent();
            periodicity.setDayOfMonth(Integer.parseInt(dayStr));
        }

        // Parse time
        String timeStr = doc.getDocumentElement().getElementsByTagName("StartBoundary").item(0)
                .getTextContent();
        String time = timeStr.substring(11, 16);
        periodicity.setTime(LocalTime.parse(time));

        is.close();

        PeriodicCheck pc = new PeriodicCheck(uuid, input, configuration, periodicity);
        if (preIssue250) {
            editPeriodicalCheck(pc);
        }
        return pc;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:de.hybris.platform.servicelayer.impex.ImportValidationModesTest.java

private InputStream givenImpexStream() {
    return IOUtils.toInputStream("INSERT_UPDATE Title;name[unique=true, lang=en];\n;test;\n", ENCODING);
}

From source file:ch.entwine.weblounge.common.impl.content.movie.LazyMovieResourceImpl.java

/**
 * Loads the audio visual header only./*w  w  w . j  ava2 s. c  o m*/
 */
protected void loadAudioVisualHeader() {
    try {

        // Get a hold of the audio visual reader
        MovieResourceReader reader = (readerRef != null) ? readerRef.get() : null;
        if (reader == null) {
            reader = new MovieResourceReader();
            readerRef = new WeakReference<MovieResourceReader>(reader);
        }

        // If no separate header was given, then we need to load the whole thing
        // instead.
        if (headerXml == null) {
            loadAudioVisual();
            return;
        }

        // Load the audio visual header
        audioVisual = reader.readHeader(IOUtils.toInputStream(headerXml, "utf-8"), uri.getSite());
        isHeaderLoaded = true;
        if (isHeaderLoaded && isBodyLoaded)
            cleanupAfterLoading();
        else
            headerXml = null;

    } catch (Throwable e) {
        logger.error("Failed to lazy-load header of {}", uri);
        throw new IllegalStateException(e);
    }
}

From source file:edu.lternet.pasta.portal.search.BrowseGroup.java

private void addFetchDownElements() {
    String fetchDownXML = ControlledVocabularyClient.webServiceFetchDown(this.termId);
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    try {//from w  w w  .j a  va  2 s  .  c om
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputStream inputStream = IOUtils.toInputStream(fetchDownXML, "UTF-8");
        Document document = documentBuilder.parse(inputStream);
        Element documentElement = document.getDocumentElement();
        NodeList documentNodeList = documentElement.getElementsByTagName("term");

        for (int i = 0; i < documentNodeList.getLength(); i++) {
            Node documentNode = documentNodeList.item(i);
            NodeList childNodes = documentNode.getChildNodes();
            String termId = null;
            String value = null;
            String hasMoreDown = null;

            for (int j = 0; j < childNodes.getLength(); j++) {

                Node childNode = childNodes.item(j);
                if (childNode instanceof Element) {
                    Element childElement = (Element) childNode;
                    if (childElement.getTagName().equals("term_id")) {
                        Text text = (Text) childElement.getFirstChild();
                        termId = text.getData().trim();
                    } else if (childElement.getTagName().equals("string")) {
                        Text text = (Text) childElement.getFirstChild();
                        value = text.getData().trim();
                    } else if (childElement.getTagName().equals("hasMoreDown")) {
                        Text text = (Text) childElement.getFirstChild();
                        hasMoreDown = text.getData().trim();
                    }
                }
            }

            if (hasMoreDown != null && hasMoreDown.equals("1")) {
                BrowseGroup downTerm = new BrowseGroup(value);
                this.addBrowseGroup(downTerm);
                downTerm.setTermId(termId);
                downTerm.setHasMoreDown(hasMoreDown);
                downTerm.addFetchDownElements();

            } else {
                BrowseTerm downTerm = new BrowseTerm(value);
                downTerm.setTermId(termId);
                this.addBrowseTerm(downTerm);
            }
        }
    } catch (Exception e) {
        logger.error("Exception:\n" + e.getMessage());
        e.printStackTrace();
    }

    if (!isBlacklistedTerm(this.value)) {
        BrowseTerm browseTerm = new BrowseTerm(this.value);
        browseTerm.setLevel(level + 1);
        this.addBrowseTerm(browseTerm);
    }

}