Example usage for java.lang System gc

List of usage examples for java.lang System gc

Introduction

In this page you can find the example usage for java.lang System gc.

Prototype

public static void gc() 

Source Link

Document

Runs the garbage collector in the Java Virtual Machine.

Usage

From source file:gov.nist.appvet.tool.SynchronousService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List items = null;//ww w  .  j  a  va 2  s  .c  om
    FileItem fileItem = null;

    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    // Get form fields
    Iterator iter = items.iterator();
    FileItem item = null;
    while (iter.hasNext()) {
        item = (FileItem) iter.next();
        if (item.isFormField()) {
            //String incomingParameter = item.getFieldName();
            //String incomingValue = item.getString();
            // For this service, we do not expect any input parameters 
            // except for the app file.
            //log.debug("Ignoring " + incomingParameter + " = " + incomingValue);
        } else {
            // item should now hold the received file
            if (item != null) {
                fileItem = item;
                log.debug("Received file: " + fileItem.getName());
            }
        }
    }

    String appFilePath = null;
    String fileName = null;
    Random rand = new Random(new Date().getTime());
    final int randInt = rand.nextInt(9999999);
    String id = new Integer(randInt).toString();

    if (fileItem != null) {
        fileName = getFileName(fileItem.getName());
        if (!fileName.endsWith(".apk")) {
            sendHttp400(response, "Invalid app file: " + fileItem.getName());
            return;
        }

        appFilePath = Properties.TEMP_DIR + "/" + id + fileName;
        log.debug("App file path: " + appFilePath);

        if (!saveFileUpload(fileItem, appFilePath)) {
            sendHttp500(response, "Could not save uploaded file");
            return;
        }
    } else {
        sendHttp400(response, "No app was received.");
        return;
    }

    String command = Properties.command + " " + appFilePath;

    StringBuffer reportBuffer = new StringBuffer();
    boolean succeeded = runTool(command, reportBuffer);
    if (!succeeded) {
        if (reportBuffer.toString().contains("java.lang.SecurityException")) {
            returnReport(response, fileName, ToolStatus.FAIL, reportBuffer.toString());
        } else {
            log.error("Error detected: " + reportBuffer.toString());
            returnReport(response, fileName, ToolStatus.ERROR, reportBuffer.toString());
        }
    } else {
        log.debug("Analyzing report for " + appFilePath);
        ToolStatus reportStatus = analyzeReport(reportBuffer.toString());
        log.debug("Result: " + reportStatus.name());
        returnReport(response, fileName, reportStatus, reportBuffer.toString());
    }

    boolean deleted = deleteFile(appFilePath);
    if (deleted) {
        log.debug("Deleted " + appFilePath);
    } else {
        log.error("Could not delete file " + appFilePath);
    }

    // Clean up
    reportBuffer = null;
    System.gc();
}

From source file:com.duroty.service.Mailet.java

public void run() {
    try {//from w w  w .j a va  2 s . c  o  m
        flush();
    } catch (Exception e2) {
        System.gc();
    } catch (OutOfMemoryError e2) {
        System.gc();
    } catch (Throwable e2) {
        if (mime != null) {
            sendError(mime, e2);
        }

        System.gc();
    } finally {
        if (servible != null) {
            servible.removePool(messageName + "--" + repositoryName);
        }
    }
}

From source file:dk.statsbiblioteket.util.reader.ReplacerTest.java

@Test
@Ignore/*from w ww  .  j a  va  2  s . c  om*/
public void testSpeedCharsVsString() throws Exception {
    Random random = new Random(456);
    int RUNS = 10;
    int[] RULES = new int[] { 0, 10, 100, 1000 };
    int[] DESTINATIONS = new int[] { 1, 10, 20 };
    int[] INPUT_CHARS = new int[] { 10, 100, 1000, 10000, 1000000 };

    for (int ruleCount : RULES) {
        for (int destinations : DESTINATIONS) {
            for (int inputChars : INPUT_CHARS) {
                Map<String, String> rules = ReplacePerformanceTest.getRangeReplacements(ruleCount, 1, 1, 1,
                        destinations);
                String input = ReplacePerformanceTest.randomWord(random, 0, inputChars);
                TextTransformer charsT = new CharArrayReplacer(rules);
                TextTransformer stringT = new StringReplacer(rules);
                System.gc();
                long charsTime = 0;
                long stringTime = 0;
                for (int runs = 0; runs < RUNS; runs++) {
                    long startTime = System.currentTimeMillis();
                    charsT.transform(input);
                    charsTime += System.currentTimeMillis() - startTime;
                    startTime = System.currentTimeMillis();
                    stringT.transform(input);
                    stringTime += System.currentTimeMillis() - startTime;
                }
                log.info("Rules: " + rules.size() + ", destination " + "lengths max: " + destinations
                        + ", input length: " + input.length() + ", chars: " + charsTime / RUNS + "ms, Strings: "
                        + stringTime / RUNS + "ms");
            }
        }
    }
}

