Example usage for java.io OutputStream toString

List of usage examples for java.io OutputStream toString

Introduction

In this page you can find the example usage for java.io OutputStream toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:ch.cyberduck.core.Path.java

/**
 * Will copy from in to out. Will attempt to skip Status#getCurrent
 * from the inputstream but not from the outputstream. The outputstream
 * is asssumed to append to a already existing file if
 * Status#getCurrent > 0//from   w ww.ja v  a  2  s .  c  o  m
 *
 * @param out      The stream to write to
 * @param in       The stream to read from
 * @param throttle The bandwidth limit
 * @param l        The stream listener to notify about bytes received and sent
 * @param offset   Start reading at offset in file
 * @param limit    Transfer only up to this length
 * @param status   Transfer status
 * @throws IOResumeException           If the input stream fails to skip the appropriate
 *                                     number of bytes
 * @throws IOException                 Write not completed due to a I/O problem
 * @throws ConnectionCanceledException When transfer is interrupted by user setting the
 *                                     status flag to cancel.
 */
protected void upload(final OutputStream out, final InputStream in, final BandwidthThrottle throttle,
        final StreamListener l, long offset, final long limit, final TransferStatus status) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("upload(" + out.toString() + ", " + in.toString());
    }
    this.getSession()
            .message(MessageFormat.format(Locale.localizedString("Uploading {0}", "Status"), this.getName()));

    if (offset > 0) {
        long skipped = in.skip(offset);
        if (log.isInfoEnabled()) {
            log.info(String.format("Skipping %d bytes", skipped));
        }
        if (skipped < status.getCurrent()) {
            throw new IOResumeException(
                    String.format("Skipped %d bytes instead of %d", skipped, status.getCurrent()));
        }
    }
    this.transfer(in, new ThrottledOutputStream(out, throttle), l, limit, status);
}

From source file:org.codehaus.mojo.VeraxxMojo.java

protected void preExecute(Executor exec, CommandLine commandLine, Map enviro) throws MojoExecutionException {
    OutputStream outStream = /*System.out;*/new ByteArrayOutputStream();
    OutputStream errStream = new ByteArrayOutputStream();

    CommandLine commandLineCheck = new CommandLine(getExecutable());
    Executor execCheck = new DefaultExecutor();
    String[] args = parseCommandlineArgs("--version");
    commandLineCheck.addArguments(args, false);
    execCheck.setWorkingDirectory(exec.getWorkingDirectory());

    getLog().info("Executing command line: " + commandLineCheck);

    int res = 0;//from   w w w  . j  a  va  2  s. c o  m
    try {
        res = executeCommandLine(execCheck, commandLineCheck, enviro, outStream/*getOutputStreamOut()*/,
                errStream/*getOutputStreamErr()*/, getInputStream());
    } catch (ExecuteException e) {
        getLog().info(
                "Exec Exception while detecting Vera++ version. Assume old Vera++ v1.1.x (and less) output parsing style");
        getLog().info("Vera++ err output is : " + errStream.toString());
        veraxx_version = 0;
        /*throw new MojoExecutionException( "preExecute Command execution failed.", e );*/
        return;
    } catch (IOException e) {
        getLog().info("Vera++ detected version is : " + outStream.toString());
        getLog().info("Vera++ err output is : " + errStream.toString());
        // due to jdk8 bug :: https://bugs.openjdk.java.net/browse/JDK-8054565
        // we use this dirty try/catch ...
        // because this quick command line call can close the output stream before jvm does
        getLog().info("jvm " + System.getProperty("java.version") + " (8u11 - 9) workaround, ignoring a "
                + e.toString() + " during vera++ test command line.");
        //throw new MojoExecutionException( "preExecute Command execution failed.", e );
    }

    if (isResultCodeAFailure(res)) {
        getLog().info("Vera++ returned a failure result code : " + res);
        //throw new MojoExecutionException( "preExecute Result of " + commandLineCheck + " execution is: '" + res + "'." );
    }
    DefaultArtifactVersion newFormatMinVersion = new DefaultArtifactVersion("1.2.0");
    DefaultArtifactVersion currentVeraVersion = new DefaultArtifactVersion(outStream.toString());

    getLog().debug("Vera++ detected version is : " + outStream.toString());
    getLog().debug("Vera++ version as ArtefactVersion is : " + currentVeraVersion.toString());

    if (currentVeraVersion.compareTo(newFormatMinVersion) < 0) {
        getLog().info("Use old Vera++ v1.1.x (and less) output parsing style");
        veraxx_version = 0;
    } else {
        getLog().info("Use Vera++ v1.2.0 (and more) output parsing style");
        veraxx_version = 1;
    }
}

