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:com.globalsight.everest.webapp.pagehandler.administration.createJobs.CreateJobsMainHandler.java

private List<String> uploadFile(HttpServletRequest p_request, File parentFile)
        throws GlossaryException, IOException {
    byte[] inBuf = new byte[MAX_LINE_LENGTH];
    int bytesRead;
    ServletInputStream in;/*w  ww  .  ja va2  s. c  o  m*/
    String contentType;
    String boundary;
    String filePath = "";
    String path = parentFile.getPath() + File.separator;
    List<String> filePaths = new ArrayList<String>();
    File file = new File(path);
    Set<String> uploadedFileNames = new HashSet<String>();
    for (File f : file.listFiles()) {
        uploadedFileNames.add(f.getName());
    }

    // Let's make sure that we have the right type of content
    //
    contentType = p_request.getContentType();
    if (contentType == null || !contentType.toLowerCase().startsWith("multipart/form-data")) {
        String[] arg = { "form did not use ENCTYPE=multipart/form-data but `" + contentType + "'" };

        throw new GlossaryException(GlossaryException.MSG_FAILED_TO_UPLOAD_FILE, arg, null);
    }

    // Extract the boundary string in this request. The
    // boundary string is part of the content type string
    //
    int bi = contentType.indexOf("boundary=");
    if (bi == -1) {
        String[] arg = { "no boundary string found in request" };

        throw new GlossaryException(GlossaryException.MSG_FAILED_TO_UPLOAD_FILE, arg, null);
    } else {
        // 9 := len("boundary=")
        boundary = contentType.substring(bi + 9);

        // The real boundary has additional two dashes in
        // front
        //
        boundary = "--" + boundary;
    }

    in = p_request.getInputStream();
    bytesRead = in.readLine(inBuf, 0, inBuf.length);

    if (bytesRead < 3) {
        String[] arg = { "incomplete request (not enough data)" };

        // Not enough content was send as part of the post
        throw new GlossaryException(GlossaryException.MSG_FAILED_TO_UPLOAD_FILE, arg, null);
    }

    while (bytesRead != -1) {
        String lineRead = new String(inBuf, 0, bytesRead, "utf-8");
        if (lineRead.startsWith("Content-Disposition: form-data; name=\"")) {
            if (lineRead.indexOf("filename=\"") != -1) {
                // Get file name
                String fileName = getFilename(lineRead.substring(0, lineRead.length() - 2));

                // Get content type line
                bytesRead = in.readLine(inBuf, 0, inBuf.length);
                lineRead = new String(inBuf, 0, bytesRead - 2, "utf-8");

                // Read and ignore the blank line
                bytesRead = in.readLine(inBuf, 0, inBuf.length);

                // Create a temporary file to store the
                // contents in it for now. We might not have
                // additional information, such as TUV id for
                // building the complete file path. We will
                // save the contents in this file for now and
                // finally rename it to correct file name.
                //

                // if a file with same name has been uploaded, ignore this
                if (uploadedFileNames.contains(fileName)) {
                    continue;
                }

                filePath = path + fileName;
                filePaths.add(filePath);
                File m_tempFile = new File(filePath);
                FileOutputStream fos = new FileOutputStream(m_tempFile);
                BufferedOutputStream bos = new BufferedOutputStream(fos, MAX_LINE_LENGTH * 4);

                // Read through the file contents and write
                // it out to a local temp file.
                boolean writeRN = false;
                while ((bytesRead = in.readLine(inBuf, 0, inBuf.length)) != -1) {
                    // Let's first check if we are already on
                    // boundary line
                    if (bytesRead > 2 && inBuf[0] == '-' && inBuf[1] == '-') {
                        lineRead = new String(inBuf, 0, bytesRead, "utf-8");
                        if (lineRead.startsWith(boundary)) {
                            break;
                        }
                    }

                    // Write out carriage-return, new-line
                    // pair which might have been left over
                    // from last write.
                    //
                    if (writeRN) {
                        bos.write(new byte[] { (byte) '\r', (byte) '\n' });
                        writeRN = false;
                    }

                    // The ServletInputStream.readline() adds
                    // "\r\n" bytes for the last line of the
                    // file contents. If we find these pair
                    // as the last bytes we need to delay
                    // writing it until the next go, since it
                    // could very well be the last line of
                    // file content.
                    //
                    if (bytesRead > 2 && inBuf[bytesRead - 2] == '\r' && inBuf[bytesRead - 1] == '\n') {
                        bos.write(inBuf, 0, bytesRead - 2);
                        writeRN = true;
                    } else {
                        bos.write(inBuf, 0, bytesRead);
                    }
                }

                bos.flush();
                bos.close();
                fos.close();
            } else {
                // This is the field part

                // First get the field name

                //               int start = lineRead.indexOf("name=\"");
                //               int end = lineRead.indexOf("\"", start + 7);
                //               String fieldName = lineRead.substring(start + 6, end);

                // Read and ignore the blank line
                bytesRead = in.readLine(inBuf, 0, inBuf.length);

                // String Buffer to keep the field value
                //
                StringBuffer fieldValue = new StringBuffer();

                boolean writeRN = false;
                while ((bytesRead = in.readLine(inBuf, 0, inBuf.length)) != -1) {
                    lineRead = new String(inBuf, 0, bytesRead, "utf-8");

                    // Let's first check if we are already on
                    // boundary line
                    //
                    if (bytesRead > 2 && inBuf[0] == '-' && inBuf[1] == '-') {
                        if (lineRead.startsWith(boundary)) {
                            break;
                        }
                    }

                    // Write out carriage-return, new-line
                    // pair which might have been left over
                    // from last write.
                    //
                    if (writeRN) {
                        fieldValue.append("\r\n");
                        writeRN = false;
                    }

                    // The ServletInputStream.readline() adds
                    // "\r\n" bytes for the last line of the
                    // field value. If we find these pair as
                    // the last bytes we need to delay
                    // writing it until the next go, since it
                    // could very well be the last line of
                    // field value.
                    //
                    if (bytesRead > 2 && inBuf[bytesRead - 2] == '\r' && inBuf[bytesRead - 1] == '\n') {
                        fieldValue.append(lineRead.substring(0, lineRead.length() - 2));
                        writeRN = true;
                    } else {
                        fieldValue.append(lineRead);
                    }
                }
            }
        }

        bytesRead = in.readLine(inBuf, 0, inBuf.length);
    }
    return filePaths;
}