From source file:ms1quant.MS1Quant.java

/**
 * @param args the command line arguments MS1Quant parameterfile
 *///from   w  w  w  .  j a  v a 2 s .co  m
public static void main(String[] args) throws Exception {

    BufferedReader reader = null;
    try {
        System.out.println(
                "=================================================================================================");
        System.out.println("Umpire MS1 quantification and feature detection analysis (version: "
                + UmpireInfo.GetInstance().Version + ")");
        if (args.length < 3 || !args[1].startsWith("-mode")) {
            System.out
                    .println("command : java -jar -Xmx10G MS1Quant.jar ms1quant.params -mode[1 or 2] [Option]");
            System.out.println("\n-mode");
            System.out.println("\t1:Single file mode--> mzXML_file PepXML_file");
            System.out.println("\t\tEx: -mode1 file1.mzXML file1.pep.xml");
            System.out.println(
                    "\t2:Folder mode--> mzXML_Folder PepXML_Folder, all generated csv tables will be merged into a single csv file");
            System.out.println("\t\tEx: -mode2 /data/mzxml/ /data/pepxml/");
            System.out.println("\nOptions");
            System.out.println(
                    "\t-C\tNo of concurrent files to be processed (only for folder mode), Ex. -C5, default:1");
            System.out.println("\t-p\tMinimum probability, Ex. -p0.9, default:0.9");
            System.out.println("\t-ID\tDetect identified feature only");
            System.out.println("\t-O\toutput folder, Ex. -O/data/");
            return;
        }
        ConsoleLogger consoleLogger = new ConsoleLogger();
        consoleLogger.SetConsoleLogger(Level.DEBUG);
        consoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "ms1quant_debug.log");
        Logger logger = Logger.getRootLogger();
        logger.debug("Command: " + Arrays.toString(args));
        logger.info("MS1Quant version: " + UmpireInfo.GetInstance().Version);

        String parameterfile = args[0];
        logger.info("Parameter file: " + parameterfile);
        File paramfile = new File(parameterfile);
        if (!paramfile.exists()) {
            logger.error("Parameter file " + paramfile.getAbsolutePath()
                    + " cannot be found. The program will exit.");
        }

        reader = new BufferedReader(new FileReader(paramfile.getAbsolutePath()));
        String line = "";
        InstrumentParameter param = new InstrumentParameter(InstrumentParameter.InstrumentType.TOF5600);
        int NoCPUs = 2;
        int NoFile = 1;
        param.DetermineBGByID = false;
        param.EstimateBG = true;

        //<editor-fold defaultstate="collapsed" desc="Read parameter file">
        while ((line = reader.readLine()) != null) {
            if (!"".equals(line) && !line.startsWith("#")) {
                logger.info(line);
                //System.out.println(line);
                if (line.split("=").length < 2) {
                    continue;
                }
                if (line.split("=").length < 2) {
                    continue;
                }
                String type = line.split("=")[0].trim();
                if (type.startsWith("para.")) {
                    type = type.replace("para.", "SE.");
                }
                String value = line.split("=")[1].trim();
                switch (type) {
                case "Thread": {
                    NoCPUs = Integer.parseInt(value);
                    break;
                }
                //<editor-fold defaultstate="collapsed" desc="instrument parameters">

                case "SE.MS1PPM": {
                    param.MS1PPM = Float.parseFloat(value);
                    break;
                }
                case "SE.MS2PPM": {
                    param.MS2PPM = Float.parseFloat(value);
                    break;
                }
                case "SE.SN": {
                    param.SNThreshold = Float.parseFloat(value);
                    break;
                }
                case "SE.MS2SN": {
                    param.MS2SNThreshold = Float.parseFloat(value);
                    break;
                }
                case "SE.MinMSIntensity": {
                    param.MinMSIntensity = Float.parseFloat(value);
                    break;
                }
                case "SE.MinMSMSIntensity": {
                    param.MinMSMSIntensity = Float.parseFloat(value);
                    break;
                }
                case "SE.MinRTRange": {
                    param.MinRTRange = Float.parseFloat(value);
                    break;
                }
                case "SE.MaxNoPeakCluster": {
                    param.MaxNoPeakCluster = Integer.parseInt(value);
                    param.MaxMS2NoPeakCluster = Integer.parseInt(value);
                    break;
                }
                case "SE.MinNoPeakCluster": {
                    param.MinNoPeakCluster = Integer.parseInt(value);
                    param.MinMS2NoPeakCluster = Integer.parseInt(value);
                    break;
                }
                case "SE.MinMS2NoPeakCluster": {
                    param.MinMS2NoPeakCluster = Integer.parseInt(value);
                    break;
                }
                case "SE.MaxCurveRTRange": {
                    param.MaxCurveRTRange = Float.parseFloat(value);
                    break;
                }
                case "SE.Resolution": {
                    param.Resolution = Integer.parseInt(value);
                    break;
                }
                case "SE.RTtol": {
                    param.RTtol = Float.parseFloat(value);
                    break;
                }
                case "SE.NoPeakPerMin": {
                    param.NoPeakPerMin = Integer.parseInt(value);
                    break;
                }
                case "SE.StartCharge": {
                    param.StartCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.EndCharge": {
                    param.EndCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.MS2StartCharge": {
                    param.MS2StartCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.MS2EndCharge": {
                    param.MS2EndCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.NoMissedScan": {
                    param.NoMissedScan = Integer.parseInt(value);
                    break;
                }
                case "SE.Denoise": {
                    param.Denoise = Boolean.valueOf(value);
                    break;
                }
                case "SE.EstimateBG": {
                    param.EstimateBG = Boolean.valueOf(value);
                    break;
                }
                case "SE.RemoveGroupedPeaks": {
                    param.RemoveGroupedPeaks = Boolean.valueOf(value);
                    break;
                }
                case "SE.MinFrag": {
                    param.MinFrag = Integer.parseInt(value);
                    break;
                }
                case "SE.IsoPattern": {
                    param.IsoPattern = Float.valueOf(value);
                    break;
                }
                case "SE.StartRT": {
                    param.startRT = Float.valueOf(value);
                }
                case "SE.EndRT": {
                    param.endRT = Float.valueOf(value);
                }

                //</editor-fold>
                }
            }
        }
        //</editor-fold>

        int mode = 1;
        if (args[1].equals("-mode2")) {
            mode = 2;
        } else if (args[1].equals("-mode1")) {
            mode = 1;
        } else {
            logger.error("-mode number not recongized. The program will exit.");
        }

        String mzXML = "";
        String pepXML = "";
        String mzXMLPath = "";
        String pepXMLPath = "";
        File mzXMLfile = null;
        File pepXMLfile = null;
        File mzXMLfolder = null;
        File pepXMLfolder = null;
        int idx = 0;
        if (mode == 1) {
            mzXML = args[2];
            logger.info("Mode1 mzXML file: " + mzXML);
            mzXMLfile = new File(mzXML);
            if (!mzXMLfile.exists()) {
                logger.error("Mode1 mzXML file " + mzXMLfile.getAbsolutePath()
                        + " cannot be found. The program will exit.");
                return;
            }
            pepXML = args[3];
            logger.info("Mode1 pepXML file: " + pepXML);
            pepXMLfile = new File(pepXML);
            if (!pepXMLfile.exists()) {
                logger.error("Mode1 pepXML file " + pepXMLfile.getAbsolutePath()
                        + " cannot be found. The program will exit.");
                return;
            }
            idx = 4;
        } else if (mode == 2) {
            mzXMLPath = args[2];
            logger.info("Mode2 mzXML folder: " + mzXMLPath);
            mzXMLfolder = new File(mzXMLPath);
            if (!mzXMLfolder.exists()) {
                logger.error("Mode2 mzXML folder " + mzXMLfolder.getAbsolutePath()
                        + " does not exist. The program will exit.");
                return;
            }
            pepXMLPath = args[3];
            logger.info("Mode2 pepXML folder: " + pepXMLPath);
            pepXMLfolder = new File(pepXMLPath);
            if (!pepXMLfolder.exists()) {
                logger.error("Mode2 pepXML folder " + pepXMLfolder.getAbsolutePath()
                        + " does not exist. The program will exit.");
                return;
            }
            idx = 4;
        }

        String outputfolder = "";
        float MinProb = 0f;
        for (int i = idx; i < args.length; i++) {
            if (args[i].startsWith("-")) {
                if (args[i].equals("-ID")) {
                    param.TargetIDOnly = true;
                    logger.info("Detect ID feature only: true");
                }
                if (args[i].startsWith("-O")) {
                    outputfolder = args[i].substring(2);
                    logger.info("Output folder: " + outputfolder);

                    File outputfile = new File(outputfolder);
                    if (!outputfolder.endsWith("\\") | outputfolder.endsWith("/")) {
                        outputfolder += "/";
                    }
                    if (!outputfile.exists()) {
                        outputfile.mkdir();
                    }
                }
                if (args[i].startsWith("-C")) {
                    try {
                        NoFile = Integer.parseInt(args[i].substring(2));
                        logger.info("No of concurrent files: " + NoFile);
                    } catch (Exception ex) {
                        logger.error(args[i]
                                + " is not a correct integer format, will process only one file at a time.");
                    }
                }
                if (args[i].startsWith("-p")) {
                    try {
                        MinProb = Float.parseFloat(args[i].substring(2));
                        logger.info("probability threshold: " + MinProb);
                    } catch (Exception ex) {
                        logger.error(args[i] + " is not a correct format, will use 0 as threshold instead.");
                    }
                }
            }
        }

        reader.close();
        TandemParam tandemparam = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
        PTMManager.GetInstance();

        if (param.TargetIDOnly) {
            param.EstimateBG = false;
            param.ApexDelta = 1.5f;
            param.NoMissedScan = 10;
            param.MiniOverlapP = 0.2f;
            param.RemoveGroupedPeaks = false;
            param.CheckMonoIsotopicApex = false;
            param.DetectByCWT = false;
            param.FillGapByBK = false;
            param.IsoCorrThreshold = -1f;
            param.SmoothFactor = 3;
        }

        if (mode == 1) {
            logger.info("Processing " + mzXMLfile.getAbsolutePath() + "....");
            long time = System.currentTimeMillis();
            LCMSPeakMS1 LCMS1 = new LCMSPeakMS1(mzXMLfile.getAbsolutePath(), NoCPUs);
            LCMS1.SetParameter(param);

            LCMS1.Resume = false;
            if (!param.TargetIDOnly) {
                LCMS1.CreatePeakFolder();
            }
            LCMS1.ExportPeakClusterTable = true;

            if (pepXMLfile.exists()) {
                tandemparam.InteractPepXMLPath = pepXMLfile.getAbsolutePath();
                LCMS1.ParsePepXML(tandemparam, MinProb);
                logger.info("No. of PSMs included: " + LCMS1.IDsummary.PSMList.size());
                logger.info("No. of Peptide ions included: " + LCMS1.IDsummary.GetPepIonList().size());
            }

            if (param.TargetIDOnly) {
                LCMS1.SaveSerializationFile = false;
            }

            if (param.TargetIDOnly || !LCMS1.ReadPeakCluster()) {
                LCMS1.PeakClusterDetection();
            }

            if (pepXMLfile.exists()) {
                LCMS1.AssignQuant(false);
                LCMS1.IDsummary.ExportPepID(outputfolder);
            }
            time = System.currentTimeMillis() - time;
            logger.info(LCMS1.ParentmzXMLName + " processed time:"
                    + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time),
                            TimeUnit.MILLISECONDS.toMinutes(time)
                                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)),
                            TimeUnit.MILLISECONDS.toSeconds(time)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))));
            LCMS1.BaseClearAllPeaks();
            LCMS1.SetSpectrumParser(null);
            LCMS1.IDsummary = null;
            LCMS1 = null;
            System.gc();
        } else if (mode == 2) {

            LCMSID IDsummary = new LCMSID("", "", "");
            logger.info("Parsing all pepXML files in " + pepXMLPath + "....");
            for (File file : pepXMLfolder.listFiles()) {
                if (file.getName().toLowerCase().endsWith("pep.xml")
                        || file.getName().toLowerCase().endsWith("pepxml")) {
                    PepXMLParser pepXMLParser = new PepXMLParser(IDsummary, file.getAbsolutePath(), MinProb);
                }
            }
            HashMap<String, LCMSID> LCMSIDMap = IDsummary.GetLCMSIDFileMap();

            ExecutorService executorPool = null;
            executorPool = Executors.newFixedThreadPool(NoFile);

            logger.info("Processing all mzXML files in " + mzXMLPath + "....");
            for (File file : mzXMLfolder.listFiles()) {
                if (file.getName().toLowerCase().endsWith("mzxml")) {
                    LCMSID id = LCMSIDMap.get(FilenameUtils.getBaseName(file.getName()));
                    if (id == null || id.PSMList == null) {
                        logger.warn("No IDs found in :" + FilenameUtils.getBaseName(file.getName())
                                + ". Quantification for this file is skipped");
                        continue;
                    }
                    if (!id.PSMList.isEmpty()) {
                        MS1TargetQuantThread thread = new MS1TargetQuantThread(file, id, NoCPUs, outputfolder,
                                param);
                        executorPool.execute(thread);
                    }
                }
            }
            LCMSIDMap.clear();
            LCMSIDMap = null;
            IDsummary = null;
            executorPool.shutdown();
            try {
                executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
            } catch (InterruptedException e) {
                logger.info("interrupted..");
            }

            if (outputfolder == null | outputfolder.equals("")) {
                outputfolder = mzXMLPath;
            }

            logger.info("Merging PSM files..");
            File output = new File(outputfolder);
            FileWriter writer = new FileWriter(output.getAbsolutePath() + "/PSM_merge.csv");
            boolean header = false;
            for (File csvfile : output.listFiles()) {
                if (csvfile.getName().toLowerCase().endsWith("_psms.csv")) {
                    BufferedReader outreader = new BufferedReader(new FileReader(csvfile));
                    String outline = outreader.readLine();
                    if (!header) {
                        writer.write(outline + "\n");
                        header = true;
                    }
                    while ((outline = outreader.readLine()) != null) {
                        writer.write(outline + "\n");
                    }
                    outreader.close();
                    csvfile.delete();
                }
            }
            writer.close();
        }
        logger.info("MS1 quant module is complete.");
    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}

