Example usage for java.io ByteArrayOutputStream reset

List of usage examples for java.io ByteArrayOutputStream reset

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream reset.

Prototype

public synchronized void reset() 

Source Link

Document

Resets the count field of this ByteArrayOutputStream to zero, so that all currently accumulated output in the output stream is discarded.

Usage

From source file:org.apache.hadoop.hdfs.TestDFSShell.java

private void textTest(Path root, Configuration conf) throws Exception {
    PrintStream bak = null;/*from ww  w  . java  2 s .co m*/
    try {
        final FileSystem fs = root.getFileSystem(conf);
        fs.mkdirs(root);

        // Test the gzip type of files. Magic detection.
        OutputStream zout = new GZIPOutputStream(fs.create(new Path(root, "file.gz")));
        Random r = new Random();
        bak = System.out;
        ByteArrayOutputStream file = new ByteArrayOutputStream();
        for (int i = 0; i < 1024; ++i) {
            char c = Character.forDigit(r.nextInt(26) + 10, 36);
            file.write(c);
            zout.write(c);
        }
        zout.close();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));

        String[] argv = new String[2];
        argv[0] = "-text";
        argv[1] = new Path(root, "file.gz").toString();
        int ret = ToolRunner.run(new FsShell(conf), argv);
        assertEquals("'-text " + argv[1] + " returned " + ret, 0, ret);
        assertTrue("Output doesn't match input", Arrays.equals(file.toByteArray(), out.toByteArray()));

        // Create a sequence file with a gz extension, to test proper
        // container detection. Magic detection.
        SequenceFile.Writer writer = SequenceFile.createWriter(conf,
                SequenceFile.Writer.file(new Path(root, "file.gz")), SequenceFile.Writer.keyClass(Text.class),
                SequenceFile.Writer.valueClass(Text.class));
        writer.append(new Text("Foo"), new Text("Bar"));
        writer.close();
        out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        argv = new String[2];
        argv[0] = "-text";
        argv[1] = new Path(root, "file.gz").toString();
        ret = ToolRunner.run(new FsShell(conf), argv);
        assertEquals("'-text " + argv[1] + " returned " + ret, 0, ret);
        assertTrue("Output doesn't match input", Arrays.equals("Foo\tBar\n".getBytes(), out.toByteArray()));
        out.reset();

        // Test deflate. Extension-based detection.
        OutputStream dout = new DeflaterOutputStream(fs.create(new Path(root, "file.deflate")));
        byte[] outbytes = "foo".getBytes();
        dout.write(outbytes);
        dout.close();
        out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        argv = new String[2];
        argv[0] = "-text";
        argv[1] = new Path(root, "file.deflate").toString();
        ret = ToolRunner.run(new FsShell(conf), argv);
        assertEquals("'-text " + argv[1] + " returned " + ret, 0, ret);
        assertTrue("Output doesn't match input", Arrays.equals(outbytes, out.toByteArray()));
        out.reset();

        // Test a simple codec. Extension based detection. We use
        // Bzip2 cause its non-native.
        CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(BZip2Codec.class, conf);
        String extension = codec.getDefaultExtension();
        Path p = new Path(root, "file." + extension);
        OutputStream fout = new DataOutputStream(codec.createOutputStream(fs.create(p, true)));
        byte[] writebytes = "foo".getBytes();
        fout.write(writebytes);
        fout.close();
        out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        argv = new String[2];
        argv[0] = "-text";
        argv[1] = new Path(root, p).toString();
        ret = ToolRunner.run(new FsShell(conf), argv);
        assertEquals("'-text " + argv[1] + " returned " + ret, 0, ret);
        assertTrue("Output doesn't match input", Arrays.equals(writebytes, out.toByteArray()));
        out.reset();
    } finally {
        if (null != bak) {
            System.setOut(bak);
        }
    }
}

From source file:org.kuali.ole.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Creates a PDF document based on the PO information and the items that were selected by the user on the Purchase Order
 * Retransmit Document page to be retransmitted, then display the PDF to the browser.
 *
 * @param mapping  An ActionMapping/*from   w w w.  jav a  2 s  .  c o  m*/
 * @param form     An ActionForm
 * @param request  The HttpServletRequest
 * @param response The HttpServletResponse
 * @return An ActionForward
 * @throws Exception
 */
