Example usage for java.io BufferedOutputStream flush

List of usage examples for java.io BufferedOutputStream flush

Introduction

In this page you can find the example usage for java.io BufferedOutputStream flush.

Prototype

@Override
public synchronized void flush() throws IOException 

Source Link

Document

Flushes this buffered output stream.

Usage

From source file:org.apache.catalina.startup.HostConfig.java

/**
 * Deploy WAR files.//from w w  w .  j  a  v  a2s.c  o m
 */
protected void deployWARs(File appBase, String[] files) {

    for (int i = 0; i < files.length; i++) {

        if (files[i].equalsIgnoreCase("META-INF"))
            continue;
        if (files[i].equalsIgnoreCase("WEB-INF"))
            continue;
        if (deployed.contains(files[i]))
            continue;
        File dir = new File(appBase, files[i]);
        if (files[i].toLowerCase().endsWith(".war")) {

            deployed.add(files[i]);

            // Calculate the context path and make sure it is unique
            String contextPath = "/" + files[i];
            int period = contextPath.lastIndexOf(".");
            if (period >= 0)
                contextPath = contextPath.substring(0, period);
            if (contextPath.equals("/ROOT"))
                contextPath = "";
            if (host.findChild(contextPath) != null)
                continue;

            // Checking for a nested /META-INF/context.xml
            JarFile jar = null;
            JarEntry entry = null;
            InputStream istream = null;
            BufferedOutputStream ostream = null;
            File xml = new File(configBase, files[i].substring(0, files[i].lastIndexOf(".")) + ".xml");
            if (!xml.exists()) {
                try {
                    jar = new JarFile(dir);
                    entry = jar.getJarEntry("META-INF/context.xml");
                    if (entry != null) {
                        istream = jar.getInputStream(entry);
                        ostream = new BufferedOutputStream(new FileOutputStream(xml), 1024);
                        byte buffer[] = new byte[1024];
                        while (true) {
                            int n = istream.read(buffer);
                            if (n < 0) {
                                break;
                            }
                            ostream.write(buffer, 0, n);
                        }
                        ostream.flush();
                        ostream.close();
                        ostream = null;
                        istream.close();
                        istream = null;
                        entry = null;
                        jar.close();
                        jar = null;
                        deployDescriptors(configBase(), configBase.list());
                        return;
                    }
                } catch (Exception e) {
                    // Ignore and continue
                    if (ostream != null) {
                        try {
                            ostream.close();
                        } catch (Throwable t) {
                            ;
                        }
                        ostream = null;
                    }
                    if (istream != null) {
                        try {
                            istream.close();
                        } catch (Throwable t) {
                            ;
                        }
                        istream = null;
                    }
                    entry = null;
                    if (jar != null) {
                        try {
                            jar.close();
                        } catch (Throwable t) {
                            ;
                        }
                        jar = null;
                    }
                }
            }

            if (isUnpackWARs()) {

                // Expand and deploy this application as a directory
                log.debug(sm.getString("hostConfig.expand", files[i]));
                URL url = null;
                String path = null;
                try {
                    url = new URL("jar:file:" + dir.getCanonicalPath() + "!/");
                    path = ExpandWar.expand(host, url);
                } catch (IOException e) {
                    // JAR decompression failure
                    log.warn(sm.getString("hostConfig.expand.error", files[i]));
                    continue;
                } catch (Throwable t) {
                    log.error(sm.getString("hostConfig.expand.error", files[i]), t);
                    continue;
                }
                try {
                    if (path != null) {
                        url = new URL("file:" + path);
                        ((Deployer) host).install(contextPath, url);
                    }
                } catch (Throwable t) {
                    log.error(sm.getString("hostConfig.expand.error", files[i]), t);
                }

            } else {

                // Deploy the application in this WAR file
                log.info(sm.getString("hostConfig.deployJar", files[i]));
                try {
                    URL url = new URL("file", null, dir.getCanonicalPath());
                    url = new URL("jar:" + url.toString() + "!/");
                    ((Deployer) host).install(contextPath, url);
                } catch (Throwable t) {
                    log.error(sm.getString("hostConfig.deployJar.error", files[i]), t);
                }

            }

        }

    }

}

From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java

/**
 * //  w  w  w .j  a v  a  2s  .c  o m
 * 
 * @param is
 *           
 * @param f
 *           
 * 
 * @throws IOException
 *           IO
 */
static void writeInputStreamToFile(InputStream is, File f) throws IOException {
    BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(f));
    byte[] buffer = new byte[1024];
    int read = 0;

    while ((read = is.read(buffer)) > 0) {
        bf.write(buffer, 0, read);
    }

    is.close();
    bf.flush();
    bf.close();
}