From source file:com.github.lindenb.jvarkit.tools.bam2wig.Bam2Wig.java

private void run(final SamReader sfr) {
    SAMSequenceRecord prev_ssr = null;//from ww  w  .ja  v a  2s.c om
    SAMSequenceDictionary dict = sfr.getFileHeader().getSequenceDictionary();
    SAMRecordIterator iter = sfr.iterator();
    int array[] = null;
    SAMSequenceDictionaryProgress progess = new SAMSequenceDictionaryProgress(dict);
    if (custom_track) {
        pw.println("track type=wiggle_0 name=\"__REPLACE_WIG_NAME__\" description=\"__REPLACE_WIG_DESC__\"");
    }

    for (;;) {
        SAMRecord rec = null;
        if (iter.hasNext()) {
            rec = iter.next();
            progess.watch(rec);
            if (rec.getReadUnmappedFlag())
                continue;
            if (rec.getMappingQuality() == 0)
                continue;
            if (rec.getMappingQuality() < min_qual)
                continue;
        }

        if (rec == null || (prev_ssr != null && prev_ssr.getSequenceIndex() != rec.getReferenceIndex())) {
            if (prev_ssr != null) {
                int start0 = 0;
                while (start0 < array.length && array[start0] == 0) {
                    ++start0;
                }

                int end0 = prev_ssr.getSequenceLength();
                while (end0 > 0 && array[end0 - 1] == 0) {
                    --end0;
                }

                int last_non_zero_pos0 = start0;
                int num_zero_regions_skipped = 0;
                boolean need_print_header = true;
                while (start0 < end0) {
                    /* 
                     * http://genome.ucsc.edu/goldenPath/help/wiggle.html
                       Wiggle track data values can be integer or real, positive or negative values.
                       Chromosome positions are specified as 1-relative.
                       For a chromosome of length N, the first position is 1 and the last position is N. Only positions specified have data. Positions not specified do not have data and will not be graphed. 
                     */

                    int n = 0;
                    double sum = 0;
                    for (int j = 0; j < WINDOW_SIZE && start0 + j < array.length; ++j) {
                        sum += array[start0 + j];
                        n++;
                    }

                    if (sum / n < min_depth) {
                        sum = 0;
                    }

                    if (sum == 0) {
                        start0 += WINDOW_SHIFT;
                        num_zero_regions_skipped++;
                        continue;
                    } else {
                        if ((start0 - last_non_zero_pos0) <= min_gap) {
                            for (int r = 0; r < num_zero_regions_skipped; ++r) {
                                pw.println(0);
                            }
                        } else {
                            need_print_header = (num_zero_regions_skipped > 0);
                        }

                        last_non_zero_pos0 = start0;
                        num_zero_regions_skipped = 0;
                    }

                    if (need_print_header) {
                        need_print_header = false;
                        pw.println("fixedStep chrom=" + prev_ssr.getSequenceName() + " start=" + (start0 + 1)
                                + " step=" + WINDOW_SHIFT + " span=" + WINDOW_SIZE);
                    }

                    if (cast_to_integer) {
                        pw.println((int) (sum / n));
                    } else {
                        pw.println((float) (sum / n));
                    }

                    if (pw.checkError())
                        break;
                    start0 += WINDOW_SHIFT;
                }
                array = null;
                System.gc();
                prev_ssr = null;
            }
            if (rec == null)
                break;
            if (pw.checkError())
                break;
        }
        if (prev_ssr == null) {
            prev_ssr = dict.getSequence(rec.getReferenceIndex());
            LOG.info("Allocating int[" + prev_ssr.getSequenceLength() + "]");
            array = new int[prev_ssr.getSequenceLength()];
            LOG.info("Allocating : Done.");
            Arrays.fill(array, 0);
        }

        final Cigar cigar = rec.getCigar();
        if (cigar == null)
            continue;
        int refpos1 = rec.getAlignmentStart();
        for (CigarElement ce : cigar.getCigarElements()) {
            final CigarOperator op = ce.getOperator();
            if (op.consumesReferenceBases()) {
                if (op.consumesReadBases()) {
                    for (int i = 0; i < ce.getLength() && refpos1 <= array.length; ++i) {
                        if (refpos1 >= 1 && refpos1 <= array.length) {
                            array[refpos1 - 1]++;
                        }
                        refpos1++;
                    }
                } else {
                    refpos1 += ce.getLength();
                }
            }
        }
    }
    progess.finish();
    iter.close();
    pw.flush();
}