public ActionForward printingRetransmitPoOnly(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    String selectedItemIndexes = request.getParameter("selectedItemIndexes");
    String documentNumber = request.getParameter("poDocumentNumberForRetransmit");
    PurchaseOrderDocument po = SpringContext.getBean(PurchaseOrderService.class)
            .getPurchaseOrderByDocumentNumber(documentNumber);
    String retransmitHeader = request.getParameter("retransmitHeader");

    // setting the isItemSelectedForRetransmitIndicator items of the PO obtained from the database based on its value from
    // the po from the form

    setItemSelectedForRetransmitIndicatorFromPOInForm(selectedItemIndexes, po.getItems());
    po.setRetransmitHeader(retransmitHeader);
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        // below method will throw ValidationException if errors are found
        SpringContext.getBean(PurchaseOrderService.class).retransmitPurchaseOrderPDF(po, baosPDF);

        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        sbContentDispValue.append("inline");
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } catch (ValidationException e) {
        LOG.warn("Caught ValidationException while trying to retransmit PO with doc id "
                + po.getDocumentNumber());
        return mapping.findForward(OLEConstants.MAPPING_ERROR);
    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:org.dbgl.gui.EditProfileDialog.java

protected void doPerformDosboxConfAction(DosboxConfAction action) {
    try {/*from  w  ww. ja  v a2  s .co m*/
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bos);
        updateAllConfigurationsBySettings();

        Conf newDosboxVersion = null;
        if (action == DosboxConfAction.RELOAD_TEMPLATE) {
            newDosboxVersion = new Conf(templatesList.get(template.getSelectionIndex()),
                    dbversionsList.get(dbversion.getSelectionIndex()), ps);
        } else {
            newDosboxVersion = new Conf(dbversionsList.get(dbversion.getSelectionIndex()), ps);
        }

        if (isMultiEdit()) {
            for (Configurable c : multiProfileList) {
                if (c.getConf().hasDifferentBaseMountsThan(newDosboxVersion)) {
                    ps.println(Settings.getInstance().msg("dialog.multiprofile.notice.basemountsconflicting"));
                    break;
                }
            }
        }

        for (Configurable c : multiProfileList) {
            doPerformdosboxConfAction(action, newDosboxVersion, c);
        }

        if (isMultiEdit()) {
            doPerformdosboxConfAction(action, newDosboxVersion, multiProfileCombined);
            enableSettingsByConfiguration(multiProfileCombined.getConf().getDosboxSettings());
            selectSettingsByConfiguration(multiProfileCombined.getConf());
        } else {
            if (action == DosboxConfAction.RELOAD_TEMPLATE) {
                if (multiProfileList.get(0).getNativeCommandsList().size() == 1) {
                    multiProfileList.get(0).setNativeCommandsList(dbase.readNativeCommandsList(-1,
                            templatesList.get(template.getSelectionIndex()).getId()));
                    updateNativeCommands(-1);
                }
            }
            enableSettingsByConfiguration(multiProfileList.get(0).getConf().getDosboxSettings());
            selectSettingsByConfiguration(multiProfileList.get(0).getConf());
        }

        if (bos.size() > 0) {
            GeneralPurposeDialogs.warningMessage(getParent(), bos.toString());
            bos.reset();
        }
    } catch (IOException | SQLException e) {
        GeneralPurposeDialogs.warningMessage(getParent(), e);
    }
}

From source file:org.kuali.kfs.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Prints the PDF only, as opposed to <code>firstTransmitPrintPo</code>, which calls this method (indirectly) to print the PDF,
 * and calls the doc handler to display the PO tabbed page.
 *
 * @param mapping An ActionMapping/* w  ww .  j  av a2s.c  o  m*/
 * @param form An ActionForm
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @throws Exception
 * @return An ActionForward
 */
