Example usage for java.io OutputStreamWriter close

List of usage examples for java.io OutputStreamWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:fr.paris.lutece.portal.web.user.AdminUserJspBeanTest.java

public void testDoImportUsersFromFile() throws AccessDeniedException, UserNotSignedException, IOException {
    AdminUserJspBean bean = new AdminUserJspBean();
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter(SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance().getToken(request, "jsp/admin/user/ImportUser.jsp"));
    AdminUser user = getUserToModify();//from  w ww.  jav a  2s . c o m
    AdminAuthenticationService.getInstance().registerUser(request, user);
    bean.init(request, "CORE_USERS_MANAGEMENT");
    Map<String, List<FileItem>> multipartFiles = new HashMap<>();
    List<FileItem> fileItems = new ArrayList<>();
    FileItem file = new DiskFileItem("import_file", "application/csv", true, "junit.csv", 1024,
            new File(System.getProperty("java.io.tmpdir")));
    OutputStreamWriter writer = new OutputStreamWriter(file.getOutputStream(), Charset.forName("UTF-8"));
    writer.write(
            "test;test;test;test@test.fr;" + AdminUser.ACTIVE_CODE + ";" + Locale.FRANCE + ";0;false;false;;;");
    writer.close();
    fileItems.add(file);
    multipartFiles.put("import_file", fileItems);
    Map<String, String[]> parameters = request.getParameterMap();
    MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest(request, multipartFiles,
            parameters);
    bean.getImportUsersFromFile(request); // initialize _importAdminUserService
    AdminUser importedUser = null;
    try {
        bean.doImportUsersFromFile(multipartRequest);
        importedUser = AdminUserHome.findUserByLogin("test");
        assertNotNull(importedUser);
        assertEquals("test", importedUser.getAccessCode());
        assertEquals("test", importedUser.getFirstName());
        assertEquals("test", importedUser.getLastName());
        assertEquals("test@test.fr", importedUser.getEmail());
        assertEquals(AdminUser.ACTIVE_CODE, importedUser.getStatus());
    } finally {
        if (importedUser != null) {
            disposeOfUser(importedUser);
        }
        disposeOfUser(user);
    }
}

From source file:eionet.util.VocabularyCSVOutputHelper.java

/**
 * Writes CSV to output stream.//  ww  w.j  a  va  2s .  c o m
 *
 * @param out
 *            outputstream
 * @param uriPrefix
 *            uri prefix for teh element identifiers
 * @param folderContextRoot
 *            parent vocabulary folder root for related identifiers
 * @param concepts
 *            list of vocabulary concepts
 * @param attributesMeta
 *            list of field names to the CSV header row
 * @throws IOException
 *             if error in I/O
 */