From source file:es.cnio.bioinfo.bicycle.gatk.MethylationFilePair.java

private void appendFiles(File f1, File f2, File outfile) throws IOException {
    //System.err.println("appending: "+f1+", "+f2+": "+outfile);

    byte[] buffer = new byte[2048];

    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outfile));

    //file 1// w ww. j  a va  2  s.  com
    FileInputStream fis = new FileInputStream(f1);

    BufferedInputStream in = new BufferedInputStream(fis);
    int readed = -1;

    while ((readed = in.read(buffer)) != -1) {
        out.write(buffer, 0, readed);
    }
    in.close();
    fis.close();

    //file 2
    fis = new FileInputStream(f2);
    in = new BufferedInputStream(fis);
    readed = -1;

    while ((readed = in.read(buffer)) != -1) {
        out.write(buffer, 0, readed);
    }
    in.close();
    fis.close();

    if (!f1.delete()) {
        throw new RuntimeException("Could no delete tempary file: " + f1);
    }

    if (!f2.delete()) {
        throw new RuntimeException("Could no delete tempary file: " + f2);
    }

    out.flush();
    out.close();

}

From source file:com.example.util.FileUtils.java

/**
 * Writes the <code>toString()</code> value of each item in a collection to
 * the specified <code>File</code> line by line.
 * The specified character encoding and the line ending will be used.
 *
 * @param file  the file to write to/*from w  w w.j a v a 2 s  .  c  o  m*/
 * @param encoding  the encoding to use, {@code null} means platform default
 * @param lines  the lines to write, {@code null} entries produce blank lines
 * @param lineEnding  the line separator to use, {@code null} is system default
 * @param append if {@code true}, then the lines will be added to the
 * end of the file rather than overwriting
 * @throws IOException in case of an I/O error
 * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
 * @since 2.1
 */