public ActionForward printPurchaseOrderPDFOnly(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    String poDocId = request.getParameter("docId");
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        // will throw validation exception if errors occur
        SpringContext.getBean(PurchaseOrderService.class).performPrintPurchaseOrderPDFOnly(poDocId, baosPDF);

        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        String useJavascript = request.getParameter("useJavascript");
        if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
            sbContentDispValue.append("attachment");
        } else {
            sbContentDispValue.append("inline");
        }
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_");
        sbFilename.append(poDocId);
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:org.dbgl.gui.MainWindow.java

private void doImportDefaultTemplates(final boolean interactive) {
    if (!interactive || GeneralPurposeDialogs.confirmMessage(shell,
            settings.msg("dialog.importdefaulttemplates.confirm.start"))) {
        try {//from   w w  w  .j av  a2s  .c o m
            if (checkDefaultDBVersion() == null) {
                return;
            }

            File defaultXml = FileUtils.getDefaultTemplatesXmlFile();
            if (!FileUtils.isExistingFile(defaultXml))
                throw new IOException(settings.msg("general.error.openfile", new Object[] { defaultXml }));

            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(defaultXml);

            XPath xPath = XPathFactory.newInstance().newXPath();
            String packageVersion = xPath.evaluate("/document/export/format-version", doc);
            String packageTitle = xPath.evaluate("/document/export/title", doc);
            String packageAuthor = xPath.evaluate("/document/export/author", doc);
            String packageNotes = xPath.evaluate("/document/export/notes", doc);
            String creationApp = xPath.evaluate("/document/export/generator-title", doc);
            String creationAppVersion = xPath.evaluate("/document/export/generator-version", doc);
            Date creationDate = XmlUtils.datetimeFormatter
                    .parse(xPath.evaluate("/document/export/creationdatetime", doc));

            System.out
                    .println(settings.msg("dialog.import.importing",
                            new Object[] { StringUtils.join(
                                    new String[] { packageTitle, packageVersion, packageAuthor, packageNotes,
                                            creationApp, creationAppVersion, creationDate.toString() },
                                    ' ') }));

            NodeList templateNodes = (NodeList) xPath.evaluate("/document/template", doc,
                    XPathConstants.NODESET);

            java.util.List<ExpTemplate> templates = new ArrayList<ExpTemplate>();
            SortedSet<DosboxVersion> dbSet = new TreeSet<DosboxVersion>();
            for (int i = 0; i < templateNodes.getLength(); i++) {
                Element templateNode = (Element) templateNodes.item(i);
                Element dosbox = XmlUtils.getNode(templateNode, "dosbox");
                DosboxVersion d = new DosboxVersion(i, XmlUtils.getTextValue(dosbox, "title"), "", "", true,
                        false, false, "", XmlUtils.getTextValue(dosbox, "version"), null, null, null, 0);
                dbSet.add(d);
                templates.add(new ExpTemplate(templateNode, ImportDialog.getDosboxVersionId(d, dbSet)));
            }

            java.util.List<Integer> dbmapping = new ArrayList<Integer>();
            for (DosboxVersion dbversion : dbSet) {
                dbmapping.add(dbversion.findBestMatchId(dbversionsList));
            }

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(bos);

            Template addedTemplate = null;
            for (ExpTemplate template : templates) {
                template.setDbversionId(
                        ImportDialog.getMappedDosboxVersionId(dbSet, dbmapping, template.getDbversionId()));

                DosboxVersion assocDBVersion = DosboxVersion.findById(dbversionsList,
                        template.getDbversionId());

                addedTemplate = dbase.addOrEditTemplate(template.getTitle(), template.getDbversionId(),
                        template.isDefault(), -1);
                Conf gameConf = new Conf(template.getImportedFullConfig(), template.getImportedIncrConfig(),
                        false, FileUtils.getDefaultTemplatesXmlFile().getPath(), addedTemplate.getId(),
                        assocDBVersion, ps);
                gameConf.save();
            }
            updateTemplateList(addedTemplate);

            if (bos.size() > 0) {
                GeneralPurposeDialogs.warningMessage(shell, bos.toString());
                bos.reset();
            } else {
                if (interactive)
                    GeneralPurposeDialogs.infoMessage(shell, settings.msg("dialog.import.notice.importok"));
            }

        } catch (XPathExpressionException | SAXException e) {
            GeneralPurposeDialogs.fatalMessage(shell,
                    settings.msg("dialog.importdefaulttemplates.error.defaultxmlinvalidformat",
                            new Object[] { e.toString() }),
                    e);
        } catch (Exception e) {
            GeneralPurposeDialogs.fatalMessage(shell, e.toString(), e);
        }
    }
}