public static void writeCSV(OutputStream out, String uriPrefix, String folderContextRoot,
        List<VocabularyConcept> concepts, List<Triple<String, String, Integer>> attributesMeta)
        throws IOException {

    OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
    addBOM(out);

    List<String> toBeAddedToHeader = new ArrayList<String>();
    for (Triple<String, String, Integer> row : attributesMeta) {
        String lang = "";
        if (StringUtils.isNotEmpty(row.getCentral())) {
            lang = "@" + row.getCentral();
        }
        int numOfElements = row.getRight();
        for (int i = 0; i < numOfElements; i++) {
            toBeAddedToHeader.add(row.getLeft() + lang);
        }
    }

    String[] entries = new String[CONCEPT_ENTRIES_COUNT + toBeAddedToHeader.size()];
    addFixedEntryHeaders(entries);

    for (int i = 0; i < toBeAddedToHeader.size(); i++) {
        entries[i + CONCEPT_ENTRIES_COUNT] = toBeAddedToHeader.get(i);
    }

    CSVWriter writer = new CSVWriter(osw, ',');
    writer.writeNext(entries);

    DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");

    for (VocabularyConcept c : concepts) {
        int elemPos = 0;
        String value = "";
        List<DataElement> attributeElems = null;

        // add fixed entries
        entries = new String[CONCEPT_ENTRIES_COUNT + toBeAddedToHeader.size()];
        entries[URI_INDEX] = uriPrefix + c.getIdentifier();
        entries[LABEL_INDEX] = c.getLabel();
        entries[DEFINITION_INDEX] = c.getDefinition();
        entries[NOTATION_INDEX] = c.getNotation();
        entries[STATUS_INDEX] = c.getStatus().getLabel();
        entries[ACCEPTED_DATE_INDEX] = c.getAcceptedDate() != null ? dateFormatter.format(c.getAcceptedDate())
                : "";

        // add extra fields
        for (Triple<String, String, Integer> row : attributesMeta) {
            String elemName = row.getLeft();

            attributeElems = VocabularyOutputHelper.getDataElementValuesByNameAndLang(elemName,
                    row.getCentral(), c.getElementAttributes());

            int sizeOfAttributeElems = 0;
            if (attributeElems != null) {
                sizeOfAttributeElems = attributeElems.size();
                for (int j = 0; j < sizeOfAttributeElems; j++) {
                    DataElement e = attributeElems.get(j);
                    if (e.isRelationalElement()) {
                        value = e.getRelatedConceptUri();
                    } else if (StringUtils.isNotEmpty(e.getRelatedConceptIdentifier())
                            && StringUtils.isNotEmpty(e.getDatatype())
                            && e.getDatatype().equalsIgnoreCase("reference")) {
                        value = folderContextRoot + e.getRelatedConceptIdentifier();
                    } else {
                        value = e.getAttributeValue();
                    }
                    // value = "\"" + value + "\"";
                    entries[CONCEPT_ENTRIES_COUNT + elemPos + j] = value;
                }
            }

            int maximumNumberOfElements = row.getRight();
            // add missing columns
            for (int j = sizeOfAttributeElems; j < maximumNumberOfElements; j++) {
                entries[CONCEPT_ENTRIES_COUNT + elemPos + j] = null;
            }

            elemPos += maximumNumberOfElements;
        }
        writer.writeNext(entries);
    }
    writer.close();
    osw.close();
}

From source file:davmail.exchange.dav.ExchangePropPatchMethod.java