From source file:cycronix.CTandroid.CTAserver.java

/** Called when the activity is first created. */
@Override/*w  w  w  .jav  a 2s.c om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getSettings(); // Restore preferences
    copyAssets(); // copy assets to external storage

    setContentView(R.layout.main);
    statusET = (EditText) findViewById(R.id.myText);
    if (statusET != null)
        statusET.setText("Not Started.");
    statusET.setEnabled(false);
    myipET = (EditText) findViewById(R.id.myIP);
    if (myipET != null)
        myipET.setText(getIPAddress(true));
    myipET.setEnabled(false);
    counterET = (EditText) findViewById(R.id.Counter);
    counterET.setEnabled(false);
    memoryET = (EditText) findViewById(R.id.Memory);
    memoryET.setEnabled(false);

    // status timer
    myTimer = new Timer();
    myTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            TimerMethod();
        }
    }, 0, 1000); // check interval

    // get GUI objects
    serverPortET = (EditText) findViewById(R.id.serverPort);
    serverPortET.setText(serverPort);
    dataFolderET = (EditText) findViewById(R.id.dataFolder);
    dataFolderET.setText(dataFolder);

    runBtn = (RadioButton) findViewById(R.id.RunButton);
    stopBtn = (RadioButton) findViewById(R.id.StopButton);
    quitBtn = (RadioButton) findViewById(R.id.QuitButton);

    runBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!Running) {
                try {
                    pLog("Starting up...");
                    putSettings();
                    Running = true;
                    int port = Integer.valueOf(serverPortET.getText().toString());
                    String resourceFolderPath = Environment.getExternalStorageDirectory() + "/"
                            + resourceFolder;
                    String dataFolderPath = dataFolderET.getText().toString(); // full path
                    if (!dataFolderPath.startsWith("/")) // relative to external storage dir
                        dataFolderPath = Environment.getExternalStorageDirectory() + "/" + dataFolderPath;
                    //                    CTserver.debug=true;
                    cts = new CTserver(port, resourceFolderPath, dataFolderPath); // start local webserver
                    cts.start();
                    serverPortET.setEnabled(false);
                    dataFolderET.setEnabled(false);
                    pLog("Running!");
                } catch (Exception e) {
                    pLog("CTserver Launch Error: " + e);
                    finish();
                }
            }
        }
    });

    stopBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Running) {
                pLog("Shutting down...");
                //                     stopSource();
                Running = false;
                putSettings();
                if (cts != null)
                    cts.stop(); // stop local webserver
                pLog("Stopped.");
                serverPortET.setEnabled(true);
                dataFolderET.setEnabled(true);
                System.gc(); // force a garbage collection
            }
        }
    });

    quitBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            pLog("Quitting App...");
            Running = false;
            stopBtn.setChecked(true);
            putSettings();
            finish();
        }
    });
}

From source file:com.letv.commonjar.http.HttpJsonCallBack.java

/**
 * /*from ww  w .  j  ava 2 s . c  o  m*/
 * @param entity
 * @return
 * @throws IOException
 */