From source file:org.apache.maven.plugin.cxx.VeraxxMojo.java

@Override
protected void preExecute(Executor exec, CommandLine commandLine, Properties enviro)
        throws MojoExecutionException {
    OutputStream outStream = /*System.out;*/new ByteArrayOutputStream();
    OutputStream errStream = new ByteArrayOutputStream();

    CommandLine commandLineCheck = new CommandLine(getExecutable());
    Executor execCheck = new DefaultExecutor();
    String[] args = parseCommandlineArgs("--version");
    commandLineCheck.addArguments(args, false);
    execCheck.setWorkingDirectory(exec.getWorkingDirectory());

    getLog().info("Executing command line: " + commandLineCheck);

    int res = 0;//from www .ja v a2s  .c om
    try {
        res = ExecutorService.executeCommandLine(execCheck, commandLineCheck, enviro,
                outStream/*getOutputStreamOut()*/, errStream/*getOutputStreamErr()*/, getInputStream());
    } catch (ExecuteException e) {
        getLog().info("Exec Exception while detecting Vera++ version."
                + " Assume old Vera++ v1.1.x (and less) output parsing style");
        getLog().info("Vera++ err output is : " + errStream.toString());
        veraxxVersion = 0;
        /*throw new MojoExecutionException( "preExecute Command execution failed.", e );*/
        return;
    } catch (IOException e) {
        getLog().info("Vera++ detected version is : " + outStream.toString());
        getLog().info("Vera++ err output is : " + errStream.toString());
        // due to jdk8 bug :: https://bugs.openjdk.java.net/browse/JDK-8054565
        // we use this dirty try/catch ...
        // because this quick command line call can close the output stream before jvm does
        getLog().info("jvm " + System.getProperty("java.version") + " (8u11 - 9) workaround, ignoring a "
                + e.toString() + " during vera++ test command line.");
        //throw new MojoExecutionException( "preExecute Command execution failed.", e );
    }

    if (isResultCodeAFailure(res)) {
        getLog().info("Vera++ returned a failure result code : " + res);
        //throw new MojoExecutionException( "preExecute Result of " + commandLineCheck 
        //    + " execution is: '" + res + "'." );
    }
    DefaultArtifactVersion newFormatMinVersion = new DefaultArtifactVersion("1.2.0");
    DefaultArtifactVersion currentVeraVersion = new DefaultArtifactVersion(outStream.toString());

    getLog().debug("Vera++ detected version is : " + outStream.toString());
    getLog().debug("Vera++ version as ArtefactVersion is : " + currentVeraVersion.toString());

    if (currentVeraVersion.compareTo(newFormatMinVersion) < 0) {
        getLog().info("Use old Vera++ v1.1.x (and less) output parsing style");
        veraxxVersion = 0;
    } else {
        getLog().info("Use Vera++ v1.2.0 (and more) output parsing style");
        veraxxVersion = 1;
    }
}

From source file:info.rmapproject.api.responsemgr.DiscoResponseManager.java

/**
 * Using URI Provided, retrieves either the latest version or requested version of an RMap DiSCO 
 * in RDF format specified and forms an HTTP response.
 *
 * @param strDiscoUri the DiSCO URI/*from   w  w  w . ja  v  a  2  s  .c  om*/
 * @param returnType the RDF return type
 * @param viewLatestVersion true if view latest version
 * @return HTTP Response
 * @throws RMapApiException the RMap API exception
 */