public static void writeLines(File file, String encoding, Collection<?> lines, String lineEnding,
        boolean append) throws IOException {
    FileOutputStream out = null;
    try {
        out = openOutputStream(file, append);
        final BufferedOutputStream buffer = new BufferedOutputStream(out);
        IOUtils.writeLines(lines, lineEnding, buffer, encoding);
        buffer.flush();
        out.close(); // don't swallow close Exception if copy completes normally
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:org.dswarm.graph.resources.GDMResource.java

@POST
@Path("/get")
@Consumes(MediaType.APPLICATION_JSON)// w w w  .  jav  a2s  .c  om
@Produces(MediaType.APPLICATION_JSON)
public Response readGDM(final String jsonObjectString, @Context final GraphDatabaseService database,
        @Context final HttpHeaders requestHeaders) throws DMPGraphException {

    final String headers = readHeaders(requestHeaders);

    GDMResource.LOG.debug("try to read GDM statements from graph db with\n{}", headers);

    final ObjectNode requestJSON = deserializeJSON(jsonObjectString, READ_GDM_MODEL_TYPE);

    final String recordClassUri = requestJSON.get(DMPStatics.RECORD_CLASS_URI_IDENTIFIER).asText();
    final String dataModelUri = requestJSON.get(DMPStatics.DATA_MODEL_URI_IDENTIFIER).asText();
    final Optional<Integer> optionalVersion = getIntValue(DMPStatics.VERSION_IDENTIFIER, requestJSON);
    final Optional<Integer> optionalAtMost = getIntValue(DMPStatics.AT_MOST_IDENTIFIER, requestJSON);

    final TransactionHandler tx = new Neo4jTransactionHandler(database);
    final NamespaceIndex namespaceIndex = new NamespaceIndex(database, tx);
    final String prefixedRecordClassURI = namespaceIndex.createPrefixedURI(recordClassUri);
    final String prefixedDataModelURI = namespaceIndex.createPrefixedURI(dataModelUri);

    GDMResource.LOG.info(
            "try to read GDM statements for data model uri = '{}' ('{}') and record class uri = '{}' ('{}') and version = '{}' from graph db",
            dataModelUri, prefixedDataModelURI, recordClassUri, prefixedRecordClassURI, optionalVersion);

    final GDMModelReader gdmReader = new PropertyGraphGDMModelReader(prefixedRecordClassURI,
            prefixedDataModelURI, optionalVersion, optionalAtMost, database, tx, namespaceIndex);

    final StreamingOutput stream = os -> {

        try {

            final BufferedOutputStream bos = new BufferedOutputStream(os, 1024);
            final Optional<ModelBuilder> optionalModelBuilder = gdmReader.read(bos);

            if (optionalModelBuilder.isPresent()) {

                final ModelBuilder modelBuilder = optionalModelBuilder.get();
                modelBuilder.build();
                bos.flush();
                os.flush();
                bos.close();
                os.close();

                GDMResource.LOG.info(
                        "finished reading '{}' resources with '{}' GDM statements ('{}' via GDM reader) for data model uri = '{}' ('{}') and record class uri = '{}' ('{}') and version = '{}' from graph db",
                        gdmReader.readResources(), gdmReader.countStatements(), gdmReader.countStatements(),
                        dataModelUri, prefixedDataModelURI, recordClassUri, prefixedRecordClassURI,
                        optionalVersion);
            } else {

                bos.close();
                os.close();

                GDMResource.LOG.info(
                        "couldn't find any GDM statements for data model uri = '{}' ('{}') and record class uri = '{}' ('{}') and version = '{}' from graph db",
                        dataModelUri, prefixedDataModelURI, recordClassUri, prefixedRecordClassURI,
                        optionalVersion);
            }
        } catch (final DMPGraphException e) {

            throw new WebApplicationException(e);
        }
    };

    return Response.ok(stream, MediaType.APPLICATION_JSON_TYPE).build();
}

From source file:com.twinsoft.convertigo.eclipse.wizards.new_project.NewProjectWizard.java

private Project createFromBlankProject(IProgressMonitor monitor) throws Exception {
    Project project = null;//from   w w  w  . j  a v a 2  s . co m
    String projectArchivePath = "";
    String newProjectName = projectName;
    String oldProjectName = "";

    switch (templateId) {
    case TEMPLATE_SQL_CONNECTOR:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + SQL_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = SQL_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                SQL_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_SAP_CONNECTOR:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + SAP_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = SAP_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                SAP_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_SEQUENCE_CONNECTOR:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + SEQUENCE_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = SEQUENCE_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                SEQUENCE_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_EAI_HTML_WEB_SITE:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + WEB_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = WEB_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                WEB_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_EAI_HTTP:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + HTTP_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = HTTP_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                HTTP_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_WEB_HTML_BULL_DKU_7107:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + DKU_PUBLISHER_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = DKU_PUBLISHER_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                DKU_PUBLISHER_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_WEB_HTML_IBM_3270:
    case TEMPLATE_WEB_HTML_IBM_5250:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + JAVELIN_PUBLISHER_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = JAVELIN_PUBLISHER_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                JAVELIN_PUBLISHER_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_EAI_BULL_DKU_7107:
    case TEMPLATE_EAI_IBM_3270:
    case TEMPLATE_EAI_IBM_5250:
    case TEMPLATE_EAI_UNIX_VT220:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/"
                + JAVELIN_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = JAVELIN_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                JAVELIN_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_EAI_CICS_COMMEAREA:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + CICS_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = CICS_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                CICS_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_WEB_SERVICE_REST_REFERENCE:
    case TEMPLATE_WEB_SERVICE_SWAGGER_REFERENCE:
    case TEMPLATE_WEB_SERVICE_SOAP_REFERENCE:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + HTTP_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = HTTP_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                HTTP_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_SITE_CLIPPER:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + SITE_CLIPPER_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = SITE_CLIPPER_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                SITE_CLIPPER_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_MOBILE_EMPTY_JQUERYMOBILE:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/"
                + JQUERYMOBILE_MOBILE_EMPTY_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = JQUERYMOBILE_MOBILE_EMPTY_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                JQUERYMOBILE_MOBILE_EMPTY_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    default:
        return null;
    }

    String temporaryDir = new File(Engine.USER_WORKSPACE_PATH + "/temp").getCanonicalPath();
    String tempProjectDir = temporaryDir + "/" + oldProjectName;
    String newProjectDir = Engine.PROJECTS_PATH + "/" + newProjectName;

    try {
        try {
            File f = null;

            monitor.setTaskName("Creating new project");
            monitor.worked(1);
            try {
                // Check if project already exists
                if (Engine.theApp.databaseObjectsManager.existsProject(newProjectName))
                    throw new EngineException("Unable to create new project ! A project with the same name (\""
                            + newProjectName + "\") already exists.");

                // Create temporary directory if needed
                f = new File(temporaryDir);
                if (f.mkdir()) {
                    monitor.setTaskName("Temporary directory created: " + temporaryDir);
                    monitor.worked(1);
                }
            } catch (Exception e) {
                throw new EngineException("Unable to create the temporary directory \"" + temporaryDir + "\".",
                        e);
            }

            // Decompress Convertigo archive to temporary directory
            ZipUtils.expandZip(projectArchivePath, temporaryDir, oldProjectName);

            monitor.setTaskName("Project archive expanded to temporary directory");
            monitor.worked(1);

            // Rename temporary project directory
            f = new File(tempProjectDir);
            if (!f.renameTo(new File(newProjectDir))) {
                throw new ConvertigoException("Unable to rename the directory path \"" + tempProjectDir
                        + "\" to \"" + newProjectDir + "\"."
                        + "\n This directory already exists or is probably locked by another application.");
            }
        } catch (Exception e) {
            throw new EngineException(
                    "Unable to deploy the project from the file \"" + projectArchivePath + "\".", e);
        }

        String xmlFilePath = newProjectDir + "/" + oldProjectName + ".xml";
        String newXmlFilePath = newProjectDir + "/" + newProjectName + ".xml";
        File xmlFile = new File(xmlFilePath);

        // load xml content of file in dom
        Document dom = null;

        // cration du docBuilderFactory
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setIgnoringElementContentWhitespace(true);
        docBuilderFactory.setNamespaceAware(true);

        // cration du docBuilder
        DocumentBuilder docBuilder;
        try {
            docBuilder = docBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new EngineException("Wrong parser configuration.", e);
        }

        // parsing du fichier
        try {
            dom = docBuilder.parse(xmlFile);
        } catch (SAXException e) {
            throw new EngineException("Wrong XML file structure.", e);
        } catch (IOException e) {
            throw new EngineException("Could not read source file.", e);
        }

        monitor.setTaskName("Xml file parsed");
        monitor.worked(1);

        // set values of elements to configure on the new project
        String newEmulatorTechnology = "";
        String emulatorTechnologyName = "";
        String newIbmTerminalType = "";
        switch (templateId) {
        case TEMPLATE_SEQUENCE_CONNECTOR:
        case TEMPLATE_EAI_HTML_WEB_SITE:
        case TEMPLATE_EAI_HTTP:
            break;
        case TEMPLATE_WEB_HTML_BULL_DKU_7107:
        case TEMPLATE_EAI_BULL_DKU_7107:
            newEmulatorTechnology = Session.DKU;
            emulatorTechnologyName = "BullDKU7107"; //$NON-NLS-1$
            break;
        case TEMPLATE_WEB_HTML_IBM_3270:
        case TEMPLATE_EAI_IBM_3270:
            newEmulatorTechnology = Session.SNA;
            newIbmTerminalType = "IBM-3279";
            emulatorTechnologyName = "IBM3270"; //$NON-NLS-1$
            break;
        case TEMPLATE_WEB_HTML_IBM_5250:
        case TEMPLATE_EAI_IBM_5250:
            newEmulatorTechnology = Session.AS400;
            newIbmTerminalType = "IBM-3179";
            emulatorTechnologyName = "IBM5250"; //$NON-NLS-1$
            break;
        case TEMPLATE_EAI_UNIX_VT220:
            newEmulatorTechnology = Session.VT;
            emulatorTechnologyName = "UnixVT220"; //$NON-NLS-1$
            break;
        default:
            break;
        }

        // rename project in .xml file for all projects
        Element projectElem = (Element) dom.getDocumentElement().getElementsByTagName("project").item(0);
        NodeList projectProperties = projectElem.getElementsByTagName("property");

        Element property = (Element) XMLUtils.findNodeByAttributeValue(projectProperties, "name", "name");
        ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
        ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                newProjectName);
        monitor.setTaskName("Project renamed");
        monitor.worked(1);

        // empty project version
        property = (Element) XMLUtils.findNodeByAttributeValue(projectProperties, "name", "version");
        ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
        ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value", "");

        // rename connector in .xml file for all projects
        String oldConnectorName = "unknown";
        String newConnectorName = "NewConnector";
        // interactionHub project connector name is by default set to "void"
        switch (templateId) {
        case TEMPLATE_MOBILE_EMPTY_JQUERYMOBILE:
        case TEMPLATE_SEQUENCE_CONNECTOR:
            newConnectorName = "void";
            break;
        default:
            newConnectorName = (page2 == null) ? "NewConnector" : page2.getConnectorName();
            break;
        }
        Element connectorElem = (Element) dom.getDocumentElement().getElementsByTagName("connector").item(0);
        NodeList connectorProperties = connectorElem.getElementsByTagName("property");

        property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "name");
        oldConnectorName = ((Element) property.getElementsByTagName("java.lang.String").item(0))
                .getAttribute("value");
        ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
        ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                newConnectorName);
        monitor.setTaskName("Connector renamed");
        monitor.worked(1);

        // configure connector properties
        switch (templateId) {
        case TEMPLATE_WEB_HTML_BULL_DKU_7107:
        case TEMPLATE_WEB_HTML_IBM_3270:
        case TEMPLATE_WEB_HTML_IBM_5250:
        case TEMPLATE_EAI_BULL_DKU_7107:
        case TEMPLATE_EAI_IBM_3270:
        case TEMPLATE_EAI_IBM_5250:
        case TEMPLATE_EAI_UNIX_VT220:
            // change emulator technology
            // and change service code
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "serviceCode");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    page7.getServiceCode());
            monitor.setTaskName("Connector service code updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name",
                    "emulatorTechnology");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    newEmulatorTechnology);
            monitor.setTaskName("Connector emulator technology updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name",
                    "ibmTerminalType");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    newIbmTerminalType);
            monitor.setTaskName("Terminal type updated");
            monitor.worked(1);

            // rename emulatorTechnology criteria
            Element criteriaElem = (Element) dom.getDocumentElement().getElementsByTagName("criteria").item(0);
            NodeList criteriaProperties = criteriaElem.getElementsByTagName("property");

            property = (Element) XMLUtils.findNodeByAttributeValue(criteriaProperties, "name", "name");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    emulatorTechnologyName);
            monitor.setTaskName("Emulator technology criteria renamed");
            monitor.worked(1);
            break;
        case TEMPLATE_WEB_SERVICE_REST_REFERENCE:
        case TEMPLATE_EAI_HTML_WEB_SITE:
        case TEMPLATE_EAI_HTTP:
            // change connector server and port,
            // change https mode
            // and change proxy server and proxy port
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "server");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    page6.getHttpServer());
            monitor.setTaskName("Connector server updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "port");
            ((Element) property.getElementsByTagName("java.lang.Integer").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.Integer").item(0)).setAttribute("value",
                    page6.getHttpPort());
            monitor.setTaskName("Connector port updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "https");
            ((Element) property.getElementsByTagName("java.lang.Boolean").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.Boolean").item(0)).setAttribute("value",
                    Boolean.toString(page6.isBSSL()));
            monitor.setTaskName("Connector https mode updated");
            monitor.worked(1);
            break;

        case TEMPLATE_EAI_CICS_COMMEAREA:
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name",
                    "mainframeName");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    page5.getCtgName());
            monitor.setTaskName("Connector mainframe name updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "server");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    page5.getCtgServer());
            monitor.setTaskName("Connector server updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "port");
            ((Element) property.getElementsByTagName("java.lang.Integer").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.Integer").item(0)).setAttribute("value",
                    page5.getCtgPort());
            monitor.setTaskName("Connector port updated");
            monitor.worked(1);
            break;

        case TEMPLATE_SQL_CONNECTOR:
            // change emulator technology
            // and change service code
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "jdbcURL");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSQLConnectorPage.getJdbcURL());
            monitor.setTaskName("JDBC URL updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name",
                    "jdbcDriverClassName");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSQLConnectorPage.getJdbcDriver());
            monitor.setTaskName("JDBC driver updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "jdbcUserName");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSQLConnectorPage.getUsername());
            monitor.setTaskName("Username updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name",
                    "jdbcUserPassword");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSQLConnectorPage.getPassword());
            monitor.setTaskName("Password updated");
            monitor.worked(1);

            break;

        case TEMPLATE_SAP_CONNECTOR:
            // change emulator technology
            // and change service code

            // Application Server Host
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "ashost");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSAPConnectorPage.getAsHost());
            monitor.setTaskName("Application Server Host updated");
            monitor.worked(1);

            // System Number
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "systemNumber");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSAPConnectorPage.getSystemNumber());
            monitor.setTaskName("System number updated");
            monitor.worked(1);

            // Client
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "client");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSAPConnectorPage.getClient());
            monitor.setTaskName("Client updated");
            monitor.worked(1);

            // User
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "user");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSAPConnectorPage.getUser());
            monitor.setTaskName("User updated");
            monitor.worked(1);

            // Password
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "password");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSAPConnectorPage.getPassword());
            monitor.setTaskName("Password updated");
            monitor.worked(1);

            // Language
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "language");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSAPConnectorPage.getLanguage());
            monitor.setTaskName("Language updated");
            monitor.worked(1);

            break;

        case TEMPLATE_SITE_CLIPPER:
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name",
                    "trustAllServerCertificates");
            ((Element) property.getElementsByTagName("java.lang.Boolean").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.Boolean").item(0)).setAttribute("value",
                    Boolean.toString(page11.isTrustAllServerCertificates()));
            monitor.setTaskName("Connector certificates policy updated");
            monitor.worked(1);
            break;

        default:
            break;
        }

        // Configure connector's default transaction properties
        Element transactionElem = (Element) dom.getDocumentElement().getElementsByTagName("transaction")
                .item(0);
        NodeList transactionProperties = transactionElem.getElementsByTagName("property");

        switch (templateId) {
        case TEMPLATE_SITE_CLIPPER:
            property = (Element) XMLUtils.findNodeByAttributeValue(transactionProperties, "name", "targetURL");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    page11.getTargetURL());
            monitor.setTaskName("Host url updated");
            monitor.worked(1);
            break;
        case TEMPLATE_SQL_CONNECTOR:
            property = (Element) XMLUtils.findNodeByAttributeValue(transactionProperties, "name", "sqlQuery");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            monitor.setTaskName("SQL queries updated");
            monitor.worked(1);
            break;
        default:
            break;
        }

        // write the new .xml file
        // prepare the string source to write
        String doc = XMLUtils.prettyPrintDOM(dom);
        // create the output file
        File newXmlFile = new File(newXmlFilePath);
        if (!newXmlFile.createNewFile()) {
            throw new ConvertigoException("Unable to create the .xml file \"" + newProjectName + ".xml\".");
        }
        // write the file to the disk
        byte data[] = doc.getBytes();
        FileOutputStream fos = new FileOutputStream(newXmlFilePath);
        BufferedOutputStream dest = new BufferedOutputStream(fos, data.length);
        try {
            dest.write(data, 0, data.length);
        } finally {
            dest.flush();
            dest.close();
        }

        monitor.setTaskName("New xml file created and saved");
        monitor.worked(1);

        // delete the old .xml file
        if (!xmlFile.delete()) {
            throw new ConvertigoException("Unable to delete the .xml file \"" + oldProjectName + ".xml\".");
        }

        monitor.setTaskName("Old xml file deleted");
        monitor.worked(1);

        try {
            String xsdInternalPath = newProjectDir + "/" + Project.XSD_FOLDER_NAME + "/"
                    + Project.XSD_INTERNAL_FOLDER_NAME;
            File xsdInternalDir = new File(xsdInternalPath).getCanonicalFile();

            boolean needConnectorRename = !oldConnectorName.equals(newConnectorName);
            if (needConnectorRename) {
                File srcDir = new File(xsdInternalDir, oldConnectorName);
                File destDir = new File(xsdInternalDir, newConnectorName);

                if (oldConnectorName.equalsIgnoreCase(newConnectorName)) {
                    File destDirTmp = new File(xsdInternalDir, "tmp" + oldConnectorName).getCanonicalFile();
                    FileUtils.moveDirectory(srcDir, destDirTmp);
                    srcDir = destDirTmp;
                }
                FileUtils.moveDirectory(srcDir, destDir);
            }

            for (File connectorDir : xsdInternalDir.listFiles()) {
                if (connectorDir.isDirectory()) {
                    String connectorName = connectorDir.getName();
                    for (File transactionXsdFile : connectorDir.listFiles()) {
                        String xsdFilePath = transactionXsdFile.getCanonicalPath();
                        ProjectUtils.xsdRenameProject(xsdFilePath, oldProjectName, newProjectName);
                        if (needConnectorRename && connectorName.equals(newConnectorName)) {
                            ProjectUtils.xsdRenameConnector(xsdFilePath, oldConnectorName, newConnectorName);
                        }
                    }
                }
            }

            monitor.setTaskName("Schemas updated");
            monitor.worked(1);

        } catch (ConvertigoException e) {
            Engine.logDatabaseObjectManager.error("An error occured while updating transaction schemas", e);
        }

        String projectPath = newProjectDir + "/" + newProjectName;

        // Import the project from the new .xml file
        project = Engine.theApp.databaseObjectsManager.importProject(projectPath + ".xml");

        // In the case we want to predefine with the new project wizard a SQL query
        switch (templateId) {
        case TEMPLATE_SQL_CONNECTOR:
            try {
                SqlConnector connector = (SqlConnector) project.getDefaultConnector();
                SqlTransaction transaction = connector.getDefaultTransaction();

                String sqlQuery = transaction.getSqlQuery();
                transaction.setSqlQuery(sqlQuery);
                CarUtils.exportProject(project, projectPath + ".xml");
            } catch (Exception e) {
                Engine.logDatabaseObjectManager
                        .error("An error occured while initialize SQL project \"" + projectName + "\"", e);
            }
            break;
        }
        monitor.setTaskName("Project loaded");
        monitor.worked(1);

        monitor.setTaskName("Resources created");
        monitor.worked(1);
    } catch (Exception e) {
        // Delete everything
        try {
            Engine.logBeans.error(
                    "An error occured while creating project, everything will be deleted. Please see Studio logs for more informations.",
                    null);
            // TODO : see if we can delete oldProjectName : a real project
            // could exist with this oldProjectName ?
            // Engine.theApp.databaseObjectsManager.deleteProject(oldProjectName,
            // false, false);
            Engine.theApp.databaseObjectsManager.deleteProject(newProjectName, false, false);
            projectName = null; // avoid load of project in view
            project = null;
        } catch (Exception ex) {
        }

        throw new Exception("Unable to create project from template", e);
    }

    return project;
}

