Example usage for java.lang Double intValue

List of usage examples for java.lang Double intValue

Introduction

In this page you can find the example usage for java.lang Double intValue.

Prototype

public int intValue() 

Source Link

Document

Returns the value of this Double as an int after a narrowing primitive conversion.

Usage

From source file:org.openmrs.module.kenyaemr.fragment.controller.patient.CurrentVisitSummaryFragmentController.java

private SimpleObject getVisitVitals(List<Obs> obsList) {
    Double weight = null;//from  w  ww.ja  va  2s .  c  o  m
    Double height = null;
    Double temp = null;
    Double pulse = null;
    Double bp_systolic = null;
    Double bp_diastolic = null;
    Double resp_rate = null;
    Double oxygen_saturation = null;
    Double muac = null;
    String lmp = null;

    Map<String, Object> vitalsMap = new HashMap<String, Object>();
    for (Obs obs : obsList) {
        if (obs.getConcept().equals(WEIGHT)) {
            weight = obs.getValueNumeric();
            if (!vitalsMap.keySet().contains("weight")) {
                vitalsMap.put("weight", weight);
            }
        } else if (obs.getConcept().equals(HEIGHT)) {
            height = obs.getValueNumeric();
            if (!vitalsMap.keySet().contains("height")) {
                vitalsMap.put("height", height);
            }
        } else if (obs.getConcept().equals(TEMP)) {
            temp = obs.getValueNumeric();
            if (!vitalsMap.keySet().contains("temp")) {
                vitalsMap.put("temp", temp);
            }
        } else if (obs.getConcept().equals(PULSE_RATE)) {
            pulse = obs.getValueNumeric();
            if (!vitalsMap.keySet().contains("pulse")) {
                vitalsMap.put("pulse", pulse.intValue());
            }
        } else if (obs.getConcept().equals(BP_SYSTOLIC)) {
            bp_systolic = obs.getValueNumeric();
            if (!vitalsMap.keySet().contains("bp_systolic")) {
                vitalsMap.put("bp_systolic", bp_systolic.intValue());
            }
        } else if (obs.getConcept().equals(BP_DIASTOLIC)) {
            bp_diastolic = obs.getValueNumeric();
            if (!vitalsMap.keySet().contains("bp_diastolic")) {
                vitalsMap.put("bp_diastolic", bp_diastolic.intValue());
            }
        } else if (obs.getConcept().equals(RESPIRATORY_RATE)) {
            resp_rate = obs.getValueNumeric();
            if (!vitalsMap.keySet().contains("resp_rate")) {
                vitalsMap.put("resp_rate", resp_rate.intValue());
            }
        } else if (obs.getConcept().equals(OXYGEN_SATURATION)) {
            oxygen_saturation = obs.getValueNumeric();
            if (!vitalsMap.keySet().contains("oxygen_saturation")) {
                vitalsMap.put("oxygen_saturation", oxygen_saturation.intValue());
            }
        } else if (obs.getConcept().equals(MUAC)) {
            muac = obs.getValueNumeric();
            if (!vitalsMap.keySet().contains("muac")) {
                vitalsMap.put("muac", muac);
            }
        } else if (obs.getConcept().equals(LMP)) {
            lmp = DATE_FORMAT.format(obs.getValueDate());
            if (!vitalsMap.keySet().contains("lmp")) {
                vitalsMap.put("lmp", lmp);
            }
        }

    }

    if (bp_diastolic != null && bp_systolic != null)
        vitalsMap.put("bp",
                new StringBuilder().append(bp_systolic.intValue()).append("/").append(bp_diastolic.intValue()));

    return SimpleObject.create("weight",
            vitalsMap.get("weight") != null ? new StringBuilder().append(vitalsMap.get("weight")).append(" Kg")
                    : "",
            "height",
            vitalsMap.get("height") != null ? new StringBuilder().append(vitalsMap.get("height")).append(" cm")
                    : "",
            "temperature",
            vitalsMap.get("temp") != null ? new StringBuilder().append(vitalsMap.get("temp")) : "", "pulse",
            vitalsMap.get("pulse") != null ? new StringBuilder().append(vitalsMap.get("pulse")).append(" ")
                    : "",
            "bp",
            vitalsMap.get("bp") != null ? new StringBuilder().append(vitalsMap.get("bp")).append(" mmHg") : "",
            "resp_rate",
            vitalsMap.get("resp_rate") != null
                    ? new StringBuilder().append(vitalsMap.get("resp_rate")).append(" ")
                    : "",
            "oxygen_saturation",
            vitalsMap.get("oxygen_saturation") != null
                    ? new StringBuilder().append(vitalsMap.get("oxygen_saturation")).append(" ")
                    : "",
            "muac",
            vitalsMap.get("muac") != null ? new StringBuilder().append(vitalsMap.get("muac")).append(" ") : "",
            "lmp", vitalsMap.get("lmp") != null ? new StringBuilder().append(vitalsMap.get("lmp")) : "");
}