byte[] getResponseData(HttpEntity entity) throws IOException {
    byte[] responseBody = null;
    if (entity != null) {
        InputStream instream = entity.getContent();
        if (instream != null) {
            long contentLength = entity.getContentLength();
            if (contentLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }
            if (contentLength < 0) {
                contentLength = BUFFER_SIZE;
            }
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    int l, count = 0;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        count += l;
                        buffer.append(tmp, 0, l);
                        onProgress(count, (int) contentLength);
                    }
                } finally {
                    instream.close();
                }
                responseBody = buffer.toByteArray();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}

From source file:com.projity.pm.graphic.frames.StartupFactory.java

public GraphicManager instanceFromExistingSession(Container container) {

    System.gc(); // hope to avoid out of memory problems

    DebugUtils.isMemoryOk(true);//from w  ww .  jav  a  2 s  .  c  o  m

    long t = System.currentTimeMillis();
    //      System.out.println("---------- StartupFactory instanceFromExistingSession#1");
    final GraphicManager graphicManager = new GraphicManager(container);
    graphicManager.setStartupFactory(this);
    SessionFactory.getInstance().setJobQueue(graphicManager.getJobQueue());
    //if (Environment.isNewLook())
    graphicManager.initLookAndFeel();
    //      System.out.println("---------- StartupFactory instanceFromExistingSession#1 done in "+(System.currentTimeMillis()-t)+" ms");
    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            long t = System.currentTimeMillis();
            //            System.out.println("---------- StartupFactory instanceFromExistingSession#2");
            graphicManager.initView();
            //            System.out.println("---------- StartupFactory instanceFromExistingSession#2 done in "+(System.currentTimeMillis()-t)+" ms");
        }
    });
    //      graphicManager.invalidate();
    return graphicManager;
}

