Example usage for java.io FileInputStream available

List of usage examples for java.io FileInputStream available

Introduction

In this page you can find the example usage for java.io FileInputStream available.

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Usage

From source file:uk.org.openeyes.diagnostics.FieldProcessor.java

/**
 * Create the main measurement text that will be understood by the server.
 * /* ww w. j  a va  2  s .  c  o m*/
 * @param patientRef the patient's reference/hos num.
 * @param xmlFile non-null existent file containing humphrey XML.
 * @param file the non-null image file.
 * @param fieldReport field report containing 
 * 
 * @return String measurement text.
 * 
 * @throws IOException if the 
 */
private String generateMeasurementText(String patientRef, File xmlFile, File file, FieldReport fieldReport)
        throws IOException {

    // execute the operation
    File imageConverted = new File(file.getParentFile(), FilenameUtils.getBaseName(file.getName()) + ".gif");
    File imageCropped = new File(file.getParentFile(),
            FilenameUtils.getBaseName(file.getName()) + "-cropped.gif");
    this.transformImages(file, imageConverted, imageCropped);
    BASE64Encoder encoder = new BASE64Encoder();
    FileInputStream fis = new FileInputStream(imageConverted);
    String encodedData = encoder.encode(IOUtils.toByteArray(fis, fis.available()));

    encoder = new BASE64Encoder();
    fis = new FileInputStream(imageCropped);
    String encodedDataThumb = encoder.encode(IOUtils.toByteArray(fis, fis.available()));

    String reportText = null;

    reportText = this.getHumphreyMeasurement(xmlFile, String.format("%07d", new Integer(patientRef)),
            fieldReport, encodedData, encodedDataThumb);

    imageConverted.delete();
    imageCropped.delete();
    return reportText;
}

From source file:org.zywx.wbpalmstar.plugin.uexaudio.EUExAudio.java