From source file:org.kuali.kfs.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Creates a PDF document based on the PO information and the items that were selected by the user on the Purchase Order
 * Retransmit Document page to be retransmitted, then display the PDF to the browser.
 *
 * @param mapping An ActionMapping//  w w  w . ja  v a 2 s . co m
 * @param form An ActionForm
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @throws Exception
 * @return An ActionForward
 */
public ActionForward printingRetransmitPoOnly(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    String selectedItemIndexes = request.getParameter("selectedItemIndexes");
    String documentNumber = request.getParameter("poDocumentNumberForRetransmit");
    PurchaseOrderDocument po = SpringContext.getBean(PurchaseOrderService.class)
            .getPurchaseOrderByDocumentNumber(documentNumber);
    String retransmitHeader = request.getParameter("retransmitHeader");

    // setting the isItemSelectedForRetransmitIndicator items of the PO obtained from the database based on its value from
    // the po from the form

    setItemSelectedForRetransmitIndicatorFromPOInForm(selectedItemIndexes, po.getItems());
    po.setRetransmitHeader(retransmitHeader);
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        // below method will throw ValidationException if errors are found
        SpringContext.getBean(PurchaseOrderService.class).retransmitPurchaseOrderPDF(po, baosPDF);

        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        sbContentDispValue.append("inline");
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } catch (ValidationException e) {
        LOG.warn("Caught ValidationException while trying to retransmit PO with doc id "
                + po.getDocumentNumber());
        return mapping.findForward(KFSConstants.MAPPING_ERROR);
    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

@Override
public InputStream setChanges(final InputStream toBeChanged, final Map<String, InputStream> properties)
        throws Exception {
    XMLEventReader reader = getEventReader(toBeChanged);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    XMLEventWriter writer = xof.createXMLEventWriter(bos);

    // ---------------------------------
    // add property changes
    // ---------------------------------
    Map.Entry<Integer, XmlElement> propertyElement = getAtomElement(reader, writer, PROPERTIES, null, 0, 2, 3,
            false);/* w ww  .ja  va  2 s. c  om*/

    writer.flush();

    ByteArrayOutputStream pbos = new ByteArrayOutputStream();
    OutputStreamWriter pwriter = new OutputStreamWriter(pbos);

    final XMLEventReader propertyReader = propertyElement.getValue().getContentReader();

    try {
        while (true) {
            final XmlElement property = getAtomElement(propertyReader, null, null);
            final String name = property.getStart().getName().getLocalPart();

            if (properties.containsKey(name)) {
                // replace
                final InputStream replacement = properties.get(name);
                properties.remove(property.getStart().getName().getLocalPart());
                pwriter.append(IOUtils.toString(replacement));
                IOUtils.closeQuietly(replacement);
            } else {
                pwriter.append(IOUtils.toString(property.toStream()));
            }
        }
    } catch (Exception ignore) {
        // end
    }

    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
        if (!remains.getKey().startsWith("[LINK]")) {
            pwriter.append(IOUtils.toString(remains.getValue()));
            IOUtils.closeQuietly(remains.getValue());
        }
    }

    pwriter.flush();
    pwriter.close();

    writer.add(propertyElement.getValue().getStart());
    writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray())));
    writer.add(propertyElement.getValue().getEnd());

    IOUtils.closeQuietly(pbos);

    writer.add(reader);
    reader.close();
    writer.flush();
    writer.close();
    // ---------------------------------

    // ---------------------------------
    // add navigationm changes
    // ---------------------------------

    // remove existent links
    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {

        if (remains.getKey().startsWith("[LINK]")) {
            reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

            bos.reset();
            writer = xof.createXMLEventWriter(bos);

            try {
                final String linkName = remains.getKey().substring(remains.getKey().indexOf("]") + 1);

                getAtomElement(reader, writer, LINK, Collections.<Map.Entry<String, String>>singleton(
                        new SimpleEntry<String, String>("title", linkName)), 0, 2, 2, false);

                writer.add(reader);

            } catch (Exception ignore) {
                // ignore
            }

            writer.flush();
            writer.close();
        }
    }

    reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

    bos.reset();
    writer = xof.createXMLEventWriter(bos);

    propertyElement = getAtomElement(reader, writer, CONTENT, null, 0, 2, 2, false);
    writer.flush();

    pbos.reset();
    pwriter = new OutputStreamWriter(pbos);

    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
        if (remains.getKey().startsWith("[LINK]")) {
            pwriter.append(IOUtils.toString(remains.getValue()));
            IOUtils.closeQuietly(remains.getValue());
        }
    }

    pwriter.flush();
    pwriter.close();

    writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray())));
    IOUtils.closeQuietly(pbos);

    writer.add(propertyElement.getValue().getStart());
    writer.add(propertyElement.getValue().getContentReader());
    writer.add(propertyElement.getValue().getEnd());

    writer.add(reader);
    reader.close();
    writer.flush();
    writer.close();
    // ---------------------------------

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java