private Response getRMapDiSCO(String strDiscoUri, RdfMediaType returnType, Boolean viewLatestVersion)
        throws RMapApiException {
    boolean reqSuccessful = false;
    Response response = null;
    try {

        log.info("DiSCO " + strDiscoUri + " requested.");

        if (strDiscoUri == null || strDiscoUri.length() == 0) {
            throw new RMapApiException(ErrorCode.ER_NO_OBJECT_URI_PROVIDED);
        }
        if (returnType == null) {
            returnType = Constants.DEFAULT_RDF_TYPE;
        }
        if (viewLatestVersion == null) {
            viewLatestVersion = false;
        }

        URI uriDiscoUri = null;
        try {
            strDiscoUri = URLDecoder.decode(strDiscoUri, "UTF-8");
            uriDiscoUri = new URI(strDiscoUri);
        } catch (Exception ex) {
            throw RMapApiException.wrap(ex, ErrorCode.ER_PARAM_WONT_CONVERT_TO_URI);
        }

        RMapDiSCODTO rmapDiscoDTO;

        if (viewLatestVersion) {
            rmapDiscoDTO = rmapService.getDiSCODTOLatestVersion(uriDiscoUri);
            //now we are using a different disco URI
            uriDiscoUri = rmapDiscoDTO.getRMapDiSCO().getId().getIri();
            strDiscoUri = uriDiscoUri.toString();
        } else {
            ;
            rmapDiscoDTO = rmapService.readDiSCODTO(uriDiscoUri);
        }

        log.info("DiSCO " + strDiscoUri + " object retrieved.");

        if (rmapDiscoDTO == null) {
            throw new RMapApiException(ErrorCode.ER_CORE_READ_DISCO_RETURNED_NULL);
        }

        //OutputStream discoOutput = rdfHandler.disco2Rdf(rmapDisco, returnType.getRdfType());
        OutputStream discoOutput = rdfHandler.disco2Rdf(rmapDiscoDTO.getRMapDiSCO(), returnType.getRdfType());
        if (discoOutput == null) {
            throw new RMapApiException(ErrorCode.ER_CORE_RDFHANDLER_OUTPUT_ISNULL);
        }

        log.info("DiSCO " + strDiscoUri + " converted to RDF.");

        String linkRel = buildGetDiscoLinks(rmapDiscoDTO);

        response = Response.status(Response.Status.OK).entity(discoOutput.toString())
                .location(new URI(Utils.makeDiscoUrl(strDiscoUri))).header("Link", linkRel) //switch this to link() or links()?
                .type(HttpTypeMediator.getResponseRMapMediaType("disco", returnType.getRdfType())) //TODO move version number to a property?
                .build();

        reqSuccessful = true;

    } catch (RMapApiException ex) {
        throw RMapApiException.wrap(ex);
    } catch (RMapDefectiveArgumentException ex) {
        throw RMapApiException.wrap(ex, ErrorCode.ER_GET_DISCO_BAD_ARGUMENT);
    } catch (RMapDiSCONotFoundException ex) {
        throw RMapApiException.wrap(ex, ErrorCode.ER_DISCO_OBJECT_NOT_FOUND);
    } catch (RMapTombstonedObjectException ex) {
        throw RMapApiException.wrap(ex, ErrorCode.ER_DISCO_TOMBSTONED);
    } catch (RMapDeletedObjectException ex) {
        throw RMapApiException.wrap(ex, ErrorCode.ER_DISCO_DELETED);
    } catch (RMapObjectNotFoundException ex) {
        throw RMapApiException.wrap(ex, ErrorCode.ER_OBJECT_NOT_FOUND);
    } catch (RMapException ex) {
        throw RMapApiException.wrap(ex, ErrorCode.ER_CORE_GENERIC_RMAP_EXCEPTION);
    } catch (Exception ex) {
        throw RMapApiException.wrap(ex, ErrorCode.ER_UNKNOWN_SYSTEM_ERROR);
    } finally {
        if (rmapService != null)
            rmapService.closeConnection();
        if (!reqSuccessful && response != null)
            response.close();
    }
    return response;
}