From source file:it.evilsocket.dsploit.core.UpdateService.java

/**
 * extract an archive into a directory//from  www  .  j ava 2 s. co  m
 *
 * @throws IOException if some I/O error occurs
 * @throws java.util.concurrent.CancellationException if task is cancelled by user
 * @throws java.lang.InterruptedException when the the running thread get cancelled.
 */
private void extract() throws CancellationException, RuntimeException, IOException, InterruptedException {
    ArchiveInputStream is = null;
    ArchiveEntry entry;
    CountingInputStream counter;
    File f, inFile;
    File[] list;
    String name;
    FileOutputStream fos = null;
    byte data[] = new byte[2048];
    int mode;
    int count;
    long total;
    short percentage, old_percentage;

    if (mCurrentTask.path == null || mCurrentTask.outputDir == null)
        return;

    mBuilder.setContentTitle(getString(R.string.extracting)).setContentText("").setContentInfo("")
            .setSmallIcon(android.R.drawable.ic_popup_sync).setProgress(100, 0, false);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

    Logger.info(String.format("extracting '%s' to '%s'", mCurrentTask.path, mCurrentTask.outputDir));

    try {
        inFile = new File(mCurrentTask.path);
        total = inFile.length();
        counter = new CountingInputStream(new FileInputStream(inFile));
        is = openArchiveStream(counter);
        old_percentage = -1;

        f = new File(mCurrentTask.outputDir);
        if (f.exists() && f.isDirectory() && (list = f.listFiles()) != null && list.length > 2)
            wipe();

        if (is instanceof TarArchiveInputStream && mCurrentTask.modeMap == null)
            mCurrentTask.modeMap = new HashMap<Integer, String>();

        while (mRunning && (entry = is.getNextEntry()) != null) {
            name = entry.getName().replaceFirst("^\\./?", "");

            if (mCurrentTask.dirToExtract != null) {
                if (!name.startsWith(mCurrentTask.dirToExtract))
                    continue;
                else
                    name = name.substring(mCurrentTask.dirToExtract.length());
            }

            f = new File(mCurrentTask.outputDir, name);

            if (entry.isDirectory()) {
                if (!f.exists()) {
                    if (!f.mkdirs()) {
                        throw new IOException(
                                String.format("Couldn't create directory '%s'.", f.getAbsolutePath()));
                    }
                }
            } else {
                BufferedOutputStream bof = new BufferedOutputStream(new FileOutputStream(f));

                while (mRunning && (count = is.read(data)) != -1) {
                    bof.write(data, 0, count);
                    percentage = (short) (((double) counter.getBytesRead() / total) * 100);
                    if (percentage != old_percentage) {
                        mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%");
                        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                        old_percentage = percentage;
                    }
                }
                bof.flush();
                bof.close();
            }
            // Zip does not store file permissions.
            if (entry instanceof TarArchiveEntry) {
                mode = ((TarArchiveEntry) entry).getMode();

                if (!mCurrentTask.modeMap.containsKey(mode))
                    mCurrentTask.modeMap.put(mode, entry.getName() + " ");
                else
                    mCurrentTask.modeMap.put(mode,
                            mCurrentTask.modeMap.get(mode).concat(entry.getName() + " "));
            }
        }

        if (!mRunning)
            throw new CancellationException("extraction cancelled.");

        Logger.info("extraction completed");

        f = new File(mCurrentTask.outputDir, ".nomedia");
        if (f.createNewFile())
            Logger.info(".nomedia created");

        if (mCurrentTask.versionString != null && !mCurrentTask.versionString.isEmpty()) {
            f = new File(mCurrentTask.outputDir, "VERSION");
            fos = new FileOutputStream(f);
            fos.write(mCurrentTask.versionString.getBytes());
        } else
            Logger.warning("version string not found");

        mBuilder.setContentInfo("").setProgress(100, 100, true);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    } finally {
        if (is != null)
            is.close();
        if (fos != null)
            fos.close();
    }
}