From source file:com.nkapps.billing.services.NumberServiceImpl.java

@Override
public String convertToText(Double number) {
    if (number == 0) {
        return "00";
    }//w w w  .j a v  a  2 s  . c  om

    String mask = "000000000000";
    DecimalFormat df = new DecimalFormat(mask);
    String snumber = df.format(number.longValue());

    int billions = Integer.parseInt(snumber.substring(0, 3));
    int millions = Integer.parseInt(snumber.substring(3, 6));
    int hundredThousands = Integer.parseInt(snumber.substring(6, 9));
    int thousands = Integer.parseInt(snumber.substring(9, 12));

    String tradBillions;
    switch (billions) {
    case 0:
        tradBillions = "";
        break;
    default:
        tradBillions = convertLessThanOneThousand(billions) + "  ";
    }
    String result = tradBillions;

    String tradMillions;
    switch (millions) {
    case 0:
        tradMillions = "";
        break;
    default:
        tradMillions = convertLessThanOneThousand(millions) + "  ";
    }
    result = result + tradMillions;

    String tradHundredThousands;
    switch (hundredThousands) {
    case 0:
        tradHundredThousands = "";
        break;
    case 1:
        tradHundredThousands = "?? ";
        break;
    default:
        tradHundredThousands = convertLessThanOneThousand(hundredThousands) + " ??";
    }
    result = result + tradHundredThousands;

    String tradThousand;
    tradThousand = convertLessThanOneThousand(thousands);
    result = result + tradThousand;
    Double tiyin = number - number.intValue();
    // remove extra spaces!
    return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ") + " ? "
            + (tiyin.equals(0) ? "00" : Double.valueOf(tiyin * 100).intValue()) + " ";
}

From source file:UI.MainStageController.java

/**
 * Bind graph setting controls to MyGraphView instance.
 *
 * @param graphView instance to which controls are bound
 *//*from w w  w  .j ava  2s .  c om*/
public void bindGraphSettings(MyGraphView graphView) {
    // Bind Node Radius Slider to all Nodes in Graph
    for (Node node : graphView.getMyVertexViewGroup().getChildren()) {
        ((MyVertexView) node).getRadiusProperty().bind(sliderNodeRadius.valueProperty());
    }
    // Bind Edge Width Slider to all Edges in Graph
    for (Node node : graphView.getMyEdgeViewGroup().getChildren()) {
        ((MyEdgeView) node).getWidthProperty().bind(sliderEdgeWidth.valueProperty()
                .multiply(Math.abs(((MyEdgeView) node).getMyEdge().getCorrelation()) + 0.1));
    }

    /**buttonPauseAnimation.setOnAction(e -> {
     boolean isRunning = graphView.animationService.isRunning();
     if (isRunning) graphView.animationService.cancel();
     if (!isRunning) graphView.animationService.restart();
     }); **/

    sliderEdgeLength.lowValueProperty().addListener((o, e, n) -> {
        graphView.animationService.setEdgeLengthLow(n.doubleValue());
    });

    sliderEdgeLength.highValueProperty().addListener((o, e, n) -> {
        graphView.animationService.setEdgeLengthHigh(n.doubleValue());
    });

    sliderNodeRepulsion.valueProperty().addListener((o, e, n) -> {
        graphView.animationService.setNodeRepulsion(n.intValue());
    });

    sliderStretchParameter.valueProperty().addListener((o, e, n) -> {
        graphView.animationService.setStretchForce(n.doubleValue());
    });

    sliderEdgeForce.valueProperty().addListener((o, e, n) -> {
        graphView.animationService.setForce(n.doubleValue());
    });

    sliderAnimationSpeed.valueProperty().addListener((o, e, n) -> {
        Double fr = sliderAnimationSpeed.getMax() - n.doubleValue();
        graphView.animationService.setFrameRate(fr.intValue());
    });

    buttonPauseAnimation.selectedProperty().bindBidirectional(graphView.pausedProperty);

}

From source file:com.aurel.track.exchange.excel.ExcelImportBL.java

/**
 * Gets the Integer value of a cell/*from  w  ww  . j  av  a 2 s.c om*/
 * 
 * @param cell
 * @return
 */
private static Integer getIntegerCellValue(Cell cell) throws ExcelImportInvalidCellValueException {
    Integer integerValue = null;
    int cellType = cell.getCellType();
    if (cellType == Cell.CELL_TYPE_NUMERIC) {
        Double doubleValue = null;
        try {
            double numericValue = cell.getNumericCellValue();
            doubleValue = new Double(numericValue);
            integerValue = new Integer(doubleValue.intValue());
        } catch (Exception e) {
            if (doubleValue == null) {
                doubleValue = new Double(Double.NaN);
            }
            throw new ExcelImportInvalidCellValueException(doubleValue.toString());
        }
    } else {
        if (cellType == Cell.CELL_TYPE_STRING) {
            RichTextString richTextString = null;
            richTextString = cell.getRichStringCellValue();
            if (richTextString != null) {
                String stringValue = richTextString.getString();
                if (stringValue != null && !"".equals(stringValue)) {
                    stringValue = stringValue.trim();
                    if (stringValue != null) {
                        try {
                            integerValue = Integer.valueOf(stringValue);
                        } catch (Exception e) {
                            throw new ExcelImportInvalidCellValueException(stringValue);
                        }
                    }
                }
            }
        } else {
            throw new ExcelImportInvalidCellValueException(getStringCellValue(cell));
        }
    }
    return integerValue;
}