From source file:io.bitsquare.seednode.SeedNodeMain.java

@Override
protected void doExecute(OptionSet options) {
    final BitsquareEnvironment environment = new BitsquareEnvironment(options);
    SeedNode.setEnvironment(environment);

    UserThread.execute(() -> seedNode = new SeedNode());

    Thread.UncaughtExceptionHandler handler = (thread, throwable) -> {
        if (throwable.getCause() != null && throwable.getCause().getCause() != null
                && throwable.getCause().getCause() instanceof BlockStoreException) {
            log.error(throwable.getMessage());
        } else {// w  w  w.  j ava2 s .  c  om
            log.error("Uncaught Exception from thread " + Thread.currentThread().getName());
            log.error("throwableMessage= " + throwable.getMessage());
            log.error("throwableClass= " + throwable.getClass());
            log.error("Stack trace:\n" + ExceptionUtils.getStackTrace(throwable));
            throwable.printStackTrace();
            log.error("We shut down the app because an unhandled error occurred");
            // We don't use the restart as in case of OutOfMemory errors the restart might fail as well
            // The run loop will restart the node anyway...
            System.exit(EXIT_FAILURE);
        }
    };
    Thread.setDefaultUncaughtExceptionHandler(handler);
    Thread.currentThread().setUncaughtExceptionHandler(handler);

    String maxMemoryOption = environment.getProperty(AppOptionKeys.MAX_MEMORY);
    if (maxMemoryOption != null && !maxMemoryOption.isEmpty()) {
        try {
            maxMemory = Integer.parseInt(maxMemoryOption);
        } catch (Throwable t) {
            log.error(t.getMessage());
        }
    }

    UserThread.runPeriodically(() -> {
        Profiler.printSystemLoad(log);
        long usedMemoryInMB = Profiler.getUsedMemoryInMB();
        if (!stopped) {
            if (usedMemoryInMB > (maxMemory - 100)) {
                log.warn(
                        "\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
                                + "We are over our memory warn limit and call the GC. usedMemoryInMB: {}"
                                + "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n",
                        usedMemoryInMB);
                System.gc();
                usedMemoryInMB = Profiler.getUsedMemoryInMB();
                Profiler.printSystemLoad(log);
            }

            final long finalUsedMemoryInMB = usedMemoryInMB;
            UserThread.runAfter(() -> {
                if (finalUsedMemoryInMB > maxMemory)
                    restart(environment);
            }, 1);
        }
    }, CHECK_MEMORY_PERIOD_SEC);

    while (true) {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException ignore) {
        }
    }
}