private void TestBackgroundRecord(String audioFolder) throws Exception {
    audioRecorder.startRecord(new File(audioFolder), 1, "testPermission");
    Thread.sleep(300);//300???
    audioRecorder.stopRecord();/*from  w w w. j  a va  2 s.  co m*/
    long size = 0;
    String recordFile = audioRecorder.getRecordFile();
    File file = new File(recordFile);
    if (file.exists()) {
        FileInputStream fis = null;
        fis = new FileInputStream(file);
        size = fis.available();
        fis.close();
    }
    BDebug.i("test size", size + "");
    if ((recordFile == null) || (recordFile.endsWith(".amr") && size <= 30)) {
        throw new myAudioPermissionException("AudioPermission maybe denied, please accept audio permission");
    }
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractServiceProviderLogoController.java

private void logoResponse(String imagePath, String defaultImagePath, HttpServletResponse response) {
    FileInputStream fileinputstream = null;
    String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    if (rootImageDir != null && !rootImageDir.trim().equals("")) {
        try {/*from   ww  w  . j  a  va 2 s .  co  m*/
            if (imagePath != null && !imagePath.trim().equals("")) {
                String absoluteImagePath = FilenameUtils.concat(rootImageDir, imagePath);
                fileinputstream = new FileInputStream(absoluteImagePath);
                if (fileinputstream != null) {
                    int numberBytes = fileinputstream.available();
                    byte bytearray[] = new byte[numberBytes];
                    fileinputstream.read(bytearray);
                    response.setContentType("image/" + FilenameUtils.getExtension(imagePath));
                    // TODO:Set Cache headers for browser to force browser to cache to reduce load
                    OutputStream outputStream = response.getOutputStream();
                    response.setContentLength(numberBytes);
                    outputStream.write(bytearray);
                    outputStream.flush();
                    outputStream.close();
                    fileinputstream.close();
                    return;
                }
            }
        } catch (FileNotFoundException e) {
            logger.debug("###File not found in retrieving logo");
        } catch (IOException e) {
            logger.debug("###IO Error in retrieving logo");
        }
    }
    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.setHeader("Location", defaultImagePath);
}

From source file:gov.nih.nci.ispy.web.taglib.PCAPlotTag.java

public int doStartTag() {
    chart = null;/*from  w  w w . j  av  a 2  s  .  co  m*/
    pcaResults = null;
    pcaData.clear();

    ServletRequest request = pageContext.getRequest();
    HttpSession session = pageContext.getSession();
    Object o = request.getAttribute(beanName);
    JspWriter out = pageContext.getOut();
    ServletResponse response = pageContext.getResponse();

    try {
        //retrieve the Finding from cache and build the list of PCAData points
        PrincipalComponentAnalysisFinding principalComponentAnalysisFinding = (PrincipalComponentAnalysisFinding) businessTierCache
                .getSessionFinding(session.getId(), taskId);

        Collection<ClinicalFactorType> clinicalFactors = new ArrayList<ClinicalFactorType>();
        List<String> sampleIds = new ArrayList<String>();
        Map<String, PCAresultEntry> pcaResultMap = new HashMap<String, PCAresultEntry>();

        pcaResults = principalComponentAnalysisFinding.getResultEntries();
        for (PCAresultEntry pcaEntry : pcaResults) {
            sampleIds.add(pcaEntry.getSampleId());
            pcaResultMap.put(pcaEntry.getSampleId(), pcaEntry);
        }

        //Get the clinical data for the sampleIds
        ClinicalDataService cqs = ClinicalDataServiceFactory.getInstance();
        IdMapperFileBasedService idMapper = IdMapperFileBasedService.getInstance();
        //Map<String, ClinicalData> clinicalDataMap = cqs.getClinicalDataMapForLabtrackIds(sampleIds);              

        PCAresultEntry entry;
        //ClinicalData clinData;
        //PatientData patientData;
        SampleInfo si;
        TimepointType timepoint;
        for (String id : sampleIds) {

            entry = pcaResultMap.get(id);
            ISPYPCADataPoint pcaPoint = new ISPYPCADataPoint(id, entry.getPc1(), entry.getPc2(),
                    entry.getPc3());

            si = idMapper.getSampleInfoForLabtrackId(id);

            //clinData = cqs.getClinicalDataForPatientDID(si.getRegistrantId(), si.getTimepoint());
            //patientData = cqs.getPatientDataForPatientDID(si.getISPYId());
            Set<String> ispyIds = new HashSet<String>();
            ispyIds.add(si.getISPYId());
            ISPYclinicalDataQueryDTO dto = new ISPYclinicalDataQueryDTO();
            dto.setRestrainingSamples(ispyIds);
            Set<PatientData> pdSet = cqs.getClinicalData(dto);
            for (PatientData patientData : pdSet) {
                pcaPoint.setISPY_ID(si.getISPYId());
                timepoint = si.getTimepoint();

                pcaPoint.setTimepoint(timepoint);

                if (patientData != null) {
                    pcaPoint.setClinicalStage(patientData.getClinicalStage());

                    int clinRespVal;
                    Double mriPctChange = null;
                    if (timepoint == TimepointType.T1) {
                        pcaPoint.setClinicalResponse(ClinicalResponseType.NA);
                        pcaPoint.setTumorMRIpctChange(null);
                    } else if (timepoint == TimepointType.T2) {
                        clinRespVal = PatientData.parseValue(patientData.getClinRespT1_T2());
                        //set the clinical respoinse to the T1_T2
                        pcaPoint.setClinicalResponse(ClinicalResponseType.getTypeForValue(clinRespVal));
                        pcaPoint.setTumorMRIpctChange(patientData.getMriPctChangeT1_T2());
                    } else if (timepoint == TimepointType.T3) {
                        //set the clinical response to T1_T3
                        clinRespVal = PatientData.parseValue(patientData.getClinRespT1_T3());
                        pcaPoint.setClinicalResponse(ClinicalResponseType.getTypeForValue(clinRespVal));
                        pcaPoint.setTumorMRIpctChange(patientData.getMriPctChangeT1_T3());
                    } else if (timepoint == TimepointType.T4) {
                        //set the clinical response to T1_T4
                        clinRespVal = PatientData.parseValue(patientData.getClinRespT1_T4());
                        pcaPoint.setClinicalResponse(ClinicalResponseType.getTypeForValue(clinRespVal));
                        pcaPoint.setTumorMRIpctChange(patientData.getMriPctChangeT1_T4());
                    } else {
                        pcaPoint.setClinicalResponse(ClinicalResponseType.UNKNOWN);
                        pcaPoint.setTumorMRIpctChange(null);
                    }
                }

                pcaData.add(pcaPoint);
            }
        }

        //check the components to see which graph to get
        if (components.equalsIgnoreCase("PC1vsPC2")) {
            ISPYPrincipalComponentAnalysisPlot plot = new ISPYPrincipalComponentAnalysisPlot(pcaData,
                    PCAcomponent.PC2, PCAcomponent.PC1,
                    ColorByType.valueOf(ColorByType.class, colorBy.toUpperCase()));
            chart = plot.getChart();
        }
        if (components.equalsIgnoreCase("PC1vsPC3")) {
            ISPYPrincipalComponentAnalysisPlot plot = new ISPYPrincipalComponentAnalysisPlot(pcaData,
                    PCAcomponent.PC3, PCAcomponent.PC1,
                    ColorByType.valueOf(ColorByType.class, colorBy.toUpperCase()));
            chart = plot.getChart();
        }
        if (components.equalsIgnoreCase("PC2vsPC3")) {
            ISPYPrincipalComponentAnalysisPlot plot = new ISPYPrincipalComponentAnalysisPlot(pcaData,
                    PCAcomponent.PC3, PCAcomponent.PC2,
                    ColorByType.valueOf(ColorByType.class, colorBy.toUpperCase()));
            chart = plot.getChart();
        }

        ISPYImageFileHandler imageHandler = new ISPYImageFileHandler(session.getId(), "png", 650, 600);
        //The final complete path to be used by the webapplication
        String finalPath = imageHandler.getSessionTempFolder();
        String finalURLpath = imageHandler.getFinalURLPath();
        /*
         * Create the actual charts, writing it to the session temp folder
        */
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        String mapName = imageHandler.createUniqueMapName();
        //PrintWriter writer = new PrintWriter(new FileWriter(mapName));
        ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 650, 600, info);
        //ImageMapUtil.writeBoundingRectImageMap(writer,"PCAimageMap",info,true);
        //writer.close();

        /*   This is here to put the thread into a loop while it waits for the
         *   image to be available.  It has an unsophisticated timer but at 
         *   least it is something to avoid an endless loop.
         **/
        boolean imageReady = false;
        int timeout = 1000;
        FileInputStream inputStream = null;
        while (!imageReady) {
            timeout--;
            try {
                inputStream = new FileInputStream(finalPath);
                inputStream.available();
                imageReady = true;
                inputStream.close();
            } catch (IOException ioe) {
                imageReady = false;
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            if (timeout <= 1) {

                break;
            }
        }

        out.print(ImageMapUtil.getBoundingRectImageMapTag(mapName, false, info));
        finalURLpath = finalURLpath.replace("\\", "/");
        long randomness = System.currentTimeMillis(); //prevent image caching
        out.print("<img id=\"geneChart\" name=\"geneChart\" src=\"" + finalURLpath + "?" + randomness
                + "\" usemap=\"#" + mapName + "\" border=\"0\" />");

        //(imageHandler.getImageTag(mapFileName));

    } catch (IOException e) {
        logger.error(e);
    } catch (Exception e) {
        logger.error(e);
    } catch (Throwable t) {
        logger.error(t);
    }

    return EVAL_BODY_INCLUDE;
}

From source file:cn.org.once.cstack.cli.utils.ApplicationUtils.java

public String deployFromAWar(File path, boolean openBrowser) throws MalformedURLException, URISyntaxException {
    checkConnectedAndApplicationSelected();

    String body = "";

    Guard.guardTrue(path != null, "Please specify a file path");

    try {//  ww  w.  jav  a2  s.co m
        File file = path;
        FileInputStream fileInputStream = new FileInputStream(file);
        fileInputStream.available();
        fileInputStream.close();
        FileSystemResource resource = new FileSystemResource(file);
        Map<String, Object> params = new HashMap<>();
        params.put("file", resource);
        params.putAll(authenticationUtils.getMap());
        body = (String) restUtils.sendPostForUpload(authenticationUtils.finalHost + urlLoader.actionApplication
                + currentApplication.getName() + "/deploy", params).get("body");
    } catch (IOException e) {
        throw new CloudUnitCliException("The file could not be opened", e);
    }

    if (StringUtils.isNotEmpty(body) && openBrowser) {
        DesktopAPI.browse(URI.create(currentApplication.getLocation()));
    }

    return MessageFormat.format("Application deployed. Access on {0}", currentApplication.getLocation());
}

From source file:com.lewa.crazychapter11.MainActivity.java

private static String loadConfig(String filePath) {
    File file = new File(filePath);
    Log.i("algerheJson", "file=" + file);
    if (!file.exists()) {
        Log.i("algerheJson", "not exist json file !~~~~");
        return "";
    }//w  w w . j a  v  a2s. c  o  m
    byte[] datas = null;
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
        int avalibleLength = fis.available();
        datas = new byte[avalibleLength];
        fis.read(datas);
        fis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (null != datas) {
        Log.i("algerheJson", "datas=" + datas);

        return EncodingUtils.getString(datas, "UTF-8");
    }
    return "";
}

From source file:com.sec.ose.osi.thread.job.identify.data.IdentifyQueue.java

private void init() {

    String userID = SDKInterfaceImpl.getInstance().getUserID();
    transactionLogFilePath = LOG_FILE_DIRECTORY + "/TRANSACTION_LOG_" + userID + "_"
            + DateUtil.getCurrentTime("%1$tY%1$tm%1$td") + ".dat";
    identifyQueueFilePath = DAT_FILE_DIRECTORY + "/identified_" + userID + ".dat";

    log.debug("open Identify Queue File: \"" + identifyQueueFilePath + "\"");

    prepareWritingTransactionLogFolder();
    if ("true".equals(Property.getInstance().getProperty(Property.LOGGING_IDENTIFY_TRANSACTIONS))) {
        transactionLogWrite = true;/*  w  w w.j  a  va2s. c o m*/
    }

    File dir = new File(DAT_FILE_DIRECTORY);
    if (!dir.exists()) {
        if (dir.mkdirs() == false) {
            log.error("FATAL:" + DAT_FILE_DIRECTORY + " is not created!!");
        }
    }

    File file = new File(identifyQueueFilePath);
    FileInputStream fis = null;
    ObjectInputStream oisReader = null;
    try {
        if (!file.exists()) {
            file.createNewFile();
        } else {
            fis = new FileInputStream(identifyQueueFilePath);
            if (fis != null && fis.available() > 0) {
                oisReader = new ObjectInputStream(fis);

                IdentifyData tmpIdentifiedData;

                while ((tmpIdentifiedData = (IdentifyData) oisReader.readObject()) != null) {

                    log.debug("read from File : \n" + tmpIdentifiedData + "\n - queueSize: " + size());

                    int type = tmpIdentifiedData.getCompositeType();
                    if ((type & IdentificationConstantValue.CODE_MATCH_TYPE) != 0) {

                        // step1
                        if (tmpIdentifiedData.getCurrentComponentName() == null
                                || tmpIdentifiedData.getCurrentComponentName().length() == 0)
                            continue;

                        // step2
                        if (tmpIdentifiedData.getCurrentLicenseName() == null
                                || tmpIdentifiedData.getCurrentLicenseName().length() == 0)
                            continue;
                    }

                    identifyDataQueue.add(tmpIdentifiedData);
                    log.debug("add - queueSize: " + size());

                }
            }
        }
    } catch (IOException e) {
        log.debug("The end of the stream/block data has been reached");
    } catch (Exception e) {
        log.warn(e);
    } finally {
        try {
            if (oisReader != null) {
                try {
                    oisReader.close();
                } catch (Exception e) {
                    log.debug(e);
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                    log.debug(e);
                }
            }
        } catch (Exception e) {
            log.warn(e);
        }
    }

    updateIdentifyQueuFile();
}

From source file:org.tigris.subversion.svnclientadapter.AbstractClientAdapter.java

/**
 * Takes svn diff output and processes it to remove absolute paths and
 * convert them to relative paths which makes it easier to apply patch
 * /*www  . j a v a2 s . c  o  m*/
 * @param tmpFile - disk file containing diff output
 * @param outFile - file to store the updated diff output
 * @param relativeToPath - path to make file references relative to or null
 *             for absolute paths
 * @throws SVNClientException 
 */
private void stripPathsFromPatch(File tmpFile, File outFile, File relativeToPath) throws SVNClientException {
    String relativeStr = null;
    if (relativeToPath != null) {
        try {
            if (relativeToPath.isDirectory())
                relativeStr = relativeToPath.getCanonicalPath();
            else
                relativeStr = relativeToPath.getParentFile().getCanonicalPath();
        } catch (IOException e1) {
            if (relativeToPath.isDirectory())
                relativeStr = relativeToPath.getAbsolutePath();
            else
                relativeStr = relativeToPath.getParentFile().getAbsolutePath();
        }
        relativeStr += "/";
        relativeStr = relativeStr.replace('\\', '/');
    }

    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        fis = new FileInputStream(tmpFile);
        fos = new FileOutputStream(outFile);
        byte b[] = new byte[fis.available()];
        fis.read(b);
        if (relativeToPath != null) {
            byte o[] = new String(b).replaceAll(relativeStr, "").getBytes();
            fos.write(o);
        } else {
            fos.write(b);
        }
    } catch (FileNotFoundException e) {
        throw new SVNClientException(e);
    } catch (IOException e) {
        throw new SVNClientException(e);
    } finally {
        try {
            if (fis != null)
                fis.close();
        } catch (IOException e) {
        }
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.drools.semantics.lang.dl.DL_9_CompilationTest.java

private void printSourceFile(File f, PrintStream out) {
    try {/*w w  w.  ja  va2 s  .  c om*/
        FileInputStream fis = new FileInputStream(f);
        byte[] buf = new byte[fis.available()];
        fis.read(buf);
        out.println(new String(buf));
    } catch (IOException ioe) {
        ioe.printStackTrace();
        fail(ioe.getMessage());
    }
}

From source file:org.zywx.wbpalmstar.plugin.uexaudio.EUExAudio.java

public void stopBackgroundRecord(String[] parm) {
    int callbackId = -1;
    if (parm.length > 0) {
        callbackId = Integer.parseInt(parm[0]);
    }/*w w w .j  ava2s . com*/
    if (start_record_fail) {
        start_record_fail = false;
        BDebug.i("??", "");
        return;
    } else if (!startBackgroundRecord_singleton) {
        for (String par : parm) {
            BDebug.i(par);
        }
        long size = 0;
        audioRecorder.stopRecord();
        String recordFile = audioRecorder.getRecordFile();// !=""?audioRecorder.getRecordFile():"null";
        try {
            File file = new File(recordFile);
            if (file.exists()) {
                FileInputStream fis = null;
                fis = new FileInputStream(file);
                size = fis.available();
                fis.close();
            }
        } catch (Exception e) {
            BDebug.i("startRecord", "1");
            if (callbackId != -1) {
                callbackToJs(callbackId, false);
            } else {
                errorCallback(0, EUExCallback.F_E_AUDIO_SOUND_PLAY_NO_OPEN_ERROR_CODE,
                        finder.getString(mContext, "plugin_audio_no_open_error"));

            }
            return;
        }
        BDebug.i("size", size + "");
        if ((recordFile.endsWith(".amr") && size <= 100) || (recordFile.endsWith(".mp3") && size <= 2000)) {
            BDebug.i("startRecord", "2");
            if (callbackId != -1) {
                callbackToJs(callbackId, false);
            } else {
                errorCallback(0, EUExCallback.F_E_AUDIO_SOUND_PLAY_NO_OPEN_ERROR_CODE,
                        finder.getString(mContext, "plugin_audio_no_open_error"));
            }
        } else {
            if (callbackId != -1) {
                callbackToJs(callbackId, false, recordFile);
            } else {
                jsCallback(F_CALLBACK_NAME_AUDIO_BACKGROUND_RECORD, 0, EUExCallback.F_C_TEXT, recordFile);
            }
        }
        startBackgroundRecord_singleton = true;
    }
}