@Override
public InputStream setChanges(final InputStream toBeChanged, final Map<String, InputStream> properties)
        throws Exception {
    XMLEventReader reader = getEventReader(toBeChanged);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLEventWriter writer = getEventWriter(bos);

    // ---------------------------------
    // add property changes
    // ---------------------------------
    Map.Entry<Integer, XmlElement> propertyElement = extractElement(reader, writer,
            Collections.<String>singletonList(PROPERTIES), 0, 2, 3);

    writer.flush();//from  w  w  w.j ava  2s .  c om

    ByteArrayOutputStream pbos = new ByteArrayOutputStream();
    OutputStreamWriter pwriter = new OutputStreamWriter(pbos);

    final XMLEventReader propertyReader = propertyElement.getValue().getContentReader();

    try {
        while (true) {
            final XmlElement property = extractElement(propertyReader, null, null, 0, -1, -1).getValue();
            final String name = property.getStart().getName().getLocalPart();

            if (properties.containsKey(name)) {
                // replace
                final InputStream replacement = properties.get(name);
                properties.remove(property.getStart().getName().getLocalPart());
                pwriter.append(IOUtils.toString(replacement));
                IOUtils.closeQuietly(replacement);
            } else {
                pwriter.append(IOUtils.toString(property.toStream()));
            }
        }
    } catch (Exception ignore) {
        // end
    }

    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
        if (!remains.getKey().startsWith("[LINK]")) {
            pwriter.append(IOUtils.toString(remains.getValue()));
            IOUtils.closeQuietly(remains.getValue());
        }
    }

    pwriter.flush();
    pwriter.close();

    writer.add(propertyElement.getValue().getStart());
    writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray())));
    writer.add(propertyElement.getValue().getEnd());

    IOUtils.closeQuietly(pbos);

    writer.add(reader);
    reader.close();
    writer.flush();
    writer.close();
    // ---------------------------------

    // ---------------------------------
    // add navigationm changes
    // ---------------------------------

    // remove existent links
    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {

        if (remains.getKey().startsWith("[LINK]")) {
            reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

            bos.reset();
            writer = getEventWriter(bos);

            try {
                final String linkName = remains.getKey().substring(remains.getKey().indexOf("]") + 1);

                extractElement(reader, writer, Collections.<String>singletonList(LINK),
                        Collections.<Map.Entry<String, String>>singleton(
                                new SimpleEntry<String, String>("title", linkName)),
                        false, 0, 2, 2);

                writer.add(reader);

            } catch (Exception ignore) {
                // ignore
            }

            writer.flush();
            writer.close();
        }
    }

    reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

    bos.reset();
    writer = getEventWriter(bos);

    propertyElement = extractElement(reader, writer, Collections.<String>singletonList(CONTENT), 0, 2, 2);
    writer.flush();

    pbos.reset();
    pwriter = new OutputStreamWriter(pbos);

    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
        if (remains.getKey().startsWith("[LINK]")) {
            pwriter.append(IOUtils.toString(remains.getValue()));
            IOUtils.closeQuietly(remains.getValue());
        }
    }

    pwriter.flush();
    pwriter.close();

    writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray())));
    IOUtils.closeQuietly(pbos);

    writer.add(propertyElement.getValue().getStart());
    writer.add(propertyElement.getValue().getContentReader());
    writer.add(propertyElement.getValue().getEnd());

    writer.add(reader);
    reader.close();
    writer.flush();
    writer.close();
    // ---------------------------------

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:org.dbgl.gui.EditProfileDialog.java