From source file:io.bitsquare.statistics.StatisticsMain.java

@Override
protected void doExecute(OptionSet options) {
    final BitsquareEnvironment environment = new BitsquareEnvironment(options);
    Statistics.setEnvironment(environment);

    UserThread.execute(() -> statistics = new Statistics());

    Thread.UncaughtExceptionHandler handler = (thread, throwable) -> {
        if (throwable.getCause() != null && throwable.getCause().getCause() != null
                && throwable.getCause().getCause() instanceof BlockStoreException) {
            log.error(throwable.getMessage());
        } else {// w w w .  jav a 2 s .co m
            log.error("Uncaught Exception from thread " + Thread.currentThread().getName());
            log.error("throwableMessage= " + throwable.getMessage());
            log.error("throwableClass= " + throwable.getClass());
            log.error("Stack trace:\n" + ExceptionUtils.getStackTrace(throwable));
            throwable.printStackTrace();
            log.error("We shut down the app because an unhandled error occurred");
            // We don't use the restart as in case of OutOfMemory errors the restart might fail as well
            // The run loop will restart the node anyway...
            System.exit(EXIT_FAILURE);
        }
    };
    Thread.setDefaultUncaughtExceptionHandler(handler);
    Thread.currentThread().setUncaughtExceptionHandler(handler);

    String maxMemoryOption = environment.getProperty(AppOptionKeys.MAX_MEMORY);
    if (maxMemoryOption != null && !maxMemoryOption.isEmpty()) {
        try {
            maxMemory = Integer.parseInt(maxMemoryOption);
        } catch (Throwable t) {
            log.error(t.getMessage());
        }
    }

    UserThread.runPeriodically(() -> {
        Profiler.printSystemLoad(log);
        long usedMemoryInMB = Profiler.getUsedMemoryInMB();
        if (!stopped) {
            if (usedMemoryInMB > (maxMemory - 100)) {
                log.warn(
                        "\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
                                + "We are over our memory warn limit and call the GC. usedMemoryInMB: {}"
                                + "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n",
                        usedMemoryInMB);
                System.gc();
                usedMemoryInMB = Profiler.getUsedMemoryInMB();
                Profiler.printSystemLoad(log);
            }

            final long finalUsedMemoryInMB = usedMemoryInMB;
            UserThread.runAfter(() -> {
                if (finalUsedMemoryInMB > maxMemory) {
                    log.error(
                            "\n\n############################################################\n"
                                    + "We shut down as we are over our memory limit. usedMemoryInMB: {}"
                                    + "\n############################################################\n\n",
                            finalUsedMemoryInMB);
                    System.exit(EXIT_FAILURE);
                }
            }, 1);
        }
    }, CHECK_MEMORY_PERIOD_SEC);

    while (true) {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException ignore) {
        }
    }
}