From source file:com.panet.imeta.repository.Repository.java

/**
 * GZips and then base64 encodes an array of bytes to a String
 * /*from w w  w. ja v a2s.c  om*/
 * @param val
 *            the array of bytes to convert to a string
 * @return the base64 encoded string
 * @throws IOException
 *             in the case there is a Base64 or GZip encoding problem
 */
public static final String byteArrayToString(byte[] val) throws IOException {

    String string;
    if (val == null) {
        string = null;
    } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gzos = new GZIPOutputStream(baos);
        BufferedOutputStream bos = new BufferedOutputStream(gzos);
        bos.write(val);
        bos.flush();
        bos.close();

        string = new String(Base64.encodeBase64(baos.toByteArray()));
    }

    return string;
}

From source file:io.pyd.synchro.SyncJob.java

/**
 * Rewrites remote file content to local file Many things can go wrong so
 * there are different exception types thrown When succeded -
 * <code>targetFile</code> contain <code>uploadFile</code> content
 * // ww w  .  j a  va 2s  . c o  m
 * @param uri
 * @param targetFile
 * @param uploadFile
 * @throws SynchroOperationException
 * @throws SynchroFileOperationException
 * @throws InterruptedException
 */
protected void uriContentToFile(URI uri, File targetFile, File uploadFile)
        throws SynchroOperationException, SynchroFileOperationException, InterruptedException {

    RestRequest rest = this.getRequest();
    int postedProgress = 0;
    int buffersize = 16384;
    int count = 0;
    HttpEntity entity;
    try {
        entity = rest.getNotConsumedResponseEntity(uri, null, uploadFile, true);
    } catch (Exception e) {
        throw new SynchroOperationException("Error during response entity: " + e.getMessage(), e);
    }
    long fullLength = entity.getContentLength();
    if (fullLength <= 0) {
        fullLength = 1;
    }

    Logger.getRootLogger().info("Downloading " + fullLength + " bytes");

    InputStream input = null;
    try {
        input = entity.getContent();
    } catch (IllegalStateException e) {
        throw new SynchroOperationException("Error during getting entity content: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new SynchroOperationException("Error during getting entity content: " + e.getMessage(), e);
    }
    BufferedInputStream in = new BufferedInputStream(input, buffersize);

    FileOutputStream output;
    try {
        String dir = targetFile.getPath();
        if (dir != null) {
            dir = dir.substring(0, dir.lastIndexOf(File.separator));
            File dirExist = new File(dir);
            if (!dirExist.exists()) {
                Logger.getRootLogger().info("Need to create directory: " + dir);
                dirExist.mkdirs();
            }
        }

        output = new FileOutputStream(targetFile.getPath());
    } catch (FileNotFoundException e) {
        throw new SynchroFileOperationException("Error during file accessing: " + e.getMessage(), e);
    }
    BufferedOutputStream out = new BufferedOutputStream(output);

    byte data[] = new byte[buffersize];
    int total = 0;

    long startTime = System.nanoTime();
    long lastTime = startTime;
    int lastTimeTotal = 0;

    long secondLength = 1000000000;
    long interval = (long) 2 * secondLength;

    try {
        while ((count = in.read(data)) != -1) {
            long duration = System.nanoTime() - lastTime;

            int tmpTotal = total + count;
            // publishing the progress....
            int tmpProgress = (int) (tmpTotal * 100 / fullLength);
            if (tmpProgress - postedProgress > 0 || duration > secondLength) {
                if (duration > interval) {
                    lastTime = System.nanoTime();
                    long lastTimeBytes = (long) ((tmpTotal - lastTimeTotal) * secondLength / 1024 / 1000);
                    long speed = (lastTimeBytes / (duration));
                    double bytesleft = (double) (((double) fullLength - (double) tmpTotal) / 1024);
                    @SuppressWarnings("unused")
                    double ETC = bytesleft / (speed * 10);
                }
                if (tmpProgress != postedProgress) {
                    logChange(getMessage("job_log_downloading"),
                            targetFile.getName() + " - " + tmpProgress + "%");
                }
                postedProgress = tmpProgress;
            }
            out.write(data, 0, count);
            total = tmpTotal;
            if (this.interruptRequired) {
                break;
            }
        }
        out.flush();
        if (out != null) {
            out.close();
        }
        if (in != null) {
            in.close();
        }
    } catch (IOException e) {
        throw new SynchroFileOperationException("Error during file content rewriting: " + e.getMessage(), e);
    }
    if (this.interruptRequired) {
        rest.release();
        throw new InterruptedException();
    }
    rest.release();
}

From source file:org.entrystore.repository.impl.ContextManagerImpl.java

/**
 * @see org.entrystore.repository.ContextManager#exportContext(org.entrystore.repository.Entry, java.io.File, java.util.Set, boolean)
 *///  w w w.ja  v  a  2s.  co  m
public void exportContext(Entry contextEntry, File destFile, Set<URI> users, boolean metadataOnly,
        Class<? extends RDFWriter> writer) throws RepositoryException {
    String contextResourceURI = contextEntry.getResourceURI().toString();
    if (!contextResourceURI.endsWith("/")) {
        contextResourceURI += "/";
    }
    String contextEntryURI = contextEntry.getEntryURI().toString();
    String contextMetadataURI = contextEntry.getLocalMetadataURI().toString();
    String contextRelationURI = contextEntry.getRelationURI().toString();

    synchronized (this.entry.repository) {
        RepositoryConnection rc = null;
        BufferedOutputStream out = null;

        try {
            try {
                out = new BufferedOutputStream(new FileOutputStream(destFile));
            } catch (FileNotFoundException e) {
                log.error(e.getMessage());
                throw new RepositoryException(e);
            }

            rc = entry.getRepository().getConnection();

            RepositoryResult<org.openrdf.model.Resource> availableNGs = rc.getContextIDs();
            List<org.openrdf.model.Resource> filteredNGs = new ArrayList<org.openrdf.model.Resource>();
            while (availableNGs.hasNext()) {
                org.openrdf.model.Resource ng = availableNGs.next();
                String ngURI = ng.stringValue();
                if (metadataOnly) {
                    if (ngURI.startsWith(contextResourceURI)
                            && (ngURI.contains("/metadata/") || ngURI.contains("/cached-external-metadata/"))) {
                        filteredNGs.add(ng);
                    }
                } else {
                    if (ngURI.startsWith(contextResourceURI) || ngURI.equals(contextEntryURI)
                            || ngURI.equals(contextMetadataURI) || ngURI.equals(contextRelationURI)) {
                        filteredNGs.add(ng);
                    }
                }
            }

            RDFHandler rdfWriter = null;
            try {
                Constructor<? extends RDFWriter> constructor = writer.getConstructor(OutputStream.class);
                rdfWriter = (RDFWriter) constructor.newInstance(out);
            } catch (Exception e) {
                log.error(e.getMessage());
            }

            if (rdfWriter == null) {
                log.error("Unable to create an RDF writer, format not supported");
                return;
            }

            Map<String, String> namespaces = NS.getMap();
            for (String nsName : namespaces.keySet()) {
                rdfWriter.handleNamespace(nsName, namespaces.get(nsName));
            }

            rdfWriter.startRDF();
            RepositoryResult<Statement> rr = rc.getStatements(null, null, null, false,
                    filteredNGs.toArray(new org.openrdf.model.Resource[filteredNGs.size()]));
            while (rr.hasNext()) {
                Statement s = rr.next();
                org.openrdf.model.URI p = s.getPredicate();
                rdfWriter.handleStatement(s);
                if (!metadataOnly) {
                    if (p.equals(RepositoryProperties.Creator) || p.equals(RepositoryProperties.Contributor)
                            || p.equals(RepositoryProperties.Read) || p.equals(RepositoryProperties.Write)
                            || p.equals(RepositoryProperties.DeletedBy)) {
                        users.add(URI.create(s.getObject().stringValue()));
                    }
                }
            }
            rdfWriter.endRDF();
        } catch (RepositoryException e) {
            log.error("Error when exporting context", e);
            throw e;
        } catch (RDFHandlerException e) {
            log.error(e.getMessage(), e);
            throw new RepositoryException(e);
        } finally {
            rc.close();
            try {
                out.flush();
                out.close();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String Unzip(String zipFileName, String dstDirectory) {
    String sRet = "";
    String fixedZipFileName = fixFileName(zipFileName);
    String fixedDstDirectory = fixFileName(dstDirectory);
    String dstFileName = "";
    int nNumExtracted = 0;
    boolean bRet = false;

    try {/*from   www . j  av  a  2  s .c  o  m*/
        final int BUFFER = 2048;
        BufferedOutputStream dest = null;
        ZipFile zipFile = new ZipFile(fixedZipFileName);
        int nNumEntries = zipFile.size();
        zipFile.close();

        FileInputStream fis = new FileInputStream(fixedZipFileName);
        CheckedInputStream checksum = new CheckedInputStream(fis, new Adler32());
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(checksum));
        ZipEntry entry;

        byte[] data = new byte[BUFFER];

        while ((entry = zis.getNextEntry()) != null) {
            System.out.println("Extracting: " + entry);
            int count;
            if (fixedDstDirectory.length() > 0)
                dstFileName = fixedDstDirectory + entry.getName();
            else
                dstFileName = entry.getName();

            String tmpDir = dstFileName.substring(0, dstFileName.lastIndexOf('/'));
            File tmpFile = new File(tmpDir);
            if (!tmpFile.exists()) {
                bRet = tmpFile.mkdirs();
            } else
                bRet = true;

            if (bRet) {
                // if we aren't just creating a directory
                if (dstFileName.lastIndexOf('/') != (dstFileName.length() - 1)) {
                    // write out the file
                    FileOutputStream fos = new FileOutputStream(dstFileName);
                    dest = new BufferedOutputStream(fos, BUFFER);
                    while ((count = zis.read(data, 0, BUFFER)) != -1) {
                        dest.write(data, 0, count);
                    }
                    dest.flush();
                    dest.close();
                    dest = null;
                    fos.close();
                    fos = null;
                }
                nNumExtracted++;
            } else
                sRet += " - failed" + lineSep;
        }

        data = null;
        zis.close();
        System.out.println("Checksum:          " + checksum.getChecksum().getValue());
        sRet += "Checksum:          " + checksum.getChecksum().getValue();
        sRet += lineSep + nNumExtracted + " of " + nNumEntries + " successfully extracted";
    } catch (Exception e) {
        e.printStackTrace();
    }

    return (sRet);
}

From source file:org.adaway.service.ApplyService.java

/**
 * Apply hosts file/*from w  w  w  . j  av a 2  s .  c  o  m*/
 *
 * @return return code
 */
int apply() {
    showApplyNotification(mService, mService.getString(R.string.apply_dialog),
            mService.getString(R.string.apply_dialog), mService.getString(R.string.apply_dialog_hostnames));

    int returnCode = StatusCodes.SUCCESS; // default return code
    BufferedOutputStream bos = null;

    try {
        /* PARSE: parse hosts files to sets of hostnames and comments */

        FileInputStream fis = mService.openFileInput(Constants.DOWNLOADED_HOSTS_FILENAME);

        BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

        // Use whitelist and/or redirection rules from hosts sources only if enabled in preferences
        HostsParser parser = new HostsParser(reader, PreferenceHelper.getWhitelistRules(mService),
                PreferenceHelper.getRedirectionRules(mService));

        fis.close();

        updateApplyNotification(mService, mService.getString(R.string.apply_dialog),
                mService.getString(R.string.apply_dialog_lists));

        /* READ DATABSE CONTENT */

        // add whitelist from db
        parser.addWhitelist(ProviderHelper.getEnabledWhitelistHashSet(mService));
        // add blacklist from db
        parser.addBlacklist(ProviderHelper.getEnabledBlacklistHashSet(mService));
        // add redirection list from db
        parser.addRedirectionList(ProviderHelper.getEnabledRedirectionListHashMap(mService));

        // get hosts sources list from db
        ArrayList<String> enabledHostsSources = ProviderHelper.getEnabledHostsSourcesArrayList(mService);
        Log.d(Constants.TAG, "Enabled hosts sources list: " + enabledHostsSources.toString());

        // compile lists (removing whitelist entries, etc.)
        parser.compileList();

        /* BUILD: build one hosts file out of sets and preferences */
        updateApplyNotification(mService, mService.getString(R.string.apply_dialog),
                mService.getString(R.string.apply_dialog_hosts));

        FileOutputStream fos = mService.openFileOutput(Constants.HOSTS_FILENAME, Context.MODE_PRIVATE);

        bos = new BufferedOutputStream(fos);

        // build current timestamp for header
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();

        // add adaway header
        String header = Constants.HEADER1 + Constants.LINE_SEPERATOR + "# " + formatter.format(now)
                + Constants.LINE_SEPERATOR + Constants.HEADER2 + Constants.LINE_SEPERATOR
                + Constants.HEADER_SOURCES;
        bos.write(header.getBytes());

        // write sources into header
        String source = null;
        for (String host : enabledHostsSources) {
            source = Constants.LINE_SEPERATOR + "# " + host;
            bos.write(source.getBytes());
        }

        bos.write(Constants.LINE_SEPERATOR.getBytes());

        String redirectionIP = PreferenceHelper.getRedirectionIP(mService);

        // add "127.0.0.1 localhost" entry
        String localhost = Constants.LINE_SEPERATOR + Constants.LOCALHOST_IPv4 + " "
                + Constants.LOCALHOST_HOSTNAME + Constants.LINE_SEPERATOR + Constants.LOCALHOST_IPv6 + " "
                + Constants.LOCALHOST_HOSTNAME;
        bos.write(localhost.getBytes());

        bos.write(Constants.LINE_SEPERATOR.getBytes());

        // write hostnames
        String line;
        String linev6;
        if (PreferenceHelper.getEnableIpv6(mService)) {
            for (String hostname : parser.getBlacklist()) {
                line = Constants.LINE_SEPERATOR + redirectionIP + " " + hostname;
                linev6 = Constants.LINE_SEPERATOR + "::1" + " " + hostname;
                bos.write(line.getBytes());
                bos.write(linev6.getBytes());
            }
        } else {
            for (String hostname : parser.getBlacklist()) {
                line = Constants.LINE_SEPERATOR + redirectionIP + " " + hostname;
                bos.write(line.getBytes());
            }
        }

        /* REDIRECTION LIST: write redirection items */
        String redirectionItemHostname;
        String redirectionItemIP;
        for (HashMap.Entry<String, String> item : parser.getRedirectionList().entrySet()) {
            redirectionItemHostname = item.getKey();
            redirectionItemIP = item.getValue();

            line = Constants.LINE_SEPERATOR + redirectionItemIP + " " + redirectionItemHostname;
            bos.write(line.getBytes());
        }

        // hosts file has to end with new line, when not done last entry won't be
        // recognized
        bos.write(Constants.LINE_SEPERATOR.getBytes());

    } catch (FileNotFoundException e) {
        Log.e(Constants.TAG, "file to read or file to write could not be found", e);

        returnCode = StatusCodes.PRIVATE_FILE_FAIL;
    } catch (IOException e) {
        Log.e(Constants.TAG, "files can not be written or read", e);

        returnCode = StatusCodes.PRIVATE_FILE_FAIL;
    } finally {
        try {
            if (bos != null) {
                bos.flush();
                bos.close();
            }
        } catch (Exception e) {
            Log.e(Constants.TAG, "Error closing output streams", e);
        }
    }

    // delete downloaded hosts file from private storage
    mService.deleteFile(Constants.DOWNLOADED_HOSTS_FILENAME);

    /* APPLY: apply hosts file using RootTools in copyHostsFile() */
    updateApplyNotification(mService, mService.getString(R.string.apply_dialog),
            mService.getString(R.string.apply_dialog_apply));

    Shell rootShell = null;
    try {
        rootShell = Shell.startRootShell();
    } catch (Exception e) {
        Log.e(Constants.TAG, "Problem opening a root shell!", e);
    }

    // copy build hosts file with RootTools, based on target from preferences
    try {
        if (PreferenceHelper.getApplyMethod(mService).equals("writeToSystem")) {

            ApplyUtils.copyHostsFile(mService, Constants.ANDROID_SYSTEM_ETC_HOSTS, rootShell);
        } else if (PreferenceHelper.getApplyMethod(mService).equals("writeToDataData")) {

            ApplyUtils.copyHostsFile(mService, Constants.ANDROID_DATA_DATA_HOSTS, rootShell);
        } else if (PreferenceHelper.getApplyMethod(mService).equals("writeToData")) {

            ApplyUtils.copyHostsFile(mService, Constants.ANDROID_DATA_HOSTS, rootShell);
        } else if (PreferenceHelper.getApplyMethod(mService).equals("customTarget")) {

            ApplyUtils.copyHostsFile(mService, PreferenceHelper.getCustomTarget(mService), rootShell);
        }
    } catch (NotEnoughSpaceException e) {
        Log.e(Constants.TAG, "Exception: ", e);

        returnCode = StatusCodes.NOT_ENOUGH_SPACE;
    } catch (RemountException e) {
        Log.e(Constants.TAG, "Exception: ", e);

        returnCode = StatusCodes.REMOUNT_FAIL;
    } catch (CommandException e) {
        Log.e(Constants.TAG, "Exception: ", e);

        returnCode = StatusCodes.COPY_FAIL;
    }

    // delete generated hosts file from private storage
    mService.deleteFile(Constants.HOSTS_FILENAME);

    /*
     * Set last_modified_local dates in database to last_modified_online, got in download task
     */
    ProviderHelper.updateAllEnabledHostsSourcesLastModifiedLocalFromOnline(mService);

    /* check if hosts file is applied with chosen method */
    // check only if everything before was successful
    if (returnCode == StatusCodes.SUCCESS) {
        if (PreferenceHelper.getApplyMethod(mService).equals("writeToSystem")) {

            /* /system/etc/hosts */

            if (!ApplyUtils.isHostsFileCorrect(mService, Constants.ANDROID_SYSTEM_ETC_HOSTS)) {
                returnCode = StatusCodes.APPLY_FAIL;
            }
        } else if (PreferenceHelper.getApplyMethod(mService).equals("writeToDataData")) {

            /* /data/data/hosts */

            if (!ApplyUtils.isHostsFileCorrect(mService, Constants.ANDROID_DATA_DATA_HOSTS)) {
                returnCode = StatusCodes.APPLY_FAIL;
            } else {
                if (!ApplyUtils.isSymlinkCorrect(Constants.ANDROID_DATA_DATA_HOSTS, rootShell)) {
                    returnCode = StatusCodes.SYMLINK_MISSING;
                }
            }
        } else if (PreferenceHelper.getApplyMethod(mService).equals("writeToData")) {

            /* /data/data/hosts */

            if (!ApplyUtils.isHostsFileCorrect(mService, Constants.ANDROID_DATA_HOSTS)) {
                returnCode = StatusCodes.APPLY_FAIL;
            } else {
                if (!ApplyUtils.isSymlinkCorrect(Constants.ANDROID_DATA_HOSTS, rootShell)) {
                    returnCode = StatusCodes.SYMLINK_MISSING;
                }
            }
        } else if (PreferenceHelper.getApplyMethod(mService).equals("customTarget")) {

            /* custom target */

            String customTarget = PreferenceHelper.getCustomTarget(mService);

            if (!ApplyUtils.isHostsFileCorrect(mService, customTarget)) {
                returnCode = StatusCodes.APPLY_FAIL;
            } else {
                if (!ApplyUtils.isSymlinkCorrect(customTarget, rootShell)) {
                    returnCode = StatusCodes.SYMLINK_MISSING;
                }
            }
        }
    }

    try {
        rootShell.close();
    } catch (Exception e) {
        Log.e(Constants.TAG, "Problem closing the root shell!", e);
    }

    /* check if APN proxy is set */
    if (returnCode == StatusCodes.SUCCESS) {
        if (ApplyUtils.isApnProxySet(mService)) {
            Log.d(Constants.TAG, "APN proxy is set!");
            returnCode = StatusCodes.APN_PROXY;
        }
    }

    return returnCode;
}

From source file:net.wastl.webmail.server.WebMailServlet.java

/**
 * Handle a request to the WebMail servlet. This is the central method of
 * the WebMailServlet. It first gathers all of the necessary information
 * from the client, then either creates or gets a Session and executes the
 * URL handler for the given path.//  www .j  a v a 2  s  .  c o  m
 */
public void service(ServletRequest req1, ServletResponse res1) throws ServletException {
    final HttpServletRequest req = (HttpServletRequest) req1;
    final HttpServletResponse res = (HttpServletResponse) res1;
    final HTTPRequestHeader http_header = new HTTPRequestHeader();

    if (req.getServletPath().equals("/admin"))
        try {
            log.debug("Forwarding /admin request back to self");
            req.getRequestDispatcher("WebMail/admin").forward(req1, res1);
            return;
        } catch (IOException ioe) {
            log.fatal("Forward from '/admin' failed", ioe);
            throw new ServletException(ioe.getMessage());
        }

    final Enumeration en = req.getHeaderNames();
    while (en.hasMoreElements()) {
        final String s = (String) en.nextElement();
        http_header.setHeader(s, req.getHeader(s));
    }

    http_header.setPath(req.getPathInfo() == null ? "/" : req.getPathInfo());

    InetAddress addr;
    try {
        addr = InetAddress.getByName(req.getRemoteHost());
    } catch (final UnknownHostException e) {
        try {
            addr = InetAddress.getByName(req.getRemoteAddr());
        } catch (final Exception ex) {
            throw new ServletException("Remote host must identify!");
        }
    }

    HTMLDocument content = null;
    final int err_code = 400;
    HTTPSession sess = null;

    /*
     * Here we try to parse the MIME content that the Client sent in his
     * POST since the JServ doesn't do that for us:-( At least we can use
     * the functionality provided by the standalone server where we need to
     * parse the content ourself anyway.
     */
    try {
        final BufferedOutputStream out = new BufferedOutputStream(res.getOutputStream());

        /*
         * First we try to use the Servlet API's methods to parse the
         * parameters. Unfortunately, it doesn't know how to handle MIME
         * multipart POSTs, so we will have to handle that ourselves
         */

        /*
         * First get all the parameters and set their values into
         * http_header
         */
        Enumeration enum2 = req.getParameterNames();
        while (enum2.hasMoreElements()) {
            final String s = (String) enum2.nextElement();
            http_header.setContent(s, req.getParameter(s));
            // log.info("Parameter "+s);
        }

        /* Then we set all the headers in http_header */
        enum2 = req.getHeaderNames();
        while (enum2.hasMoreElements()) {
            final String s = (String) enum2.nextElement();
            http_header.setHeader(s, req.getHeader(s));
        }

        /*
         * In Servlet API 2.2 we might want to fetch the attributes also,
         * but this doesn't work in API 2.0, so we leave it commented out
         */
        // enum2=req.getAttributeNames();
        // while(enum2.hasMoreElements()) {
        // String s=(String)enum2.nextElement();
        // log.info("Attribute "+s);
        // }

        /* Now let's try to handle multipart/form-data posts */

        if (req.getContentType() != null
                && req.getContentType().toUpperCase().startsWith("MULTIPART/FORM-DATA")) {
            final int size = Integer.parseInt(WebMailServer.getStorage().getConfig("max attach size"));
            final MultipartParser mparser = new MultipartParser(req, size);
            Part p;
            while ((p = mparser.readNextPart()) != null) {
                if (p.isFile()) {
                    final ByteStore bs = ByteStore.getBinaryFromIS(((FilePart) p).getInputStream(), size);
                    bs.setName(((FilePart) p).getFileName());
                    bs.setContentType(getStorage().getMimeType(((FilePart) p).getFileName()));
                    http_header.setContent(p.getName(), bs);
                    log.info("File name " + bs.getName());
                    log.info("Type      " + bs.getContentType());

                } else if (p.isParam()) {
                    http_header.setContent(p.getName(), ((ParamPart) p).getStringValue());
                }

                // log.info("Parameter "+p.getName());
            }
        }

        try {
            final String url = http_header.getPath();

            try {
                /* Find out about the session id */
                sess = req.getSession(false) == null ? null
                        : (HTTPSession) req.getSession(false).getAttribute("webmail.session");

                /*
                 * If the user was logging on, he doesn't have a session id,
                 * so generate one. If he already had one, all the better,
                 * we will take the old one
                 */
                if (sess == null && url.startsWith("/login")) {
                    sess = newSession(req, http_header);
                } else if (sess == null && url.startsWith("/admin/login")) {
                    http_header.setHeader("LOGIN", "Administrator");
                    sess = newAdminSession(req, http_header);
                }
                if (sess == null && !url.equals("/") && !url.startsWith("/passthrough")
                        && !url.startsWith("/admin")) {
                    content = getURLHandler().handleURL("/logout", sess, http_header);
                } else {
                    /* Ensure that the session state is up-to-date */
                    if (sess != null) {
                        sess.setEnv();
                    }

                    /* Let the URLHandler determine the result of the query */
                    content = getURLHandler().handleURL(url, sess, http_header);
                }
            } catch (final InvalidPasswordException e) {
                log.error("Connection to " + addr.toString() + ": Authentication failed!");
                if (url.startsWith("/admin/login")) {
                    content = getURLHandler().handleURL("/admin", null, http_header);
                } else if (url.startsWith("/login")) {
                    content = getURLHandler().handleURL("/", null, http_header);
                } else
                    // content=new
                    // HTMLErrorMessage(getStorage(),e.getMessage());
                    throw new ServletException("Invalid URL called!");
            } catch (final Exception ex) {
                content = getURLHandler().handleException(ex, sess, http_header);
                log.debug("Some strange error while handling request", ex);
            }

            /*
             * Set some HTTP headers: Date is now, the document should
             * expire in 5 minutes, proxies and clients shouldn't cache it
             * and all WebMail documents must be revalidated when they think
             * they don't have to follow the "no-cache".
             */
            res.setDateHeader("Date:", System.currentTimeMillis());
            res.setDateHeader("Expires", System.currentTimeMillis() + 300000);
            res.setHeader("Pragma", "no-cache");
            res.setHeader("Cache-Control", "must-revalidate");

            synchronized (out) {
                res.setStatus(content.getReturnCode());

                if (content.hasHTTPHeader()) {
                    final Enumeration enumVar = content.getHTTPHeaderKeys();
                    while (enumVar.hasMoreElements()) {
                        final String s = (String) enumVar.nextElement();
                        res.setHeader(s, content.getHTTPHeader(s));
                    }
                }

                /*
                 * What we will send is an image or some other sort of
                 * binary
                 */
                if (content instanceof HTMLImage) {
                    final HTMLImage img = (HTMLImage) content;
                    /*
                     * the HTMLImage class provides us with most of the
                     * necessary information that we want to send
                     */
                    res.setHeader("Content-Type", img.getContentType());
                    res.setHeader("Content-Transfer-Encoding", img.getContentEncoding());
                    res.setHeader("Content-Length", "" + img.size());
                    res.setHeader("Connection", "Keep-Alive");

                    /* Send 8k junks */
                    int offset = 0;
                    while (offset + chunk_size < img.size()) {
                        out.write(img.toBinary(), offset, chunk_size);
                        offset += chunk_size;
                    }
                    out.write(img.toBinary(), offset, img.size() - offset);
                    out.flush();

                    out.close();
                } else {
                    final byte[] encoded_content = content.toString().getBytes("UTF-8");

                    /*
                     * We are sending HTML text. Set the encoding to UTF-8
                     * for Unicode messages
                     */
                    res.setHeader("Content-Length", "" + (encoded_content.length + 2));
                    res.setHeader("Connection", "Keep-Alive");
                    res.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

                    out.write(encoded_content);
                    out.write("\r\n".getBytes());

                    out.flush();

                    out.close();
                }
            }
        } catch (final DocumentNotFoundException e) {
            log.info("Connection to " + addr.toString() + ": Could not handle request (" + err_code
                    + ") (Reason: " + e.getMessage() + ")");
            throw new ServletException("Error: " + e.getMessage(), e);
            // res.setStatus(err_code);
            // res.setHeader("Content-type","text/html");
            // res.setHeader("Connection","close");

            // content=new HTMLErrorMessage(getStorage(),e.getMessage());
            // out.write((content+"\r\n").getBytes("UTF-8"));
            // out.write("</HTML>\r\n".getBytes());
            // out.flush();
            // out.close();
        }
    } catch (final Exception e) {
        log.info("Connection to " + addr.toString() + " closed unexpectedly", e);
        throw new ServletException(e.getMessage());
    }
}

From source file:com.processing.core.PApplet.java

static public boolean saveStream(File targetFile, InputStream sourceStream) {
    File tempFile = null;//from   w ww .  j  a  v a2s  .c  om
    try {
        File parentDir = targetFile.getParentFile();
        createPath(targetFile);
        tempFile = File.createTempFile(targetFile.getName(), null, parentDir);

        BufferedInputStream bis = new BufferedInputStream(sourceStream, 16384);
        FileOutputStream fos = new FileOutputStream(tempFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = bis.read(buffer)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }

        bos.flush();
        bos.close();
        bos = null;

        if (targetFile.exists() && !targetFile.delete()) {
            System.err.println("Could not replace " + targetFile.getAbsolutePath() + ".");
        }

        if (!tempFile.renameTo(targetFile)) {
            System.err.println("Could not rename temporary file " + tempFile.getAbsolutePath());
            return false;
        }
        return true;

    } catch (IOException e) {
        if (tempFile != null) {
            tempFile.delete();
        }
        e.printStackTrace();
        return false;
    }
}