protected boolean init() {
    try {//from   www.  j  a  v a2  s  . c om
        dbversionsList = dbase.readDosboxVersionsList();
        developersList = dbase.readDevelopersList();
        publishersList = dbase.readPublishersList();
        genresList = dbase.readGenresList();
        yearsList = dbase.readYearsList();
        templatesList = dbase.readTemplatesList();
        statusList = dbase.readStatusList();
        for (int i = 0; i < AMOUNT_OF_CUSTOM_STRINGS; i++) {
            customList.add(dbase.readCustomList(i));
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bos);

        if (result instanceof Profile) {
            Profile profile = (Profile) result;
            dbversionIndex = DosboxVersion.findIndexById(dbversionsList, profile.getDbversionId());
            DosboxVersion dbversion = dbversionsList.get(dbversionIndex);
            Conf cc = new Conf(profile, dbversion, ps);
            if ((cc.getAutoexec().isIncomplete()) && (!GeneralPurposeDialogs.confirmMessage(getParent(),
                    settings.msg("dialog.profile.confirm.profileincomplete",
                            new Object[] { FileUtils.DOSBOX_CONF, dbversion.getCanonicalConfFile() })))) {
                return false;
            }
            java.util.List<NativeCommand> nativeCommands = dbase.readNativeCommandsList(profile.getId(), -1);
            multiProfileList.add(new ExpProfile(profile.getId(), cc,
                    FileUtils.makeRelativeToDosroot(cc.getAutoexec().getCanonicalMainDir()), nativeCommands,
                    profile));
        } else if (isMultiEdit()) {
            dbversionIndex = DosboxVersion.findIndexById(dbversionsList, multiProfileCombined.getDbversionId());
        } else {
            dbversionIndex = DosboxVersion.indexOfDefault(dbversionsList);
            DosboxVersion dbversion = dbversionsList.get(dbversionIndex);
            templateIndex = Template.indexOfDefault(templatesList);
            Conf cc = null;
            java.util.List<NativeCommand> nativeCommands = null;
            if ((result instanceof String) && FileUtils.isConfFile((String) result)) {
                cc = new Conf(FileUtils.canonicalToDosroot((String) result), (Template) null, dbversion, ps);
                nativeCommands = dbase.readNativeCommandsList(-1, -1);
            } else if (templateIndex != -1) {
                cc = new Conf((File) null, templatesList.get(templateIndex), dbversion, ps);
                nativeCommands = dbase.readNativeCommandsList(-1, templatesList.get(templateIndex).getId());
            } else {
                cc = new Conf((File) null, (Template) null, dbversion, ps);
                nativeCommands = dbase.readNativeCommandsList(-1, -1);
            }
            multiProfileList.add(new ExpProfile(cc, nativeCommands));
        }
        if (bos.size() > 0) {
            GeneralPurposeDialogs.warningMessage(getParent(), bos.toString());
            bos.reset();
        }
        return true;

    } catch (Exception e) {
        GeneralPurposeDialogs.warningMessage(getParent(), e);
        return false;
    }
}

From source file:net.lightbody.bmp.proxy.jetty.http.handler.DumpHandler.java