From source file:ch.epfl.scapetoad.CartogramGastner.java

public boolean newt2(double h, double[] ptappr, double xguess, double yguess, int j, int k) {

    double deltax, deltay, dfxdx, dfxdy, dfydx, dfydy, fx, fy;
    int gaussx, gaussxplus, gaussy, gaussyplus, i;
    double temp;// w ww.  j  a  v  a 2  s  . c o m
    Double tempobj = null;

    ptappr[0] = xguess;
    ptappr[1] = yguess;

    for (i = 1; i <= IMAX; i++) {
        temp = this.interpolateBilinear(this.gridvx, ptappr[0], ptappr[1]);

        fx = ptappr[0] - (0.5 * h * temp) - this.x[j][k] - (0.5 * h * this.vx[j][k]);

        temp = this.interpolateBilinear(this.gridvy, ptappr[0], ptappr[1]);

        fy = ptappr[1] - (0.5 * h * temp) - this.y[j][k] - (0.5 * h * this.vy[j][k]);

        tempobj = new Double(ptappr[0]);
        gaussx = tempobj.intValue();
        tempobj = new Double(ptappr[1]);
        gaussy = tempobj.intValue();

        if (gaussx == this.lx)
            gaussxplus = 0;
        else
            gaussxplus = gaussx + 1;

        if (gaussy == this.ly)
            gaussyplus = 0;
        else
            gaussyplus = gaussy + 1;

        deltax = this.x[j][k] - gaussx;
        deltay = this.y[j][k] - gaussy;

        dfxdx = 1 - 0.5 * h * ((1 - deltay) * (this.gridvx[gaussxplus][gaussy] - this.gridvx[gaussx][gaussy])
                + deltay * (this.gridvx[gaussxplus][gaussyplus] - this.gridvx[gaussx][gaussyplus]));

        dfxdy = -0.5 * h * ((1 - deltax) * (this.gridvx[gaussx][gaussyplus] - this.gridvx[gaussx][gaussy])
                + deltax * (this.gridvx[gaussxplus][gaussyplus] - this.gridvx[gaussxplus][gaussy]));

        dfydx = -0.5 * h * ((1 - deltay) * (this.gridvy[gaussxplus][gaussy] - this.gridvy[gaussx][gaussy])
                + deltay * (this.gridvy[gaussxplus][gaussyplus] - this.gridvy[gaussx][gaussyplus]));

        dfydy = 1 - 0.5 * h * ((1 - deltax) * (this.gridvy[gaussx][gaussyplus] - this.gridvy[gaussx][gaussy])
                + deltax * (this.gridvy[gaussxplus][gaussyplus] - this.gridvy[gaussxplus][gaussy]));

        if ((fx * fx + fy * fy) < this.TOLF)
            return true;

        deltax = (fy * dfxdy - fx * dfydy) / (dfxdx * dfydy - dfxdy * dfydx);
        deltay = (fx * dfydx - fy * dfxdx) / (dfxdx * dfydy - dfxdy * dfydx);

        if ((deltax * deltax + deltay * deltay) < this.TOLX)
            return true;

        ptappr[0] += deltax;
        ptappr[1] += deltay;

    }

    return false;

}

From source file:org.plos.crepo.integration.ContentRepoTest.java