From source file:com.fanfou.app.opensource.service.DownloadService.java

private void download(final AppVersionInfo info) {
    if ((info == null) || TextUtils.isEmpty(info.downloadUrl)) {
        return;//  w  ww . j av  a 2  s.  c o  m
    }
    showProgress();
    final String url = info.downloadUrl;
    final int versionCode = info.versionCode;
    if (AppContext.DEBUG) {
        Log.v(DownloadService.TAG, "download apk file url: " + url + " versionCode:" + versionCode);
    }
    InputStream is = null;
    BufferedOutputStream bos = null;
    final SimpleClient client = new SimpleClient(AppContext.getAppContext());
    boolean needDownload = true;
    final File file = new File(IOHelper.getDownloadDir(this), "fanfouapp_" + versionCode + ".apk");
    try {
        final HttpResponse response = client.get(url);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            final HttpEntity entity = response.getEntity();
            final long totalSize = entity.getContentLength();
            long download = 0;

            if (file.exists() && file.isFile() && (file.length() == totalSize)) {
                needDownload = false;
                download = totalSize;
                if (AppContext.DEBUG) {
                    Log.v(DownloadService.TAG,
                            "download apk file is already exists: " + file.getAbsolutePath());
                }
            }

            if (needDownload) {
                is = entity.getContent();
                bos = new BufferedOutputStream(new FileOutputStream(file));
                final byte[] buffer = new byte[8196];
                int read = -1;
                while ((read = is.read(buffer)) != -1) {
                    bos.write(buffer, 0, read);
                    download += read;
                    final int progress = (int) ((100.0 * download) / totalSize);
                    sendProgressMessage(progress);
                    if (AppContext.DEBUG) {
                        log("progress=" + progress);
                    }
                }
                bos.flush();
            }
            if (download >= totalSize) {
                sendSuccessMessage(file);
            }
        }
    } catch (final IOException e) {
        if (AppContext.DEBUG) {
            Log.e(DownloadService.TAG, "download error: " + e.getMessage());
            e.printStackTrace();
        }

    } finally {
        this.nm.cancel(DownloadService.NOTIFICATION_PROGRESS_ID);
        IOHelper.forceClose(is);
        IOHelper.forceClose(bos);
    }
}