public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response)
        throws HttpException, IOException {
    if (!isStarted())
        return;/* w  w w .  j a v  a 2 s .co  m*/

    // Only handle GET, HEAD and POST
    if (!HttpRequest.__GET.equals(request.getMethod()) && !HttpRequest.__HEAD.equals(request.getMethod())
            && !HttpRequest.__POST.equals(request.getMethod()))
        return;

    log.debug("Dump");

    response.setField(HttpFields.__ContentType, HttpFields.__TextHtml);
    OutputStream out = response.getOutputStream();
    ByteArrayOutputStream buf = new ByteArrayOutputStream(2048);
    Writer writer = new OutputStreamWriter(buf, StringUtil.__ISO_8859_1);
    writer.write("<HTML><H1>Dump HttpHandler</H1>");
    writer.write("<PRE>\npath=" + request.getPath() + "\ncontextPath=" + getHttpContext().getContextPath()
            + "\npathInContext=" + pathInContext + "\n</PRE>\n");
    writer.write("<H3>Header:</H3><PRE>");
    writer.write(request.toString());
    writer.write("</PRE>\n<H3>Parameters:</H3>\n<PRE>");
    Set names = request.getParameterNames();
    Iterator iter = names.iterator();
    while (iter.hasNext()) {
        String name = iter.next().toString();
        List values = request.getParameterValues(name);
        if (values == null || values.size() == 0) {
            writer.write(name);
            writer.write("=\n");
        } else if (values.size() == 1) {
            writer.write(name);
            writer.write("=");
            writer.write((String) values.get(0));
            writer.write("\n");
        } else {
            for (int i = 0; i < values.size(); i++) {
                writer.write(name);
                writer.write("[" + i + "]=");
                writer.write((String) values.get(i));
                writer.write("\n");
            }
        }
    }

    String cookie_name = request.getParameter("CookieName");
    if (cookie_name != null && cookie_name.trim().length() > 0) {
        String cookie_action = request.getParameter("Button");
        try {
            Cookie cookie = new Cookie(cookie_name.trim(), request.getParameter("CookieVal"));
            if ("Clear Cookie".equals(cookie_action))
                cookie.setMaxAge(0);
            response.addSetCookie(cookie);
        } catch (IllegalArgumentException e) {
            writer.write("</PRE>\n<H3>BAD Set-Cookie:</H3>\n<PRE>");
            writer.write(e.toString());
            LogSupport.ignore(log, e);
        }
    }

    writer.write("</PRE>\n<H3>Cookies:</H3>\n<PRE>");
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (int c = 0; c < cookies.length; c++) {
            Cookie cookie = cookies[c];
            writer.write(cookie.getName());
            writer.write("=");
            writer.write(cookie.getValue());
            writer.write("\n");
        }
    }

    writer.write("</PRE>\n<H3>Attributes:</H3>\n<PRE>");
    Enumeration attributes = request.getAttributeNames();
    if (attributes != null && attributes.hasMoreElements()) {
        while (attributes.hasMoreElements()) {
            String attr = attributes.nextElement().toString();
            writer.write(attr);
            writer.write("=");
            writer.write(request.getAttribute(attr).toString());
            writer.write("\n");
        }
    }

    writer.write("</PRE>\n<H3>Content:</H3>\n<PRE>");
    byte[] content = new byte[4096];
    int len;
    try {
        InputStream in = request.getInputStream();
        while ((len = in.read(content)) >= 0)
            writer.write(new String(content, 0, len));
    } catch (IOException e) {
        LogSupport.ignore(log, e);
        writer.write(e.toString());
    }

    // You wouldn't normally set a trailer like this, but
    // we don't want to commit the output to force trailers as
    // it makes test harness messy
    request.getAcceptableTransferCodings();

    // commit now
    writer.flush();
    response.setIntField(HttpFields.__ContentLength, buf.size() + 1000);
    buf.writeTo(out);
    out.flush();

    // Now add the response
    buf.reset();
    writer.write("</PRE>\n<H3>Response:</H3>\n<PRE>");
    writer.write(response.toString());
    writer.write("</PRE></HTML>");
    writer.flush();
    for (int pad = 998 - buf.size(); pad-- > 0;)
        writer.write(" ");
    writer.write("\015\012");
    writer.flush();
    buf.writeTo(out);

    request.setHandled(true);
}