From source file:org.kitodo.imagemanagementmodule.ConvertRunner.java

/**
 * Executes the ImageMagick command using Apache Commons Exec.
 *
 * @param commandLine//from   w  w w  .  ja  va 2  s  .c om
 *            command line to execute
 * @throws IOException
 *             if I/O fails
 */
void run(IMOperation commandLine) throws IOException {
    Executor executor = new DefaultExecutor();

    OutputStream outAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outAndErr));

    long timeoutMillis = 1000
            * Config.getIntParameter("ImageManagementModule.timeoutSec", DEFAULT_TIMEOUT_MINS);
    executor.setWatchdog(new ExecuteWatchdog(timeoutMillis));

    CommandLine command;
    try {
        String sshHosts = Config.getParameter("ImageManagementModule.sshHosts");
        command = new CommandLine("ssh");
        String[] hosts = sshHosts.split(",");
        String host = hosts[RANDOMNESS_GENERATOR.nextInt(hosts.length)];
        command.addArgument(host, false);
        command.addArgument(convertCommand + ' ' + commandLine.toString(), false);
    } catch (NoSuchElementException e) {
        logger.trace("SSH not configured.", e);
        command = new CommandLine(convertCommand);
        command.addArguments(commandLine.toString());
    }

    try {
        logger.debug("Executing: {}", command);
        logger.trace("Timeout: {} mins", timeoutMillis / 60000d);
        executor.execute(command);
        logger.debug("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
    } catch (IOException | RuntimeException e) {
        logger.error("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
        throw e;
    }
}

From source file:org.kitodo.imagemanagement.ConvertRunner.java

/**
 * Executes the ImageMagick command using Apache Commons Exec.
 *
 * @param commandLine/*from   w w w. j  ava2 s  . c  om*/
 *            command line to execute
 * @throws IOException
 *             if I/O fails
 */
void run(IMOperation commandLine) throws IOException {
    Executor executor = new DefaultExecutor();

    OutputStream outAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outAndErr));

    long timeoutMillis = 1000
            * KitodoConfig.getIntParameter(ParameterImageManagement.TIMEOUT_SEC, DEFAULT_TIMEOUT_MINS);
    executor.setWatchdog(new ExecuteWatchdog(timeoutMillis));

    CommandLine command;
    try {
        String sshHosts = KitodoConfig.getParameter(ParameterImageManagement.SSH_HOST);
        command = new CommandLine("ssh");
        String[] hosts = sshHosts.split(",");
        String host = hosts[RANDOMNESS_GENERATOR.nextInt(hosts.length)];
        command.addArgument(host, false);
        command.addArgument(convertCommand + ' ' + commandLine.toString(), false);
    } catch (NoSuchElementException e) {
        logger.trace("SSH not configured.", e);
        command = new CommandLine(convertCommand);
        command.addArguments(commandLine.toString());
    }

    try {
        logger.debug("Executing: {}", command);
        logger.trace("Timeout: {} mins", timeoutMillis / 60000d);
        executor.execute(command);
        logger.debug("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
    } catch (IOException | RuntimeException e) {
        logger.error("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
        throw e;
    }
}

From source file:org.sdm.spa.actors.transport.SrmliteCopier.java

@Override
protected CopyResult copyTo(String srcFile, ConnectionDetails destDetails, String destFile, boolean recursive)
        throws SshException {
    int exitCode = 0;
    String cmdWithPath = null;//www  .  j  av a 2s  . c  o  m

    StringBuffer cmd = new StringBuffer(100);
    LocalExec localObject = new LocalExec();
    localObject.setTimeout(timeout, false, false);
    String[] srcFileList = null;
    String[] srcFile_list = null;
    StringBuffer warn = new StringBuffer(100);
    boolean warn_flag = false;
    String osname = (System.getProperty("os.name")).toLowerCase();
    String cmdFile = "srmlite_" + System.currentTimeMillis() + ".xml";
    String userhome = (System.getProperty("user.home")).toLowerCase();

    // srmlite -f xml_file -td target_directory
    if (srcFile.contains(",")) { // List of files is provided
        srcFileList = srcFile.split(",");
        srcFile_list = new String[srcFileList.length];
        for (int count = 0; count < srcFileList.length; count++) {
            if ((srcFileList[count].trim()).startsWith("/") || (srcFileList[count].trim()).startsWith(":/", 1)
                    || (srcFileList[count].trim()).contains(":\\")) {
                srcFile_list[count] = srcFileList[count].trim();
            } else {
                warn.append(srcFile_list[count].trim() + " ");
                if (!warn_flag)
                    warn_flag = true;
            }
        }
        if (warn_flag) {
            warn.append(" does not contain full path to the source file. Please provide full path. ");
            warn_flag = false;
        }
    }

    try {
        if (srcFile.contains(",")) {
            build_xml_ForLocalSource(userhome + File.separatorChar + cmdFile, srcFile_list, destFile);
        }
    } catch (Exception e) {// Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }

    if (srcFile.contains(",")) {
        // command format
        // "<path>/srmlite -f xml_input -td scp://user@host/<dest path>"
        if (osname.contains("windows"))
            cmd.append("srmlite.bat -f ");
        else
            cmd.append("srmlite -f ");
        cmd.append("file:///");
        cmd.append(userhome + File.separatorChar + cmdFile);
        cmd.append(" -td ");
        if (srmProtocol.equals("")) {
            cmd.append("scp://");
        } else {
            cmd.append(srmProtocol);
            cmd.append("://");
        }
        cmd.append(destDetails.toString());
        cmd.append(destFile);
        // cmd.append("/");
    } else {
        // command format
        // "<path>/srmlite -s file:////<srcfile> -t scp://user@host/<dest path>"
        if (osname.contains("windows"))
            cmd.append("srmlite.bat -s ");
        else
            cmd.append("srmlite -s ");
        cmd.append("\"");
        // Anand: might need file:////
        cmd.append("file:///");
        cmd.append(srcFile);
        cmd.append("\"");
        if (recursive)
            cmd.append(" -recursive");
        // TODO: We assume that target is always a directory.
        cmd.append(" -td ");

        if (srmProtocol.equals("")) {
            cmd.append("scp://");
        } else {
            cmd.append(srmProtocol);
            cmd.append("://");
        }

        cmd.append(destDetails.toString());
        // Anand: Commented because it shows as host@ip//root instead of
        // /root
        // cmd.append("/");
        cmd.append(destFile);
    }

    log.debug("Command without path = " + cmd);

    if (protocolPathSrc.equals("")) {
        if (osname.contains("windows")) {
            System.out.println("OSNAME WINDOWS*****************");
            cmdWithPath = cmd.toString();
        } else {
            cmdWithPath = getCmdWithDefaultPath(cmd);
        }
    } else {
        cmdWithPath = protocolPathSrc + cmd;
    }

    log.debug("*************Full command executed is ::  " + cmdWithPath);

    if (isDebugging)
        log.debug("copy cmd=" + cmdWithPath);
    OutputStream streamOut = new ByteArrayOutputStream();
    OutputStream streamErr = new ByteArrayOutputStream();
    try {
        exitCode = localObject.executeCmd(cmdWithPath, streamOut, streamErr, destDetails.toString());
    } catch (Exception e) {
        return new CopyResult(1, e.toString(), "");
    }
    if (isDebugging) {
        log.error("Output on stdout:" + streamOut);
        log.error("Output on stderr:" + streamErr);
    }
    String message = streamErr.toString();
    message = message + " \n\n" + streamOut.toString();
    String fileDeleteMsg = "";
    if (srcFile.contains(",")) {
        try {
            boolean success = false;
            success = localObject.deleteFile(cmdFile, false, false);
            if (success) {
                log.debug("deleted the xml script file " + cmdFile + " created for file copy");
            }
            if (!success) {
                log.warn("Unable to delete the xml script file " + cmdFile + " created for file copy");
                fileDeleteMsg = "Unable to delete the xml script file " + cmdFile + " created for file copy";
            }
        } catch (ExecException e) {
            log.warn("Unable to delete the xml script file " + cmdFile + " created for file copy : "
                    + e.toString());
        }
    }
    return new CopyResult(exitCode, message + fileDeleteMsg, "");
}

From source file:org.apache.vxquery.rest.service.VXQueryService.java

/**
 * Reads results from hyracks given the {@link HyracksJobContext} containing
 * {@link ResultSetId} and {@link JobId} mapping.
 *
 * @param jobContext//  ww w .  j a  va2s  .co  m
 *            mapoing between the {@link ResultSetId} and corresponding hyracks
 *            {@link JobId}
 * @return Results of the given query
 * @throws Exception
 *             IOErrors and etc
 */
private String readResults(HyracksJobContext jobContext) throws Exception {
    int nReaders = 1;

    if (hyracksDataset == null) {
        hyracksDataset = new HyracksDataset(hyracksClientConnection, jobContext.getFrameSize(), nReaders);
    }

    FrameManager resultDisplayFrameMgr = new FrameManager(jobContext.getFrameSize());
    IFrame frame = new VSizeFrame(resultDisplayFrameMgr);
    IHyracksDatasetReader reader = hyracksDataset.createReader(jobContext.getJobId(),
            jobContext.getResultSetId());
    OutputStream resultStream = new ByteArrayOutputStream();

    // This loop is required for XTests to reliably identify the error code of
    // SystemException.
    while (reader.getResultStatus() == DatasetJobRecord.Status.RUNNING) {
        Thread.sleep(100);
    }

    IFrameTupleAccessor frameTupleAccessor = new ResultFrameTupleAccessor();
    try (PrintWriter writer = new PrintWriter(resultStream, true)) {
        while (reader.read(frame) > 0) {
            writer.print(ResultUtils.getStringFromBuffer(frame.getBuffer(), frameTupleAccessor));
            writer.flush();
            frame.getBuffer().clear();
        }
    }

    hyracksClientConnection.waitForCompletion(jobContext.getJobId());
    LOGGER.log(Level.FINE,
            String.format("Result for resultId %d completed", jobContext.getResultSetId().getId()));
    return resultStream.toString();
}

From source file:org.openmrs.module.ModuleFileParser.java

/**
 * Get the module//from   w  ww  .  j  av a  2 s  . c o  m
 *
 * @return new module object
 */
public Module parse() throws ModuleException {

    Module module = null;
    JarFile jarfile = null;
    InputStream configStream = null;

    try {
        try {
            jarfile = new JarFile(moduleFile);
        } catch (IOException e) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.cannotGetJarFile"),
                    moduleFile.getName(), e);
        }

        // look for config.xml in the root of the module
        ZipEntry config = jarfile.getEntry("config.xml");
        if (config == null) {
            throw new ModuleException(Context.getMessageSourceService().getMessage("Module.error.noConfigFile"),
                    moduleFile.getName());
        }

        // get a config file stream
        try {
            configStream = jarfile.getInputStream(config);
        } catch (IOException e) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.cannotGetConfigFileStream"),
                    moduleFile.getName(), e);
        }

        // turn the config file into an xml document
        Document configDoc = null;
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            db.setEntityResolver(new EntityResolver() {

                @Override
                public InputSource resolveEntity(String publicId, String systemId)
                        throws SAXException, IOException {
                    // When asked to resolve external entities (such as a
                    // DTD) we return an InputSource
                    // with no data at the end, causing the parser to ignore
                    // the DTD.
                    return new InputSource(new StringReader(""));
                }
            });

            configDoc = db.parse(configStream);
        } catch (Exception e) {
            log.error("Error parsing config.xml: " + configStream.toString(), e);

            OutputStream out = null;
            String output = "";
            try {
                out = new ByteArrayOutputStream();
                // Now copy bytes from the URL to the output stream
                byte[] buffer = new byte[4096];
                int bytes_read;
                while ((bytes_read = configStream.read(buffer)) != -1) {
                    out.write(buffer, 0, bytes_read);
                }
                output = out.toString();
            } catch (Exception e2) {
                log.warn("Another error parsing config.xml", e2);
            } finally {
                try {
                    out.close();
                } catch (Exception e3) {
                }
            }

            log.error("config.xml content: " + output);
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.cannotParseConfigFile"),
                    moduleFile.getName(), e);
        }

        Element rootNode = configDoc.getDocumentElement();

        String configVersion = rootNode.getAttribute("configVersion").trim();

        if (!validConfigVersions.contains(configVersion)) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.invalidConfigVersion",
                            new Object[] { configVersion }, Context.getLocale()),
                    moduleFile.getName());
        }

        String name = getElement(rootNode, configVersion, "name").trim();
        String moduleId = getElement(rootNode, configVersion, "id").trim();
        String packageName = getElement(rootNode, configVersion, "package").trim();
        String author = getElement(rootNode, configVersion, "author").trim();
        String desc = getElement(rootNode, configVersion, "description").trim();
        String version = getElement(rootNode, configVersion, "version").trim();

        // do some validation
        if (name == null || name.length() == 0) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.nameCannotBeEmpty"),
                    moduleFile.getName());
        }
        if (moduleId == null || moduleId.length() == 0) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.idCannotBeEmpty"), name);
        }
        if (packageName == null || packageName.length() == 0) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.packageCannotBeEmpty"), name);
        }

        // create the module object
        module = new Module(name, moduleId, packageName, author, desc, version);

        // find and load the activator class
        module.setActivatorName(getElement(rootNode, configVersion, "activator").trim());

        module.setRequireDatabaseVersion(
                getElement(rootNode, configVersion, "require_database_version").trim());
        module.setRequireOpenmrsVersion(getElement(rootNode, configVersion, "require_version").trim());
        module.setUpdateURL(getElement(rootNode, configVersion, "updateURL").trim());
        module.setRequiredModulesMap(getRequiredModules(rootNode, configVersion));
        module.setAwareOfModulesMap(getAwareOfModules(rootNode, configVersion));
        module.setStartBeforeModulesMap(getStartBeforeModules(rootNode, configVersion));

        module.setAdvicePoints(getAdvice(rootNode, configVersion, module));
        module.setExtensionNames(getExtensions(rootNode, configVersion));

        module.setPrivileges(getPrivileges(rootNode, configVersion));
        module.setGlobalProperties(getGlobalProperties(rootNode, configVersion));

        module.setMessages(getMessages(rootNode, configVersion, jarfile, moduleId, version));

        module.setMappingFiles(getMappingFiles(rootNode, configVersion, jarfile));
        module.setPackagesWithMappedClasses(getPackagesWithMappedClasses(rootNode, configVersion));

        module.setConfig(configDoc);

        module.setMandatory(getMandatory(rootNode, configVersion, jarfile));

        module.setFile(moduleFile);

        module.setConditionalResources(getConditionalResources(rootNode));
    } finally {
        try {
            jarfile.close();
        } catch (Exception e) {
            log.warn("Unable to close jarfile: " + jarfile, e);
        }
        if (configStream != null) {
            try {
                configStream.close();
            } catch (Exception io) {
                log.error("Error while closing config stream for module: " + moduleFile.getAbsolutePath(), io);
            }
        }
    }

    return module;
}

From source file:org.saiku.repository.JackRabbitRepositoryManager.java

public byte[] exportRepository() throws RepositoryException, IOException {
    final ByteArrayOutputStream os2 = new ByteArrayOutputStream();
    final OutputStream os = new ByteArrayOutputStream();
    session.exportDocumentView("/", os, false, false);
    ZipOutputStream zs = new ZipOutputStream(os2);
    ZipEntry e = new ZipEntry("backup.xml");
    zs.putNextEntry(e);//from  w ww .  j  a v a 2s . co m
    zs.write(os.toString().getBytes());
    zs.closeEntry();
    zs.close();
    return os2.toByteArray();
}