protected byte[] generateRequestContent() {
    try {//from ww w. j av a 2 s  . c om
        // build namespace map
        int currentChar = 'e';
        final Map<String, Integer> nameSpaceMap = new HashMap<String, Integer>();
        final Set<PropertyValue> setPropertyValues = new HashSet<PropertyValue>();
        final Set<PropertyValue> deletePropertyValues = new HashSet<PropertyValue>();
        for (PropertyValue propertyValue : propertyValues) {
            // data type namespace
            if (!nameSpaceMap.containsKey(TYPE_NAMESPACE) && propertyValue.getTypeString() != null) {
                nameSpaceMap.put(TYPE_NAMESPACE, currentChar++);
            }
            // property namespace
            String namespaceUri = propertyValue.getNamespaceUri();
            if (!nameSpaceMap.containsKey(namespaceUri)) {
                nameSpaceMap.put(namespaceUri, currentChar++);
            }
            if (propertyValue.getXmlEncodedValue() == null) {
                deletePropertyValues.add(propertyValue);
            } else {
                setPropertyValues.add(propertyValue);
            }
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(baos, "UTF-8");
        writer.write("<D:propertyupdate xmlns:D=\"DAV:\"");
        for (Map.Entry<String, Integer> mapEntry : nameSpaceMap.entrySet()) {
            writer.write(" xmlns:");
            writer.write((char) mapEntry.getValue().intValue());
            writer.write("=\"");
            writer.write(mapEntry.getKey());
            writer.write("\"");
        }
        writer.write(">");
        if (!setPropertyValues.isEmpty()) {
            writer.write("<D:set><D:prop>");
            for (PropertyValue propertyValue : setPropertyValues) {
                String typeString = propertyValue.getTypeString();
                char nameSpaceChar = (char) nameSpaceMap.get(propertyValue.getNamespaceUri()).intValue();
                writer.write('<');
                writer.write(nameSpaceChar);
                writer.write(':');
                writer.write(propertyValue.getName());
                if (typeString != null) {
                    writer.write(' ');
                    writer.write(nameSpaceMap.get(TYPE_NAMESPACE));
                    writer.write(":dt=\"");
                    writer.write(typeString);
                    writer.write("\"");
                }
                writer.write('>');
                writer.write(propertyValue.getXmlEncodedValue());
                writer.write("</");
                writer.write(nameSpaceChar);
                writer.write(':');
                writer.write(propertyValue.getName());
                writer.write('>');
            }
            writer.write("</D:prop></D:set>");
        }
        if (!deletePropertyValues.isEmpty()) {
            writer.write("<D:remove><D:prop>");
            for (PropertyValue propertyValue : deletePropertyValues) {
                char nameSpaceChar = (char) nameSpaceMap.get(propertyValue.getNamespaceUri()).intValue();
                writer.write('<');
                writer.write(nameSpaceChar);
                writer.write(':');
                writer.write(propertyValue.getName());
                writer.write("/>");
            }
            writer.write("</D:prop></D:remove>");
        }
        writer.write("</D:propertyupdate>");
        writer.close();
        return baos.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.techventus.server.voice.Voice.java

/**
 * Posts a settings change.// w ww .j a v a2s  .  c  om
 *
 * @param requestURL the request url
 * @param paraString the para string
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 */
private String postSettings(URL requestURL, String paraString) throws IOException {
    String out = "";
    HttpURLConnection conn = (HttpURLConnection) requestURL.openConnection();
    conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    conn.setRequestProperty("User-agent", USER_AGENT);

    conn.setDoOutput(true);
    conn.setDoInput(true);

    OutputStreamWriter callwr = new OutputStreamWriter(conn.getOutputStream());
    callwr.write(paraString);
    callwr.flush();

    // Get the response
    conn.connect();
    int responseCode = conn.getResponseCode();
    if (PRINT_TO_CONSOLE)
        System.out.println(requestURL + " - " + conn.getResponseMessage());
    InputStream is;
    if (responseCode == 200) {
        is = conn.getInputStream();
    } else {
        is = conn.getErrorStream();
    }
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader callrd = new BufferedReader(isr);

    String line;
    while ((line = callrd.readLine()) != null) {
        out += line + "\n\r";
    }

    callwr.close();
    callrd.close();

    if (out.equals("")) {
        throw new IOException("No Response Data Received.");
    }

    if (PRINT_TO_CONSOLE)
        System.out.println(out);

    return out;
}

From source file:com.denimgroup.threadfix.service.defects.utils.RestUtilsImpl.java

@Nonnull
private InputStream postUrl(String urlString, String data, String username, String password,
        String contentType) {/* w ww  .  ja v  a2 s  .  co  m*/
    URL url;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        LOG.warn("URL used for POST was bad: '" + urlString + "'");
        throw new RestUrlException(e, "Received a malformed server URL.");
    }

    HttpURLConnection httpConnection = null;
    OutputStreamWriter outputWriter = null;
    try {
        if (proxyService == null) {
            httpConnection = (HttpURLConnection) url.openConnection();
        } else {
            httpConnection = proxyService.getConnectionWithProxyConfig(url, classToProxy);
        }

        setupAuthorization(httpConnection, username, password);

        httpConnection.addRequestProperty("Content-Type", contentType);
        httpConnection.addRequestProperty("Accept", contentType);

        httpConnection.setDoOutput(true);
        outputWriter = new OutputStreamWriter(httpConnection.getOutputStream());
        outputWriter.write(data);
        outputWriter.flush();

        InputStream is = httpConnection.getInputStream();

        return is;
    } catch (IOException e) {
        LOG.warn("IOException encountered trying to post to URL with message: " + e.getMessage());
        if (httpConnection == null) {
            LOG.warn(
                    "HTTP connection was null so we cannot do further debugging of why the HTTP request failed");
        } else {
            try {
                InputStream errorStream = httpConnection.getErrorStream();
                if (errorStream == null) {
                    LOG.warn("Error stream from HTTP connection was null");
                } else {
                    LOG.warn(
                            "Error stream from HTTP connection was not null. Attempting to get response text.");
                    setPostErrorResponse(IOUtils.toString(errorStream));
                    LOG.warn("Error text in response was '" + getPostErrorResponse() + "'");
                    throw new RestIOException(e, getPostErrorResponse(),
                            "Unable to get response from server. Error text was: " + getPostErrorResponse(),
                            getStatusCode(httpConnection));
                }
            } catch (IOException e2) {
                LOG.warn("IOException encountered trying to read the reason for the previous IOException: "
                        + e2.getMessage(), e2);
                throw new RestIOException(e2, "Unable to read response from server." + e2.getMessage(),
                        getStatusCode(httpConnection));
            }
        }
        throw new RestIOException(e, "Unable to read response from server." + e.toString());
    } finally {
        if (outputWriter != null) {
            try {
                outputWriter.close();
            } catch (IOException e) {
                LOG.warn("Failed to close output stream in postUrl.", e);
            }
        }
    }
}

From source file:geotheme.servlet.wms.java

/**
 * @see HttpServlet#service(HttpServletRequest req, HttpServletResponse res)
 *///from  w  ww  .  j  a v a  2  s  . com
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    OutputStreamWriter wr = null;
    InputStream in = null;
    OutputStream out = null;

    //req.setCharacterEncoding("UTF-8");

    try {
        Map<String, Object> reqMap = new HashMap<String, Object>();

        Enumeration<?> en = req.getParameterNames();
        String key = new String();

        /**
         * Converting all Map Keys into Upper Case
         **/
        while (en.hasMoreElements()) {
            key = (String) en.nextElement();
            reqMap.put(key.toUpperCase(), req.getParameter(key));
        }

        wmsParamBean wmsBean = new wmsParamBean();
        BeanUtils.populate(wmsBean, reqMap);

        HttpSession session = req.getSession(true);

        /**
         * Reading the saved SLD
         **/
        String sessionName = wmsBean.getLAYER();

        if (sessionName.length() < 1)
            sessionName = wmsBean.getLAYERS();

        if (session.getAttribute(sessionName) != null) {

            wmsBean.setSLD_BODY((String) session.getAttribute(sessionName));
            wmsBean.setSLD("");
            wmsBean.setSTYLES("");
        }

        if (wmsBean.getREQUEST().compareToIgnoreCase("GetPDFGraphic") == 0) {
            /**
             * Generate PDF Request
             */
            generatePDF pdf = new generatePDF(this.pdfURL, this.pdfLayers);

            ByteArrayOutputStream baos = pdf.createPDFFromImage(wmsBean, this.geoserverURL);

            res.addHeader("Content-Type", "application/force-download");
            res.addHeader("Content-Disposition", "attachment; filename=\"MapOutput.pdf\"");

            res.getOutputStream().write(baos.toByteArray());
        } else {
            /**
             * Generating Map from GeoServer
             **/
            URL geoURL = new URL(this.geoserverURL);

            URLConnection geoConn = geoURL.openConnection();
            geoConn.setDoOutput(true);

            wr = new OutputStreamWriter(geoConn.getOutputStream(), "UTF-8");
            wr.write(wmsBean.getURL_PARAM());
            wr.flush();

            in = geoConn.getInputStream();
            out = res.getOutputStream();

            res.setContentType(wmsBean.getFORMAT());

            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
        }
    } catch (Exception e) {
        //e.printStackTrace();
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
        if (in != null) {
            in.close();
        }
        if (wr != null) {
            wr.close();
        }
    }
}

From source file:edu.ur.ir.ir_export.service.DefaultCollectionExportService.java

/**
 * Generate an xml file with the specified collections.
 * /*from w w w .  ja va2 s.  c  o m*/
 * @see edu.ur.dspace.export.CollectionExporter#generateCollectionXMLFile(java.io.File, java.util.Collection)
 */
public Set<FileInfo> createXmlFile(File f, Collection<InstitutionalCollection> collections,
        boolean includeChildren) throws IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    Set<FileInfo> allPictures = new HashSet<FileInfo>();
    String path = FilenameUtils.getPath(f.getCanonicalPath());
    if (!path.equals("")) {
        File pathOnly = new File(FilenameUtils.getFullPath(f.getCanonicalPath()));
        FileUtils.forceMkdir(pathOnly);
    }

    if (!f.exists()) {
        if (!f.createNewFile()) {
            throw new IllegalStateException("could not create file");
        }
    }

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException(e);
    }

    DOMImplementation impl = builder.getDOMImplementation();
    DOMImplementationLS domLs = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = domLs.createLSSerializer();
    LSOutput lsOut = domLs.createLSOutput();

    Document doc = impl.createDocument(null, "institutionalCollections", null);
    Element root = doc.getDocumentElement();

    FileOutputStream fos;
    OutputStreamWriter outputStreamWriter;
    BufferedWriter writer;

    try {
        fos = new FileOutputStream(f);

        try {
            outputStreamWriter = new OutputStreamWriter(fos, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
        writer = new BufferedWriter(outputStreamWriter);
        lsOut.setCharacterStream(writer);
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(e);
    }

    // create XML for the child collections
    for (InstitutionalCollection c : collections) {
        Element collection = doc.createElement("collection");

        this.addIdElement(collection, c.getId().toString(), doc);
        this.addNameElement(collection, c.getName(), doc);
        this.addDescription(collection, c.getDescription(), doc);
        this.addCopyright(collection, c.getCopyright(), doc);

        if (c.getPrimaryPicture() != null) {
            this.addPrimaryImage(collection, c.getPrimaryPicture().getFileInfo().getNameWithExtension(), doc);
            allPictures.add(c.getPrimaryPicture().getFileInfo());
        }
        Set<IrFile> pictures = c.getPictures();

        if (pictures.size() > 0) {
            Element pics = doc.createElement("pictures");
            for (IrFile irFile : pictures) {
                Element picture = doc.createElement("picture");
                this.addImage(picture, irFile.getFileInfo().getNameWithExtension(), doc);
                pics.appendChild(picture);
                allPictures.add(irFile.getFileInfo());
            }
            collection.appendChild(pics);
        }

        if (c.getLinks().size() > 0) {
            Element links = doc.createElement("links");
            for (InstitutionalCollectionLink l : c.getLinks()) {
                this.addLink(links, l, doc);
            }
            collection.appendChild(links);
        }

        if (includeChildren) {
            for (InstitutionalCollection child : c.getChildren()) {
                addChild(child, collection, doc, allPictures);
            }
        }
        root.appendChild(collection);
    }
    serializer.write(root, lsOut);

    try {
        fos.close();
        writer.close();
        outputStreamWriter.close();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    return allPictures;
}

From source file:be.fedict.eidviewer.lib.file.imports.Version35CSVFile.java

public static void toCSV(Version35CSVFile v35File, OutputStream outputStream) throws Exception {
    /* version;type;name;surname;gender;date_of_birth;location_of_birth;nobility;nationality;
    national_nr;special_organization;member_of_family;special_status;logical_nr;chip_nr;
    date_begin;date_end;issuing_municipality;version;street;zip;municipality;country;
    file_id;file_id_sign;file_address;file_address_sign; */

    /* picturedata;picturehash */

    /*/*from   w  ww  . jav a 2 s. c om*/
    serial_nr;component_code;os_nr;os_version;softmask_nr;softmask_version;applet_version;
    global_os_version;applet_interface_version;PKCS1_support;key_exchange_version;
    application_lifecycle;graph_perso;elec_perso;elec_perso_interface;
    */

    /* challenge, response */

    /*
     * RRN Cert
     */

    /*
    certificatescount;certificate1;certificate2;...
    */

    /*
     * PIN codes
     */

    DateFormat dottyDate = new SimpleDateFormat("dd.MM.yyyy");

    OutputStreamWriter writer = new OutputStreamWriter(outputStream);

    logger.finest(TextFormatHelper.dateToRRNDate(v35File.identity.dateOfBirth.getTime()).toUpperCase());

    // write all fixed pos data
    writer.write(String.format(
            "1;eid;;%02d;%s;%s;%c;%s;%s;%s;%s;%s;%s;%s;%s;%1d;%s;%s;%s;%s;%s;;%s;%s;%s;be;;;;;%s;;;;;;;;;;;;;;;;;;;;;RRN;1;%s;;",
            v35File.identity.documentType.getKey(), v35File.identity.firstName, v35File.identity.name,
            (v35File.identity.gender == Gender.FEMALE ? 'F' : 'M'),
            TextFormatHelper.dateToRRNDate(v35File.identity.dateOfBirth.getTime()).toUpperCase(),
            v35File.identity.placeOfBirth,
            (v35File.identity.nobleCondition != null ? v35File.identity.nobleCondition : ""),
            v35File.identity.nationality, v35File.identity.nationalNumber,
            (v35File.identity.duplicate != null ? v35File.identity.duplicate : ""),
            (v35File.identity.specialOrganisation != null ? v35File.identity.specialOrganisation : ""),
            (v35File.identity.memberOfFamily ? "1" : ""),
            (v35File.identity.specialStatus != null ? v35File.identity.specialStatus.ordinal() : 0),
            // logicalNumber
            v35File.identity.cardNumber, v35File.identity.chipNumber,
            dottyDate.format(v35File.identity.cardValidityDateBegin.getTime()),
            dottyDate.format(v35File.identity.cardValidityDateEnd.getTime()),
            v35File.identity.cardDeliveryMunicipality,
            // version
            v35File.address.streetAndNumber, v35File.address.zip, v35File.address.municipality,
            // file_id
            // file_id_sign
            // file_address
            // file_address_sign
            X509Utilities.eidBase64Encode(v35File.photo),
            // picturehash
            // serial_nr
            // component_code
            // os_nr
            // os_version
            // softmask_nr
            // softmask_version
            // applet_version
            // global_os_version
            // applet_interface_version
            // PKCS1_support
            // key_exchange_version
            // application_lifecycle
            // graph_perso
            // elec_perso
            // elec_perso_interface
            // challenge
            // response
            X509Utilities.eidBase64Encode(v35File.rrnCert.getEncoded())));

    // write variable number of certificates
    int ncerts = 0;
    if (v35File.authenticationCert != null)
        ncerts++;
    if (v35File.signingCert != null)
        ncerts++;
    if (v35File.citizenCert != null)
        ncerts++;
    if (v35File.rootCert != null)
        ncerts++;
    writer.write(String.format("%d;", ncerts));
    if (v35File.authenticationCert != null)
        X509CertToCSV(v35File.authenticationCert, "Authentication", writer);
    if (v35File.signingCert != null)
        X509CertToCSV(v35File.signingCert, "Signature", writer);
    if (v35File.citizenCert != null)
        X509CertToCSV(v35File.citizenCert, "CA", writer);
    if (v35File.rootCert != null)
        X509CertToCSV(v35File.rootCert, "Root", writer);

    // write variable number of pin codes..
    writer.write("0"); // zero PIN codes in this file
    writer.flush();
    writer.close();

}

From source file:com.izforge.izpack.compiler.CompilerConfig.java

/**
 * Adds the resources.//  w w w  . j ava  2s  . c om
 *
 * @param data The XML data.
 * @throws CompilerException Description of the Exception
 */
protected void addResources(IXMLElement data) throws CompilerException {
    notifyCompilerListener("addResources", CompilerListener.BEGIN, data);
    IXMLElement root = data.getFirstChildNamed("resources");
    if (root == null) {
        return;
    }

    // We process each res markup
    for (IXMLElement resNode : root.getChildrenNamed("res")) {
        String id = xmlCompilerHelper.requireAttribute(resNode, "id");
        String src = xmlCompilerHelper.requireAttribute(resNode, "src");
        // the parse attribute causes substitution to occur
        boolean substitute = xmlCompilerHelper.validateYesNoAttribute(resNode, "parse", NO);
        // the parsexml attribute causes the xml document to be parsed
        boolean parsexml = xmlCompilerHelper.validateYesNoAttribute(resNode, "parsexml", NO);

        String encoding = resNode.getAttribute("encoding");
        if (encoding == null) {
            encoding = "";
        }

        // basedir is not prepended if src is already an absolute path
        URL originalUrl = resourceFinder.findProjectResource(src, "Resource", resNode);
        URL url = originalUrl;

        InputStream is = null;
        OutputStream os = null;
        try {
            if (parsexml || (!"".equals(encoding)) || (substitute && !packager.getVariables().isEmpty())) {
                // make the substitutions into a temp file
                File parsedFile = FileUtils.createTempFile("izpp", null);
                parsedFile.deleteOnExit();
                FileOutputStream outFile = new FileOutputStream(parsedFile);
                os = new BufferedOutputStream(outFile);
                // and specify the substituted file to be added to the
                // packager
                url = parsedFile.toURI().toURL();
            }

            if (!"".equals(encoding)) {
                File recodedFile = FileUtils.createTempFile("izenc", null);
                recodedFile.deleteOnExit();

                InputStreamReader reader = new InputStreamReader(originalUrl.openStream(), encoding);
                OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(recodedFile), "UTF-8");

                char[] buffer = new char[1024];
                int read;
                while ((read = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, read);
                }
                reader.close();
                writer.close();
                if (parsexml) {
                    originalUrl = recodedFile.toURI().toURL();
                } else {
                    url = recodedFile.toURI().toURL();
                }
            }

            if (parsexml) {
                IXMLParser parser = new XMLParser();
                // this constructor will open the specified url (this is
                // why the InputStream is not handled in a similar manner
                // to the OutputStream)

                IXMLElement xml = parser.parse(originalUrl);
                IXMLWriter writer = new XMLWriter();
                if (substitute && !packager.getVariables().isEmpty()) {
                    // if we are also performing substitutions on the file
                    // then create an in-memory copy to pass to the
                    // substitutor
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    writer.setOutput(baos);
                    is = new ByteArrayInputStream(baos.toByteArray());
                } else {
                    // otherwise write direct to the temp file
                    writer.setOutput(os);
                }
                writer.write(xml);
            }

            // substitute variable values in the resource if parsed
            if (substitute) {
                if (packager.getVariables().isEmpty()) {
                    // reset url to original.
                    url = originalUrl;
                    assertionHelper.parseWarn(resNode,
                            "No variables defined. " + url.getPath() + " not parsed.");
                } else {
                    SubstitutionType type = SubstitutionType.lookup(resNode.getAttribute("type"));

                    // if the xml parser did not open the url
                    // ('parsexml' was not enabled)
                    if (null == is) {
                        is = new BufferedInputStream(originalUrl.openStream());
                    }
                    // VariableSubstitutor vs = new
                    // VariableSubstitutorImpl(compiler.getVariables());
                    variableSubstitutor.substitute(is, os, type, "UTF-8");
                }
            }

        } catch (Exception e) {
            assertionHelper.parseError(resNode, e.getMessage(), e);
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    // ignore as there is nothing we can realistically do
                    // so lets at least try to close the input stream
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    // ignore as there is nothing we can realistically do
                }
            }
        }

        packager.addResource(id, url);

        // remembering references to all added packsLang.xml files
        if (id.startsWith("packsLang.xml")) {
            List<URL> packsLangURLs;
            if (packsLangUrlMap.containsKey(id)) {
                packsLangURLs = packsLangUrlMap.get(id);
            } else {
                packsLangURLs = new ArrayList<URL>();
                packsLangUrlMap.put(id, packsLangURLs);
            }
            packsLangURLs.add(url);
        } else if (id.startsWith(UserInputPanel.SPEC_FILE_NAME)) {
            // Check user input panel definitions
            IXMLElement xml = new XMLParser().parse(url);
            for (IXMLElement userPanelDef : xml.getChildrenNamed(UserInputPanel.NODE_ID)) {
                String userPanelId = xmlCompilerHelper.requireAttribute(userPanelDef, "id");
                if (userInputPanelIds == null) {
                    userInputPanelIds = new HashSet<String>();
                }
                if (!userInputPanelIds.add(userPanelId)) {
                    assertionHelper.parseError(xml, "Resource " + UserInputPanel.SPEC_FILE_NAME
                            + ": Duplicate user input panel identifier '" + userPanelId + "'");
                }
            }
        }
    }
    notifyCompilerListener("addResources", CompilerListener.END, data);
}