From source file:com.liuguangqiang.download.core.DownloadTask.java

private boolean download() {
    if (mListener != null)
        mListener.sendStartMessage();//from  w  w w  .  j  a v a 2  s . com

    httpGet = new HttpGet(mParams.getUrl());

    long totalSize;
    int progress = 0;

    InputStream io = null;
    BufferedInputStream bufferIo = null;
    OutputStream out = null;
    BufferedOutputStream bufferOut = null;

    try {
        HttpResponse httpResponse = mHttpClient.execute(httpGet);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            totalSize = httpResponse.getEntity().getContentLength();
            File file = new File(mParams.getSavePath());
            io = httpResponse.getEntity().getContent();
            bufferIo = new BufferedInputStream(io);
            out = new FileOutputStream(file);
            bufferOut = new BufferedOutputStream(out);
            byte[] buf = new byte[1];
            int len;
            int percent;
            int lastPercent = -1;
            while ((len = bufferIo.read(buf)) > 0 && !isCanceled()) {
                bufferOut.write(buf, 0, len);
                progress++;
                percent = (int) (progress * 100 / totalSize);
                if (percent > lastPercent) {
                    lastPercent = percent;
                    if (mListener != null)
                        mListener.sendUpdateProgressMessage(percent);
                }
                if (percent == 100 && mListener != null) {
                    mListener.sendSuccessMessage();
                }
            }
            return true;
        } else {
            Log.i("statusCode", "failure code :" + statusCode);
            if (mListener != null)
                mListener.sendFailureMessage("status code:" + statusCode);
        }
        return false;
    } catch (Exception e) {
        if (mListener != null) {
            if (!isCanceled) {
                mListener.sendFailureMessage(e.toString());
            }
        }
        return false;
    } finally {
        try {
            if (bufferOut != null) {
                bufferOut.flush();
                bufferOut.close();
            }
            if (out != null)
                out.close();
            if (io != null)
                io.close();
            if (bufferIo != null)
                bufferIo.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}