public void creationAndContentTest() throws IOException {
    File file = null;//w  w w. j a v a 2 s.  c  o  m
    try {
        file = new File("testFile.txt");
        BufferedWriter output = new BufferedWriter(new FileWriter(file));
        output.write(testData1);
        output.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // create object 1
    RepoObjectInput repoObjectInput = RepoObjectInput.builder(BUCKET_NAME, repoObjKey3)
            .setCreationDate(creationDateTime).setFileContent(file).setDownloadName("dowloadNameTest5").build();

    Map<String, Object> repoObj1 = contentRepoService.createRepoObject(repoObjectInput).getMapView();
    assertNotNull(repoObj1);
    String fileUuid = (String) repoObj1.get("uuid");
    Double versionNumber = (Double) repoObj1.get("versionNumber");

    InputStream content1 = contentRepoService.getLatestRepoObject(RepoId.create(BUCKET_NAME, repoObjKey3));
    assertNotNull(content1);

    // version object 1 ---> object 2
    RepoObjectInput repoObjectInput2 = RepoObjectInput.builder(BUCKET_NAME, repoObjKey3).setFileContent(file)
            .setDownloadName("dowloadNameTest6").build();

    Map<String, Object> repoObj2 = contentRepoService.versionRepoObject(repoObjectInput2).getMapView();
    assertNotNull(repoObj2);
    String fileUuid2 = (String) repoObj2.get("uuid");
    Double versionNumber2 = (Double) repoObj2.get("versionNumber");

    InputStream content2 = contentRepoService
            .getRepoObject(RepoVersion.create(BUCKET_NAME, repoObjKey3, fileUuid));
    assertNotNull(content2);

    InputStream content3 = contentRepoService
            .getRepoObject(RepoVersionNumber.create(BUCKET_NAME, repoObjKey3, versionNumber.intValue()));
    assertNotNull(content3);

    String fileContent1 = IOUtils.toString(content1, CharEncoding.UTF_8);
    String fileContent2 = IOUtils.toString(content2, CharEncoding.UTF_8);
    String fileContent3 = IOUtils.toString(content3, CharEncoding.UTF_8);

    assertEquals(testData1, fileContent1);
    assertEquals(fileContent1, fileContent2);
    assertEquals(fileContent3, fileContent2);

    byte[] content4 = ByteStreams
            .toByteArray(contentRepoService.getLatestRepoObject(RepoId.create(BUCKET_NAME, repoObjKey3)));
    byte[] content5 = ByteStreams.toByteArray(
            contentRepoService.getRepoObject(RepoVersion.create(BUCKET_NAME, repoObjKey3, fileUuid2)));
    byte[] content6 = ByteStreams.toByteArray(contentRepoService
            .getRepoObject(RepoVersionNumber.create(BUCKET_NAME, repoObjKey3, versionNumber2.intValue())));

    assertNotNull(content4);
    assertNotNull(content5);
    assertNotNull(content6);

    String fileContent4 = new String(content4);
    String fileContent5 = new String(content5);
    String fileContent6 = new String(content6);

    assertEquals(fileContent4, fileContent1);
    assertEquals(fileContent4, fileContent5);
    assertEquals(fileContent4, fileContent6);

    boolean deleted = contentRepoService
            .deleteRepoObject(RepoVersion.create(BUCKET_NAME, repoObjKey3, fileUuid));
    assertTrue(deleted);
    deleted = contentRepoService.deleteRepoObject(RepoVersion.create(BUCKET_NAME, repoObjKey3, fileUuid2));
    assertTrue(deleted);

}

From source file:org.plos.crepo.integration.ContentRepoTest.java

public void collectionsTest() {

    byte[] content1 = testData1.getBytes();
    // create object 1
    RepoObjectInput repoObjectInput1 = RepoObjectInput.builder(BUCKET_NAME, repoObjKey4)
            .setByteContent(content1).setDownloadName("dowloadNameTest").setContentType("test/plain").build();

    Map<String, Object> repoObj1 = contentRepoService.createRepoObject(repoObjectInput1).getMapView();
    assertNotNull(repoObj1);//  w ww .  j a  v a2  s .  c om
    String fileUuid1 = (String) repoObj1.get("uuid");

    byte[] content2 = testData2.getBytes();
    // create object 1
    RepoObjectInput repoObjectInput2 = RepoObjectInput.builder(BUCKET_NAME, repoObjKey5)
            .setByteContent(content2).setDownloadName("dowloadNameTest7").setContentType("test/plain").build();

    Map<String, Object> repoObj2 = contentRepoService.createRepoObject(repoObjectInput2).getMapView();
    assertNotNull(repoObj2);
    String fileUuid2 = (String) repoObj2.get("uuid");

    List<RepoVersion> repoObjs = new ArrayList<RepoVersion>();
    RepoVersion rpa1 = RepoVersion.create(BUCKET_NAME, repoObjKey4, fileUuid1);
    repoObjs.add(rpa1);
    RepoVersion rpa2 = RepoVersion.create(BUCKET_NAME, repoObjKey5, fileUuid2);
    repoObjs.add(rpa2);

    RepoCollectionInput repoCollMeta1 = RepoCollectionInput.builder(BUCKET_NAME, collectionKey1)
            .setObjects(repoObjs).setCreationDateTime(new Timestamp(new Date().getTime()).toString()).build();
    Map<String, Object> collection1 = contentRepoService.createCollection(repoCollMeta1).getMapView();
    assertNotNull(collection1);
    String collUuid1 = (String) collection1.get("uuid");
    Double collVersionNumber1 = (Double) collection1.get("versionNumber");

    repoObjs.remove(1);
    Map<String, Object> collection2 = contentRepoService.versionCollection(repoCollMeta1).getMapView();
    assertNotNull(collection2);
    String collUuid2 = (String) collection2.get("uuid");
    Double collVersionNumber2 = (Double) collection2.get("versionNumber");

    List<Map<String, Object>> versions = asRawList(
            contentRepoService.getCollectionVersions(RepoId.create(BUCKET_NAME, collectionKey1)));
    assertNotNull(versions);
    assertEquals(2, versions.size());
    assertEquals(collUuid1, versions.get(0).get("uuid"));
    assertEquals(collUuid2, versions.get(1).get("uuid"));

    Map<String, Object> collection3 = contentRepoService
            .getCollection(RepoVersion.create(BUCKET_NAME, collectionKey1, collUuid1)).getMapView();
    Map<String, Object> collection4 = contentRepoService
            .getCollection(RepoVersionNumber.create(BUCKET_NAME, collectionKey1, collVersionNumber1.intValue()))
            .getMapView();

    assertNotNull(collection3);
    assertNotNull(collection4);
    assertEquals(collUuid1, collection3.get("uuid"));
    assertEquals(collection3, collection4);

    boolean deleted = contentRepoService
            .deleteCollection(RepoVersion.create(BUCKET_NAME, collectionKey1, collUuid2));
    assertTrue(deleted);

    Map<String, Object> collection5 = null;
    try {
        // get object 2 by version UUID ----> must be null
        collection5 = contentRepoService
                .getCollection(
                        RepoVersionNumber.create(BUCKET_NAME, collectionKey1, collVersionNumber2.intValue()))
                .getMapView();
        fail(EXCEPTION_EXPECTED);
    } catch (ContentRepoException fe) {
        assertNull(collection5);
        assertEquals(fe.getErrorType(), ErrorType.ErrorFetchingCollection);
        assertTrue(fe.getMessage().contains("not found"));
    }

    deleted = contentRepoService.deleteCollection(
            RepoVersionNumber.create(BUCKET_NAME, collectionKey1, collVersionNumber1.intValue()));
    assertTrue(deleted);

    Map<String, Object> collection6 = null;
    try {
        // get object 2 by version UUID ----> must be null
        collection6 = contentRepoService
                .getCollection(RepoVersion.create(BUCKET_NAME, collectionKey1, collUuid1)).getMapView();
        fail(EXCEPTION_EXPECTED);
    } catch (ContentRepoException fe) {
        assertNull(collection6);
        assertEquals(fe.getErrorType(), ErrorType.ErrorFetchingCollection);
        assertTrue(fe.getMessage().contains("not found"));
    }

    contentRepoService.deleteRepoObject(RepoVersion.create(BUCKET_NAME, repoObjKey4, fileUuid1));
    contentRepoService.deleteRepoObject(RepoVersion.create(BUCKET_NAME, repoObjKey5, fileUuid2));

}

From source file:org.tinymediamanager.core.entities.MediaFile.java

License:asdf

/**
 * Gathers the media information via the native mediainfo lib.
 * //from w  ww.  j av a2 s . co  m
 * @param force
 *          forces the execution, will not stop on already imported files
 */
public void gatherMediaInformation(boolean force) {
    // check for supported filetype
    if (!isValidMediainfoFormat()) {
        // okay, we have no valid MI file, be sure it will not be triggered any more
        if (StringUtils.isBlank(getContainerFormat())) {
            setContainerFormat(getExtension());
        }
        return;
    }

    // mediainfo already gathered
    if (!force && !getContainerFormat().isEmpty()) {
        return;
    }

    // gather subtitle infos independent of MI
    if (getType() == MediaFileType.SUBTITLE) {
        gatherSubtitleInformation();
    }

    // file size and last modified
    try {
        BasicFileAttributes attrs = Files.readAttributes(getFileAsPath(), BasicFileAttributes.class);
        filedate = attrs.lastModifiedTime().toMillis();
        setFilesize(attrs.size());
    } catch (IOException e) {
        if (miSnapshot == null) { // maybe we set it already (from ISO) so only display message when empty
            LOGGER.warn("could not get file information (size/date): " + e.getMessage());
        }
        // do not set/return here - we might have set it already... and the next check does check for a 0-byte file
        // setContainerFormat(getExtension());
        // return;
    }

    // do not work further on 0 byte files
    if (getFilesize() == 0) {
        LOGGER.warn("0 Byte file detected: " + this.filename);
        // set container format to do not trigger it again
        setContainerFormat(getExtension());
        return;
    }

    // do not work further on subtitles/NFO files
    if (type == MediaFileType.SUBTITLE || type == MediaFileType.NFO) {
        // set container format to do not trigger it again
        setContainerFormat(getExtension());
        return;
    }

    // get media info
    LOGGER.debug("start MediaInfo for " + this.getFileAsPath());
    long discFilesSizes = 0L;
    if (isISO) {
        discFilesSizes = getMediaInfoSnapshotFromISO();
    } else {
        getMediaInfoSnapshot();
    }

    if (miSnapshot == null) {
        // MI could not be opened
        LOGGER.error("error getting MediaInfo for " + this.filename);
        // set container format to do not trigger it again
        setContainerFormat(getExtension());
        closeMediaInfo();
        return;
    }
    LOGGER.trace("got MI");

    String height = "";
    String scanType = "";
    String width = "";
    String videoCodec = "";

    switch (type) {
    case VIDEO:
    case VIDEO_EXTRA:
    case SAMPLE:
    case TRAILER:
        height = getMediaInfo(StreamKind.Video, 0, "Height");
        scanType = getMediaInfo(StreamKind.Video, 0, "ScanType");
        width = getMediaInfo(StreamKind.Video, 0, "Width");
        videoCodec = getMediaInfo(StreamKind.Video, 0, "CodecID/Hint", "Format");

        // fix for Microsoft VC-1
        if (StringUtils.containsIgnoreCase(videoCodec, "Microsoft")) {
            videoCodec = getMediaInfo(StreamKind.Video, 0, "Format");
        }

        // *****************
        // get audio streams
        // *****************
        // int streams = getMediaInfo().streamCount(StreamKind.Audio);
        int streams = 0;
        if (streams == 0) {
            // fallback 1
            String cnt = getMediaInfo(StreamKind.General, 0, "AudioCount");
            try {
                streams = Integer.parseInt(cnt);
            } catch (Exception e) {
                streams = 0;
            }
        }
        if (streams == 0) {
            // fallback 2
            String cnt = getMediaInfo(StreamKind.Audio, 0, "StreamCount");
            try {
                streams = Integer.parseInt(cnt);
            } catch (Exception e) {
                streams = 0;
            }
        }
        audioStreams.clear();
        for (int i = 0; i < streams; i++) {
            MediaFileAudioStream stream = new MediaFileAudioStream();
            String audioCodec = getMediaInfo(StreamKind.Audio, i, "CodecID/Hint", "Format");
            audioCodec = audioCodec.replaceAll("\\p{Punct}", "");

            String audioAddition = getMediaInfo(StreamKind.Audio, i, "Format_Profile");
            if ("dts".equalsIgnoreCase(audioCodec) && StringUtils.isNotBlank(audioAddition)) {
                if (audioAddition.contains("ES")) {
                    audioCodec = "DTSHD-ES";
                }
                if (audioAddition.contains("HRA")) {
                    audioCodec = "DTSHD-HRA";
                }
                if (audioAddition.contains("MA")) {
                    audioCodec = "DTSHD-MA";
                }
            }
            stream.setCodec(audioCodec);

            // AAC sometimes codes channels into Channel(s)_Original
            String channels = getMediaInfo(StreamKind.Audio, i, "Channel(s)_Original", "Channel(s)");
            stream.setChannels(StringUtils.isEmpty(channels) ? "" : channels + "ch");
            try {
                String br = getMediaInfo(StreamKind.Audio, i, "BitRate");
                stream.setBitrate(Integer.parseInt(br) / 1024);
            } catch (Exception ignored) {
            }
            String language = getMediaInfo(StreamKind.Audio, i, "Language/String", "Language");
            if (language.isEmpty()) {
                if (!isDiscFile()) { // video_ts parsed 'ts' as Tsonga
                    // try to parse from filename
                    String shortname = getBasename().toLowerCase(Locale.ROOT);
                    stream.setLanguage(parseLanguageFromString(shortname));
                }
            } else {
                stream.setLanguage(parseLanguageFromString(language));
            }
            audioStreams.add(stream);
        }

        // ********************
        // get subtitle streams
        // ********************
        // streams = getMediaInfo().streamCount(StreamKind.Text);
        streams = 0;
        if (streams == 0) {
            // fallback 1
            String cnt = getMediaInfo(StreamKind.General, 0, "TextCount");
            try {
                streams = Integer.parseInt(cnt);
            } catch (Exception e) {
                streams = 0;
            }
        }
        if (streams == 0) {
            // fallback 2
            String cnt = getMediaInfo(StreamKind.Text, 0, "StreamCount");
            try {
                streams = Integer.parseInt(cnt);
            } catch (Exception e) {
                streams = 0;
            }
        }

        subtitles.clear();
        for (int i = 0; i < streams; i++) {
            MediaFileSubtitle stream = new MediaFileSubtitle();

            String codec = getMediaInfo(StreamKind.Text, i, "CodecID/Hint", "Format");
            stream.setCodec(codec.replaceAll("\\p{Punct}", ""));
            String lang = getMediaInfo(StreamKind.Text, i, "Language/String", "Language");
            stream.setLanguage(parseLanguageFromString(lang));

            String forced = getMediaInfo(StreamKind.Text, i, "Forced");
            boolean b = forced.equalsIgnoreCase("true") || forced.equalsIgnoreCase("yes");
            stream.setForced(b);

            subtitles.add(stream);
        }

        // detect 3D video (mainly from MKV files)
        // sample Mediainfo output:
        // MultiView_Count : 2
        // MultiView_Layout : Top-Bottom (left eye first)
        // MultiView_Layout : Side by Side (left eye first)
        String mvc = getMediaInfo(StreamKind.Video, 0, "MultiView_Count");
        if (!StringUtils.isEmpty(mvc) && mvc.equals("2")) {
            video3DFormat = VIDEO_3D;
            String mvl = getMediaInfo(StreamKind.Video, 0, "MultiView_Layout").toLowerCase(Locale.ROOT);
            LOGGER.debug("3D detected :) " + mvl);
            if (!StringUtils.isEmpty(mvl) && mvl.contains("top") && mvl.contains("bottom")) {
                video3DFormat = VIDEO_3D_TAB;
            }
            if (!StringUtils.isEmpty(mvl) && mvl.contains("side")) {
                video3DFormat = VIDEO_3D_SBS;
            }
        }

        break;

    case AUDIO:
        MediaFileAudioStream stream = new MediaFileAudioStream();
        String audioCodec = getMediaInfo(StreamKind.Audio, 0, "CodecID/Hint", "Format");
        stream.setCodec(audioCodec.replaceAll("\\p{Punct}", ""));
        String channels = getMediaInfo(StreamKind.Audio, 0, "Channel(s)");
        stream.setChannels(StringUtils.isEmpty(channels) ? "" : channels + "ch");
        try {
            String br = getMediaInfo(StreamKind.Audio, 0, "BitRate");
            stream.setBitrate(Integer.parseInt(br) / 1024);
        } catch (Exception e) {
        }
        String language = getMediaInfo(StreamKind.Audio, 0, "Language/String", "Language");
        if (language.isEmpty()) {
            // try to parse from filename
            String shortname = getBasename().toLowerCase(Locale.ROOT);
            stream.setLanguage(parseLanguageFromString(shortname));
        } else {
            stream.setLanguage(parseLanguageFromString(language));
        }
        audioStreams.clear();
        audioStreams.add(stream);
        break;

    case POSTER:
    case BANNER:
    case FANART:
    case THUMB:
    case EXTRAFANART:
    case GRAPHIC:
    case SEASON_POSTER:
    case LOGO:
    case CLEARLOGO:
    case CLEARART:
    case DISCART:
    case EXTRATHUMB:
        height = getMediaInfo(StreamKind.Image, 0, "Height");
        // scanType = getMediaInfo(StreamKind.Image, 0, "ScanType"); // no scantype on graphics
        width = getMediaInfo(StreamKind.Image, 0, "Width");
        videoCodec = getMediaInfo(StreamKind.Image, 0, "CodecID/Hint", "Format");
        // System.out.println(height + "-" + width + "-" + videoCodec);
        break;

    case NFO: // do nothing here, but do not display default warning (since we got the filedate)
        break;

    default:
        LOGGER.warn("no mediainformation handling for MediaFile type " + getType() + " yet.");
        break;
    }

    // video codec
    // e.g. XviD, x264, DivX 5, MPEG-4 Visual, AVC, etc.
    // get first token (e.g. DivX 5 => DivX)
    setVideoCodec(StringUtils.isEmpty(videoCodec) ? "" : new Scanner(videoCodec).next());

    // container format for all except subtitles (subtitle container format is handled another way)
    if (type == MediaFileType.SUBTITLE) {
        setContainerFormat(getExtension());
    } else {
        String extensions = getMediaInfo(StreamKind.General, 0, "Codec/Extensions", "Format");
        // get first extension
        setContainerFormat(
                StringUtils.isBlank(extensions) ? "" : new Scanner(extensions).next().toLowerCase(Locale.ROOT));

        // if container format is still empty -> insert the extension
        if (StringUtils.isBlank(containerFormat)) {
            setContainerFormat(getExtension());
        }
    }

    if (height.isEmpty() || scanType.isEmpty()) {
        setExactVideoFormat("");
    } else {
        setExactVideoFormat(height + Character.toLowerCase(scanType.charAt(0)));
    }

    // video dimension
    if (!width.isEmpty()) {
        try {
            setVideoWidth(Integer.parseInt(width));
        } catch (NumberFormatException e) {
            setVideoWidth(0);
        }
    }
    if (!height.isEmpty()) {
        try {
            setVideoHeight(Integer.parseInt(height));
        } catch (NumberFormatException e) {
            setVideoHeight(0);
        }
    }

    switch (type) {
    case VIDEO:
    case VIDEO_EXTRA:
    case SAMPLE:
    case TRAILER:
    case AUDIO:
        // overall bitrate (OverallBitRate/String)
        String br = getMediaInfo(StreamKind.General, 0, "OverallBitRate");
        if (!br.isEmpty()) {
            try {
                setOverallBitRate(Integer.parseInt(br) / 1024); // in kbps
            } catch (NumberFormatException e) {
                setOverallBitRate(0);
            }
        }

        // Duration;Play time of the stream in ms
        // Duration/String;Play time in format : XXx YYy only, YYy omited if zero
        // Duration/String1;Play time in format : HHh MMmn SSs MMMms, XX om.if.z.
        // Duration/String2;Play time in format : XXx YYy only, YYy omited if zero
        // Duration/String3;Play time in format : HH:MM:SS.MMM
        if (!isISO) {
            // ISO files get duration accumulated with snapshot
            String dur = getMediaInfo(StreamKind.General, 0, "Duration");
            if (!dur.isEmpty()) {
                try {
                    Double d = Double.parseDouble(dur);
                    setDuration(d.intValue() / 1000);
                } catch (NumberFormatException e) {
                    setDuration(0);
                }
            }
        } else {
            // do some sanity check, to see, if we have an invalid DVD structure
            // eg when the sum(filesize) way higher than ISO size
            LOGGER.trace("ISO size:" + filesize + "  dataSize:" + discFilesSizes + "  = diff:"
                    + Math.abs(discFilesSizes - filesize));
            if (discFilesSizes > 0 && filesize > 0) {
                long gig = 1024 * 1024 * 1024;
                if (Math.abs(discFilesSizes - filesize) > gig) {
                    LOGGER.error("ISO file seems to have an invalid structure - ignore duration");
                    // we set the ISO duration to zero,
                    // so the standard getDuration() will always get the scraped duration
                    setDuration(0);
                }
            }
        }
    default:
        break;
    }

    LOGGER.trace("extracted MI");
    // close mediainfo lib
    closeMediaInfo();
    LOGGER.trace("closed MI");
}

From source file:ubic.gemma.web.controller.expression.experiment.DEDVController.java

/**
 * Handle case of text export of the results.
 *///from  w  ww  .j  a v  a  2  s . co m
@RequestMapping("/downloadDEDV.html")
protected ModelAndView handleRequestInternal(HttpServletRequest request) {

    StopWatch watch = new StopWatch();
    watch.start();

    Collection<Long> geneIds = ControllerUtils.extractIds(request.getParameter("g")); // might not be any
    Collection<Long> eeIds = ControllerUtils.extractIds(request.getParameter("ee")); // might not be there

    ModelAndView mav = new ModelAndView(new TextView());
    if (eeIds == null || eeIds.isEmpty()) {
        mav.addObject("text", "Input empty for finding DEDVs: " + geneIds + " and " + eeIds);
        return mav;
    }

    String threshSt = request.getParameter("thresh");
    String resultSetIdSt = request.getParameter("rs");

    Double thresh = 100.0;
    if (StringUtils.isNotBlank(threshSt)) {
        try {
            thresh = Double.parseDouble(threshSt);
        } catch (NumberFormatException e) {
            throw new RuntimeException("Threshold was not a valid value: " + threshSt);
        }
    }

    Map<ExpressionExperimentValueObject, Map<Long, Collection<DoubleVectorValueObject>>> result;

    if (request.getParameter("pca") != null) {
        int component = Integer.parseInt(request.getParameter("component"));
        Long eeId = eeIds.iterator().next();

        Map<ProbeLoading, DoubleVectorValueObject> topLoadedVectors = this.svdService.getTopLoadedVectors(eeId,
                component, thresh.intValue());

        if (topLoadedVectors == null)
            return null;

        mav.addObject("text", format4File(topLoadedVectors.values()));
        return mav;
    }

    /*
     * The following should be set if we're viewing diff. ex results.
     */

    Long resultSetId = null;
    if (StringUtils.isNumeric(resultSetIdSt)) {
        resultSetId = Long.parseLong(resultSetIdSt);
    }

    if (resultSetId != null) {

        /*
         * Diff ex case.
         */
        Long eeId = eeIds.iterator().next();

        Collection<DoubleVectorValueObject> diffExVectors = processedExpressionDataVectorService
                .getDiffExVectors(resultSetId, thresh, MAX_RESULTS_TO_RETURN);

        if (diffExVectors == null || diffExVectors.isEmpty()) {
            mav.addObject("text", "No results");
            return mav;
        }

        /*
         * Organize the vectors in the same way expected by the ee+gene type of request.
         */
        ExpressionExperimentValueObject ee = expressionExperimentService
                .loadValueObject(expressionExperimentService.load(eeId));

        result = new HashMap<>();
        Map<Long, Collection<DoubleVectorValueObject>> gmap = new HashMap<>();

        for (DoubleVectorValueObject dv : diffExVectors) {
            for (Long g : dv.getGenes()) {
                if (!gmap.containsKey(g)) {
                    gmap.put(g, new HashSet<DoubleVectorValueObject>());
                }
                gmap.get(g).add(dv);
            }
        }

        result.put(ee, gmap);

    } else {
        // Generic listing.
        result = getDEDV(eeIds, geneIds);
    }

    if (result == null || result.isEmpty()) {
        mav.addObject("text", "No results");
        return mav;
    }

    mav.addObject("text", format4File(result));
    watch.stop();
    Long time = watch.getTime();

    if (time > 100) {
        log.info("Retrieved and Formated" + result.keySet().size() + " DEDVs for eeIDs: " + eeIds
                + " and GeneIds: "

                + geneIds + " in : " + time + " ms.");
    }
    return mav;

}