Example usage for java.io RandomAccessFile close

List of usage examples for java.io RandomAccessFile close

Introduction

In this page you can find the example usage for java.io RandomAccessFile close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this random access file stream and releases any system resources associated with the stream.

Usage

From source file:org.apache.flume.channel.file.TestFlumeEventQueue.java

@Test(expected = BadCheckpointException.class)
public void testCorruptInflightTakes() throws Exception {
    RandomAccessFile inflight = null;
    try {/*  w  w  w. j a v a 2s . co  m*/
        queue = new FlumeEventQueue(backingStore, backingStoreSupplier.getInflightTakes(),
                backingStoreSupplier.getInflightPuts());
        long txnID1 = new Random().nextInt(Integer.MAX_VALUE - 1);
        long txnID2 = txnID1 + 1;
        queue.addWithoutCommit(new FlumeEventPointer(1, 1), txnID1);
        queue.addWithoutCommit(new FlumeEventPointer(2, 1), txnID1);
        queue.addWithoutCommit(new FlumeEventPointer(2, 2), txnID2);
        queue.checkpoint(true);
        TimeUnit.SECONDS.sleep(3L);
        inflight = new RandomAccessFile(backingStoreSupplier.getInflightTakes(), "rw");
        inflight.seek(0);
        inflight.writeInt(new Random().nextInt());
        queue = new FlumeEventQueue(backingStore, backingStoreSupplier.getInflightTakes(),
                backingStoreSupplier.getInflightPuts());
        SetMultimap<Long, Long> deserializedMap = queue.deserializeInflightTakes();
        Assert.assertTrue(deserializedMap.get(txnID1).contains(new FlumeEventPointer(1, 1).toLong()));
        Assert.assertTrue(deserializedMap.get(txnID1).contains(new FlumeEventPointer(2, 1).toLong()));
        Assert.assertTrue(deserializedMap.get(txnID2).contains(new FlumeEventPointer(2, 2).toLong()));
    } finally {
        inflight.close();
    }
}

From source file:com.android.volley.toolbox.DownloadNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        RandomAccessFile acessfile = null;
        File file = null;//from ww  w. j  a  v  a  2 s.  c  o  m
        try {
            if (!(request instanceof DownOrUpRequest)) {
                throw new IllegalArgumentException("request object mast be DownOrUpRequest???");
            }
            DownOrUpRequest requestDown = (DownOrUpRequest) request;
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            // Download have no cache
            file = getFile(requestDown);
            acessfile = new RandomAccessFile(file, "rws");

            long length = acessfile.length();
            acessfile.seek(length);
            if (length != 0) {
                headers.put("Range", "bytes=" + length + "-");//
            }
            httpResponse = mHttpStack.performRequest(requestDown, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, requestDown, responseContents, statusLine);

            if (statusCode < 200 || statusCode > 299) {
                acessfile.close();
                throw new IOException();
            }
            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity(), requestDown, acessfile);
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }
            acessfile.close();
            String re = null;
            if (!requestDown.isCanceled() || requestDown.getmMaxLength() == requestDown.getmCurLength()) {
                String path = file.getAbsolutePath();
                String re_name = ((DownOrUpRequest) request).getmDownloadName();
                if (re_name != null) {
                    re = path.substring(0, path.lastIndexOf('/')) + "/" + re_name;
                } else {
                    re = path.substring(0, path.lastIndexOf("."));
                }
                File rename = new File(re);
                boolean result = file.renameTo(rename);
                if (!result) {
                    Log.e(this.getClass().getName(),
                            "?????:"
                                    + rename);
                    throw new IOException(
                            "????????");
                }
                requestDown.setDownloadFile(rename);
            } else {
                re = file.getAbsolutePath();
                statusCode = 209;
            }
            return new NetworkResponse(statusCode, re.getBytes(), responseHeaders, false,
                    SystemClock.elapsedRealtime() - requestStart);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            if (acessfile != null) {
                try {
                    acessfile.close();
                    file.delete();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            throw new NetworkError(networkResponse);
        }
    }
}

From source file:org.apache.hadoop.mapreduce.task.reduce.InMemoryLinkMapOutput.java

@Override
public void shuffle(MapHost host, InputStream input, long compressedLength, long decompressedLength,
        ShuffleClientMetrics metrics, Reporter reporter) throws IOException {

    String mapHostName = host.getHostName().split(":")[0];
    String app_path = conf.get(MRConfig.LOCAL_DIR);
    LOG.debug("original app_path " + app_path);
    String[] app_path_parts = app_path.split("/");
    app_path_parts[app_path_parts.length - 5] = mapHostName;
    StringBuilder builder = new StringBuilder();
    for (String s : app_path_parts) {
        builder.append(s);//from  w w  w .  ja  va  2 s  .  c om
        builder.append("/");
    }
    app_path = builder.toString();
    String src = app_path + "output/" + getMapId() + "/file.out";

    File f = new File(src);
    if (f.exists()) {
        LOG.debug("shuffleToLink: the src " + src + " EXIST!");
    }

    //LOG.debug("src file size: "+f.length());

    //input = new FileInputStream(src);
    //input.skip(offset);

    RandomAccessFile raf = new RandomAccessFile(f, "r");
    input = Channels.newInputStream(raf.getChannel().position(offset));

    IFileInputStream checksumIn = new IFileInputStream(input, compressedLength, conf);

    input = checksumIn;

    // Are map-outputs compressed?
    if (codec != null) {
        decompressor.reset();
        input = codec.createInputStream(input, decompressor);
    }

    try {
        LOG.debug("offset: " + offset);
        LOG.debug("memory.length: " + memory.length);
        LOG.debug("compressedLength: " + compressedLength);
        LOG.debug("decompressedLength: " + decompressedLength);

        // TO-DO: would offset and length be OK to be int?
        IOUtils.readFully(input, memory, 0, memory.length);
        metrics.inputBytes((int) memory.length);
        reporter.progress();
        LOG.info("Read " + memory.length + " bytes from map-output for " + getMapId());

        /**
         * We've gotten the amount of data we were expecting. Verify the
         * decompressor has nothing more to offer. This action also forces
         * the decompressor to read any trailing bytes that weren't critical
         * for decompression, which is necessary to keep the stream in sync.
         */
        //if (input.read() >= 0) {
        //   throw new IOException(
        //         "Unexpected extra bytes from input stream for "
        //               + getMapId());
        //}
        input.close();
        raf.close();
    } catch (IOException ioe) {
        // Close the streams
        IOUtils.cleanup(LOG, input);

        // Re-throw
        throw ioe;
    } finally {
        CodecPool.returnDecompressor(decompressor);
    }
}

From source file:com.cloud.storage.template.HttpTemplateDownloader.java

@Override
public long download(boolean resume, DownloadCompleteCallback callback) {
    switch (status) {
    case ABORTED:
    case UNRECOVERABLE_ERROR:
    case DOWNLOAD_FINISHED:
        return 0;
    default:/*from   www. jav a 2  s  .c  o  m*/

    }
    int bytes = 0;
    File file = new File(toFile);
    try {

        long localFileSize = 0;
        if (file.exists() && resume) {
            localFileSize = file.length();
            s_logger.info("Resuming download to file (current size)=" + localFileSize);
        }

        Date start = new Date();

        int responseCode = 0;

        if (localFileSize > 0) {
            // require partial content support for resume
            request.addRequestHeader("Range", "bytes=" + localFileSize + "-");
            if (client.executeMethod(request) != HttpStatus.SC_PARTIAL_CONTENT) {
                errorString = "HTTP Server does not support partial get";
                status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
                return 0;
            }
        } else if ((responseCode = client.executeMethod(request)) != HttpStatus.SC_OK) {
            status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
            errorString = " HTTP Server returned " + responseCode + " (expected 200 OK) ";
            return 0; //FIXME: retry?
        }

        Header contentLengthHeader = request.getResponseHeader("Content-Length");
        boolean chunked = false;
        long remoteSize2 = 0;
        if (contentLengthHeader == null) {
            Header chunkedHeader = request.getResponseHeader("Transfer-Encoding");
            if (chunkedHeader == null || !"chunked".equalsIgnoreCase(chunkedHeader.getValue())) {
                status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
                errorString = " Failed to receive length of download ";
                return 0; //FIXME: what status do we put here? Do we retry?
            } else if ("chunked".equalsIgnoreCase(chunkedHeader.getValue())) {
                chunked = true;
            }
        } else {
            remoteSize2 = Long.parseLong(contentLengthHeader.getValue());
        }

        if (remoteSize == 0) {
            remoteSize = remoteSize2;
        }

        if (remoteSize > MAX_TEMPLATE_SIZE_IN_BYTES) {
            s_logger.info("Remote size is too large: " + remoteSize + " , max=" + MAX_TEMPLATE_SIZE_IN_BYTES);
            status = Status.UNRECOVERABLE_ERROR;
            errorString = "Download file size is too large";
            return 0;
        }

        if (remoteSize == 0) {
            remoteSize = MAX_TEMPLATE_SIZE_IN_BYTES;
        }

        InputStream in = !chunked ? new BufferedInputStream(request.getResponseBodyAsStream())
                : new ChunkedInputStream(request.getResponseBodyAsStream());

        RandomAccessFile out = new RandomAccessFile(file, "rwd");
        out.seek(localFileSize);

        s_logger.info("Starting download from " + getDownloadUrl() + " to " + toFile + " remoteSize="
                + remoteSize + " , max size=" + MAX_TEMPLATE_SIZE_IN_BYTES);

        byte[] block = new byte[CHUNK_SIZE];
        long offset = 0;
        boolean done = false;
        status = TemplateDownloader.Status.IN_PROGRESS;
        while (!done && status != Status.ABORTED && offset <= remoteSize) {
            if ((bytes = in.read(block, 0, CHUNK_SIZE)) > -1) {
                out.write(block, 0, bytes);
                offset += bytes;
                out.seek(offset);
                totalBytes += bytes;
            } else {
                done = true;
            }
        }
        Date finish = new Date();
        String downloaded = "(incomplete download)";
        if (totalBytes >= remoteSize) {
            status = TemplateDownloader.Status.DOWNLOAD_FINISHED;
            downloaded = "(download complete remote=" + remoteSize + "bytes)";
        }
        errorString = "Downloaded " + totalBytes + " bytes " + downloaded;
        downloadTime += finish.getTime() - start.getTime();
        out.close();

        return totalBytes;
    } catch (HttpException hte) {
        status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
        errorString = hte.getMessage();
    } catch (IOException ioe) {
        status = TemplateDownloader.Status.UNRECOVERABLE_ERROR; //probably a file write error?
        errorString = ioe.getMessage();
    } finally {
        if (status == Status.UNRECOVERABLE_ERROR && file.exists() && !file.isDirectory()) {
            file.delete();
        }
        request.releaseConnection();
        if (callback != null) {
            callback.downloadComplete(status);
        }
    }
    return 0;
}

From source file:com.mellanox.r4h.MiniDFSCluster.java

public static boolean corruptBlock(File blockFile) throws IOException {
    if (blockFile == null || !blockFile.exists()) {
        return false;
    }/*from   w  ww .  j  a v a  2 s  .c om*/
    // Corrupt replica by writing random bytes into replica
    Random random = new Random();
    RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
    FileChannel channel = raFile.getChannel();
    String badString = "BADBAD";
    int rand = random.nextInt((int) channel.size() / 2);
    raFile.seek(rand);
    raFile.write(badString.getBytes());
    raFile.close();
    LOG.warn("Corrupting the block " + blockFile);
    return true;
}

From source file:au.org.ala.layers.dao.ObjectDAOImpl.java

private HashMap<String, Object> getGridIndexEntry(String path, String objectId) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    RandomAccessFile raf = null;
    try {/* w  w w  . j  a v a 2 s  . c  o  m*/
        raf = new RandomAccessFile(path + ".wkt.index.dat", "r");

        int s2 = Integer.parseInt(objectId);

        // it is all in order, seek to the record
        int recordSize = 4 * 7; // 2 int + 5 float
        int start = raf.readInt();
        raf.seek(recordSize * (s2 - start));

        map.put("gn", raf.readInt());
        map.put("charoffset", raf.readInt());
        map.put("minx", raf.readFloat());
        map.put("miny", raf.readFloat());
        map.put("maxx", raf.readFloat());
        map.put("maxy", raf.readFloat());
        map.put("area", raf.readFloat());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            if (raf != null) {
                raf.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    return map;
}

From source file:org.ala.spatial.util.AnalysisJobMaxent.java

private String getMaxentError(File file, int count) {
    try {/*  w  w w.  j  ava 2 s  .  c  om*/
        RandomAccessFile rf = new RandomAccessFile(file, "r");

        // first check if maxent threw a 'No species selected' error
        String nosp = rf.readLine(); // first line: date/time
        nosp = rf.readLine(); // second line: maxent version
        nosp = rf.readLine(); // third line: "No species selected"
        if (nosp.equals("No species selected")) {
            return "No species selected";
        }

        long flen = file.length() - 1;
        int nlcnt = -1;
        StringBuilder lines = new StringBuilder();
        while (nlcnt != count) {
            rf.seek(flen--);
            char c = (char) rf.read();
            lines.append(c);
            if (c == '\n') {
                nlcnt++;
            }

        }
        String line = lines.reverse().toString();
        if (line.contains("Warning: Skipping species because it has 0 test samples")) {
            return "Warning: Skipping species because it has 0 test samples";
        }

        rf.close();
    } catch (Exception e) {
        System.out.println("Unable to read lines");
        e.printStackTrace(System.out);
    }

    // return false anyways
    return null;
}

From source file:edu.harvard.i2b2.adminTool.dataModel.PatientMappingFactory.java

public String createlld(int minPatientNum, int maxPatientNum, boolean bDisplayAll, boolean writeFile,
        boolean displayDemographics) {

    ArrayList conceptOrder = new ArrayList();
    int maxLineCount = 0; // zero turns off check for maximum count of lines
    StringBuilder resultFile = new StringBuilder();
    ArrayList<PatientDemographics> demographicsArray = new ArrayList<PatientDemographics>();

    try {//from w w  w  . j a  va  2s  .com
        // get the root
        Element root = null;// doc.getRootElement();
        // get the children from the i2b2 document
        java.util.List allChildren = root.getChildren();
        int iNumberOfChildren = allChildren.size();
        // set up the variables for the loop
        String sPatient_num = null;
        String sConcept_cd = null;
        String sOldPatient_num = "start";
        String sOldConcept_cd = null;
        String sStart_date = null;
        String sOldStart_date = null;
        String sEnd_date = null;
        String sInout_cd = null;
        String sDeath_date = null;
        String sColor = null;
        String sHeight = null;
        String sValue = null;
        String sTablename = null;
        int patientNum = 0;
        Date oDate;

        resultFile.append(GetTimelineHeader());
        boolean bOverMax = false;
        int conceptCount = 0;
        int patientCount = minPatientNum;
        StringBuilder patientRecord = new StringBuilder();

        String currentPatientNum = null;
        int indexPos = 0;

        for (int p = 0; p < demographicsArray.size(); p++) {
            PatientDemographics record = demographicsArray.get(p);
            currentPatientNum = record.patientNumber();

            if (displayDemographics) {
                patientRecord.append(getTimelinePatientString(currentPatientNum, record));
            } else {
                patientRecord.append(getTimelinePatientString(currentPatientNum));
            }

            resultFile.append(patientRecord.toString());
            patientRecord = new StringBuilder();
            patientCount++;

            conceptCount = 0;
            sOldConcept_cd = null;
            sOldStart_date = null;
            sOldPatient_num = "";

            if ((indexPos == iNumberOfChildren) && bDisplayAll) {
                conceptCount = 0;
                while ((conceptOrder != null) && (conceptCount < conceptOrder.size())) {
                    patientRecord.append(getTimelineConceptString((String) conceptOrder.get(conceptCount), 1));
                    patientRecord.append(getTimelineEmptyDateString());
                    conceptCount++;
                }

                resultFile.append(patientRecord.toString());
                patientRecord = new StringBuilder();
            }

            for (int i = indexPos; i < iNumberOfChildren; i++) {
                if ((maxLineCount > 0) && (i > maxLineCount)) {
                    bOverMax = true;
                    break;
                }

                Element oChild = (Element) allChildren.get(i);
                sPatient_num = "";// oChild.getChild(ss_patient_num).getText(
                // );

                if (!sPatient_num.equals(currentPatientNum) && (sOldPatient_num.equals("start")) /*
                                                                                                 * &&
                                                                                                 * !sOldPatient_num
                                                                                                 * .equals(
                                                                                                 * sPatient_num
                                                                                                 * )
                                                                                                 */) {
                    if (bDisplayAll) {
                        try {
                            patientNum = Integer.parseInt(sPatient_num);
                            conceptCount = 0;
                            while ((conceptOrder != null) && (conceptCount < conceptOrder.size())) {
                                patientRecord.append(
                                        getTimelineConceptString((String) conceptOrder.get(conceptCount), 1));
                                patientRecord.append(getTimelineEmptyDateString());
                                conceptCount++;
                            }

                            resultFile.append(patientRecord.toString());
                            patientRecord = new StringBuilder();
                            // patientCount++;
                        } catch (java.lang.OutOfMemoryError e) {
                            log.error("In resultset builder 5: " + e.getMessage());
                            // closeConnection(oConnection);
                            return "memory error";
                        } catch (Exception e) {
                            log.error(e.getMessage());
                            // closeConnection(oConnection);
                            return "error";
                        }

                        conceptCount = 0;
                        sOldConcept_cd = null;
                        sOldStart_date = null;
                    }
                    break;
                } else if (!sPatient_num.equals(currentPatientNum) && !(sOldPatient_num.equals("start")) /*
                                                                                                         * &&!
                                                                                                         * sOldPatient_num
                                                                                                         * .equals(
                                                                                                         * sPatient_num
                                                                                                         * )
                                                                                                         */) {
                    if ((bDisplayAll) && (conceptCount < (conceptOrder.size()))) {
                        while ((conceptOrder != null) && (conceptCount < conceptOrder.size())) {
                            patientRecord.append(
                                    getTimelineConceptString((String) conceptOrder.get(conceptCount), 1));
                            patientRecord.append(getTimelineEmptyDateString());
                            conceptCount++;
                        }
                    }

                    resultFile.append(patientRecord.toString());
                    patientRecord = new StringBuilder();
                    patientCount++;

                    conceptCount = 0;
                    sOldConcept_cd = null;
                    sOldStart_date = null;
                    break;
                } else if (sPatient_num.equals(currentPatientNum)) {
                    indexPos = i + 1;
                    sOldPatient_num = sPatient_num;
                    // if (bUseConcept) {
                    // sConcept_cd =
                    // oChild.getChild(ss_concept_cd).getText();
                    // }
                    // else {
                    // sConcept_cd =
                    // oChild.getAttributeValue(ss_q_name_char);
                    // }

                    if (!sConcept_cd.equals(sOldConcept_cd)) {
                        // conceptCount++;
                        if (bDisplayAll) {
                            for (int j = conceptCount; j < conceptOrder.size(); j++) {
                                if (sConcept_cd.equals(conceptOrder.get(j))) {
                                    break;
                                } else {
                                    patientRecord
                                            .append(getTimelineConceptString((String) conceptOrder.get(j), 1));
                                    patientRecord.append(getTimelineEmptyDateString());
                                    conceptCount++;
                                }
                            }
                        }

                        // int iNumConceptObservations =
                        // getNumConceptObservationsRollingupStartDate
                        // (allChildren,i);

                        // patientRecord.append(getTimelineConceptString(
                        // sConcept_cd,iNumConceptObservations));
                        conceptCount++;
                        sOldStart_date = null;
                    }

                    sOldConcept_cd = sConcept_cd;
                    // sStart_date =
                    // oChild.getChild(ss_start_date).getText();
                    // if (!sStart_date.equals(sOldStart_date)) {
                    // if (!sStart_date.equals(null)) {
                    if ((!sStart_date.equals(null))
                            && ((sOldStart_date == null) || (!sStart_date.equals(sOldStart_date)))) {
                        // sEnd_date =
                        // oChild.getChild(ss_end_date).getText();
                        if ((sEnd_date == null) || (sEnd_date.trim().length() == 0))
                            sEnd_date = sStart_date;
                        // sInout_cd =
                        // oChild.getChild(ss_inout_cd).getText();
                        sInout_cd = "";
                        // sColor = oChild.getChild(ss_color_cd).getText();
                        // sHeight =
                        // oChild.getChild(ss_height_cd).getText();
                        // sValue = oChild.getChild(ss_value_cd).getText();
                        // sTablename =
                        // oChild.getChild(ss_table_name).getText();
                        String prefix = "C";
                        if (sTablename.equalsIgnoreCase("visit_dimension")) {
                            prefix = "E";
                        } else if (sTablename.equalsIgnoreCase("provider_dimension")) {
                            prefix = "P";
                        }

                        // if ((sValue==null)||(sValue.length()==0)) {
                        // sValue = prefix+" = ::"+sConcept_cd+"::"+
                        // "$$"+oChild.getChild(ss_patient_num).getText()+
                        // "$$"+oChild.getChild(ss_concept_cd).getText() +
                        // "$$"+ChangeRsDateFull(sStart_date) ;//+"::";
                    } else {
                        // sValue = prefix+" Value = " +
                        // "::"+sConcept_cd+": "+sValue+"::"+
                        // "$$"+oChild.getChild(ss_patient_num).getText()+
                        // "$$"+oChild.getChild(ss_concept_cd).getText() +
                        // "$$"+ChangeRsDateFull(sStart_date) ;//+"::";
                    }

                    // log.debug("   "+ ChangeRsDate(sStart_date) + " -> " +
                    // ChangeRsDate(sEnd_date));
                    // System.out.print(getTimelineDateString(ChangeRsDate(
                    // sStart_date),ChangeRsDate(sEnd_date)));
                    // System.out.print(getTimelineDateString(ChangeRsDate(
                    // sStart_date),ChangeRsDate(sEnd_date),sConcept_cd));
                    if (sInout_cd.equalsIgnoreCase("I")) {
                        if (sColor != null)
                            patientRecord.append(getTimelineDateStringSpecial(ChangeRsDate(sStart_date),
                                    ChangeRsDate(sEnd_date), sColor));
                        else
                            patientRecord.append(getTimelineDateStringSpecial(ChangeRsDate(sStart_date),
                                    ChangeRsDate(sEnd_date)));
                    } else if (sInout_cd.equalsIgnoreCase("E")) {
                        if (sColor != null)
                            patientRecord.append(getTimelineDateStringEncounter(ChangeRsDate(sStart_date),
                                    ChangeRsDate(sEnd_date), sColor));
                        else
                            patientRecord.append(getTimelineDateStringEncounter(ChangeRsDate(sStart_date),
                                    ChangeRsDate(sEnd_date)));
                    } else if (sInout_cd.equalsIgnoreCase("D")) {
                        if (sStart_date.length() == 0) {
                            if (sColor != null)
                                patientRecord.append(getTimelineDateStringEncounter("today", "today", sColor));
                            else
                                patientRecord.append(getTimelineDateStringEncounter("today", "today"));
                        } else {
                            if (sColor != null)
                                patientRecord.append(
                                        getTimelineDateStringDeath(ChangeRsDate(sStart_date), "today", sColor));
                            else
                                patientRecord.append(
                                        getTimelineDateStringDeath(ChangeRsDate(sStart_date), "today", sColor));
                        }
                    } else {
                        if (sConcept_cd.equals("Death")) {
                            if (sStart_date.length() == 0) {
                                sStart_date = "today";
                                sColor = "lightbrown";
                            }
                            sEnd_date = "today";
                        }
                        if (sColor != null) {
                            if (sConcept_cd.equalsIgnoreCase("EGFR"))
                                patientRecord.append(getTimelineDateString(ChangeRsDate(sStart_date),
                                        ChangeRsDate(sEnd_date), sColor,
                                        "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=gene&cmd=Retrieve&dopt=Graphics&list_uids=1956"));
                            else
                                patientRecord.append(getTimelineDateStringHeight(ChangeRsDate(sStart_date),
                                        ChangeRsDate(sEnd_date), sColor, sHeight, sValue));
                        } else
                            patientRecord.append(getTimelineDateStringHeight(ChangeRsDate(sStart_date),
                                    ChangeRsDate(sEnd_date), sHeight));
                    }
                }
                sOldStart_date = sStart_date;

                if (!bOverMax) {
                    if (bDisplayAll && (indexPos == iNumberOfChildren)) {
                        while ((conceptOrder != null) && (conceptCount < conceptOrder.size())) {
                            patientRecord.append(
                                    getTimelineConceptString((String) conceptOrder.get(conceptCount), 1));
                            patientRecord.append(getTimelineEmptyDateString());
                            conceptCount++;
                        }
                    }
                    resultFile.append(patientRecord.toString());
                    patientRecord = new StringBuilder();
                    patientCount++;
                }
            }
        }

        if ((!bOverMax) && bDisplayAll) {
            while ((conceptOrder != null) && (conceptCount < conceptOrder.size())) {
                patientRecord.append(getTimelineConceptString((String) conceptOrder.get(conceptCount), 1));
                patientRecord.append(getTimelineEmptyDateString());
                conceptCount++;
            }
            resultFile.append(patientRecord.toString());
        }

        resultFile.append(GetTimelineFooter());
        log.debug(" Total Count " + iNumberOfChildren);

        if (writeFile) {
            String i2b2File = System.getProperty("user.dir") + '/' + "i2b2xml.lld";
            File oDelete = new File(i2b2File);
            if (oDelete != null)
                oDelete.delete();
            RandomAccessFile f = new RandomAccessFile(i2b2File, "rw");
            Lib.append(f, resultFile.toString());
            f.close();
        }

        if (bOverMax) {
            log.debug("reached maximum at " + new Date());
            return "overmaximum";
        }
    } catch (java.lang.OutOfMemoryError e) {
        log.error("In resultset builder 6: " + e.getMessage());
        // closeConnection(oConnection);
        return "memory error";
    } catch (Exception e) {
        log.error(e.getMessage());
        // closeConnection(oConnection);
        return "error";
    }

    log.debug("done at " + new Date());
    return resultFile.toString();

}

From source file:edu.harvard.i2b2.explorer.dataModel.TimelineFactory.java

@SuppressWarnings("unchecked")
public String generateTimelineData(String result, ArrayList<TimelineRow> rows, boolean writeFile,
        boolean displayAll, boolean displayDemographics, final MainComposite explorer) {

    try {// www. ja va  2  s.c o  m
        PDOResponseMessageModel pdoresponsefactory = new PDOResponseMessageModel();
        StatusType statusType = pdoresponsefactory.getStatusFromResponseXML(result);
        if (!statusType.getType().equalsIgnoreCase("DONE")) {
            return "error";
        }

        JAXBUtil jaxbUtil = ExplorerJAXBUtil.getJAXBUtil();

        JAXBElement jaxbElement = jaxbUtil.unMashallFromString(result);
        ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
        BodyType bodyType = messageType.getMessageBody();
        PatientDataResponseType responseType = (PatientDataResponseType) new JAXBUnWrapHelper()
                .getObjectByClass(bodyType.getAny(), PatientDataResponseType.class);
        PageType pageType = responseType.getPage();
        if (pageType != null) {
            final int returnLastIndex = pageType.getPagingByPatients().getPatientsReturned().getLastIndex()
                    .intValue();
            final int returnFirstIndex = pageType.getPagingByPatients().getPatientsReturned().getFirstIndex()
                    .intValue();
            final int requestLastIndex = pageType.getPagingByPatients().getPatientsRequested().getLastIndex()
                    .intValue();
            if (returnLastIndex < requestLastIndex) {
                // System.out.println("Can't return all the requested "+
                // requestIndex+" patients, only "+returnIndex+" patients returned");
                explorer.getDisplay().syncExec(new Runnable() {
                    public void run() {
                        // MessageBox mBox = new MessageBox(explorer
                        // .getShell(), SWT.ICON_INFORMATION
                        // | SWT.OK );
                        // mBox.setText("Please Note ...");
                        // mBox.setMessage("Only "+(returnLastIndex-returnFirstIndex+1)+" patients returned");
                        // mBox.open();
                        if (explorer.runMode() >= 0) {
                            explorer.setIncrementNumber(returnLastIndex - returnFirstIndex + 1);
                        } else if (explorer.runMode() == -1) {
                            explorer.setDecreaseNumber(returnLastIndex - returnFirstIndex + 1);
                        }
                    }
                });
                explorer.returnedNumber(returnLastIndex - returnFirstIndex + 1);
            } else {
                explorer.returnedNumber(-1);
            }
        } else {
            explorer.getDisplay().syncExec(new Runnable() {
                public void run() {
                    // MessageBox mBox = new MessageBox(explorer
                    // .getShell(), SWT.ICON_INFORMATION
                    // | SWT.OK );
                    // mBox.setText("Please Note ...");
                    // mBox.setMessage("Only "+(returnLastIndex-returnFirstIndex+1)+" patients returned");
                    // mBox.open();
                    if (explorer.runMode() >= 0) {
                        explorer.setIncrementNumber(-1);
                    } else if (explorer.runMode() == -1) {
                        explorer.setDecreaseNumber(-1);
                    }
                }
            });
        }

        StringBuilder resultFile = new StringBuilder();
        resultFile.append(GetTimelineHeader());

        PatientSet patientDimensionSet = pdoresponsefactory.getPatientSetFromResponseXML(result);
        if (patientDimensionSet != null) {
            log.debug("Total patient: " + patientDimensionSet.getPatient().size());
            // for(int i=0;
            // i<patientDimensionSet.getPatientDimension().size();i++) {
            // PatientDimensionType patientType =
            // patientDimensionSet.getPatientDimension().get(i);
            // System.out.println("PatientNum: " +
            // patientType.getPatientNum());
            // }
        } else {
            return "error";
        }

        // / testing the visit set
        // PatientDataType.VisitDimensionSet visitSet =
        // pdoresponsefactory.getVisitSetFromResponseXML(result);
        // System.out.println("Total visits: "+visitSet.getVisitDimension().
        // size());

        List<ObservationSet> factSets = pdoresponsefactory.getFactSetsFromResponseXML(result);

        log.debug("\nGenerate lld:");

        String curPNum = "-1";
        for (int i = 0; i < patientDimensionSet.getPatient().size(); i++) {
            PatientType patientType = patientDimensionSet.getPatient().get(i);
            String pnum = patientType.getPatientId().getValue();
            // Integer pnum = new Integer(snum);
            // log.debug("PatientNum: " + snum);
            //if(curPNum.equals("-1")) {
            curPNum = new String(pnum);
            //}

            if (displayDemographics) {
                resultFile.append(getTimelinePatientString(pnum.toString(), patientType));
            } else {
                resultFile.append(getTimelinePatientString(pnum.toString()));
            }

            String path = null;
            TimelineRow currentRow = null;
            ObservationSet observationFactSet = null;

            for (int j = 0; j < rows.size(); j++) {
                TimelineRow row = rows.get(j);
                int total = 0;
                StringBuilder resultString = new StringBuilder();

                XMLGregorianCalendar curStartDate = null;
                //int currentInstanceNum = 0;
                //String currentConcept = "";
                ArrayList<ObservationType> facts = new ArrayList<ObservationType>();
                ObservationType curFact = null;
                boolean recorded = false;
                String sStart_date = null;
                String sEnd_date = null;

                // loop thru all the pdo sets for this row here
                for (int s = 0; s < row.pdoItems.size(); s++) {
                    PDOItem pset = row.pdoItems.get(s);
                    observationFactSet = null;

                    for (int m = 0; m < factSets.size(); m++) {
                        ObservationSet tmpFactSet = factSets.get(m);
                        if (tmpFactSet.getPanelName().equalsIgnoreCase(pset.panelName())) {
                            observationFactSet = tmpFactSet;
                            path = observationFactSet.getPanelName();
                            currentRow = row;
                            break;
                        }
                    }

                    if (observationFactSet == null) {
                        continue;
                    }

                    for (int k = 0; k < observationFactSet.getObservation().size(); k++) {
                        ObservationType obsFactType = observationFactSet.getObservation().get(k);
                        //if(curFact == null) {
                        //curFact = obsFactType;
                        //}

                        //facts.add(obsFactType);

                        if (pnum.equals(obsFactType.getPatientId().getValue())) {
                            /*
                             * if ((curStartDate != null) &&
                             * (obsFactType.getStartDate().compare(
                             * curStartDate) == DatatypeConstants.EQUAL)) {
                             * continue; }
                             */
                            if (curFact == null) {
                                curFact = obsFactType;
                            }

                            if (curStartDate == null) {
                                curStartDate = obsFactType.getStartDate();
                            }

                            sStart_date = obsFactType.getStartDate().getMonth() + "-"
                                    + obsFactType.getStartDate().getDay() + "-"
                                    + obsFactType.getStartDate().getYear();

                            if (obsFactType.getEndDate() == null) {
                                sEnd_date = sStart_date;
                            } else {
                                sEnd_date = obsFactType.getEndDate().getMonth() + "-"
                                        + obsFactType.getEndDate().getDay() + "-"
                                        + obsFactType.getEndDate().getYear();
                            }

                            double nval = -1;
                            if (obsFactType.getNvalNum().getValue() != null) {
                                nval = obsFactType.getNvalNum().getValue().doubleValue();
                            }
                            PDOValueModel valdp = null;

                            boolean same = sameInstance(curFact, obsFactType);
                            if (false) {//pset.hasValueDisplayProperty) {
                                for (int n = 0; n < pset.valDisplayProperties.size(); n++) {
                                    PDOValueModel tmpvaldp = pset.valDisplayProperties.get(n);
                                    // if (tmpvaldp.inRange(nval)) {
                                    valdp = tmpvaldp;
                                    // break;
                                    // }
                                }

                                String sValue = getSValue(obsFactType.getConceptCd().getName(), obsFactType,
                                        true);
                                if ((curStartDate != null) && (obsFactType.getStartDate()
                                        .compare(curStartDate) == DatatypeConstants.EQUAL)) {
                                    resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date,
                                            "slateblue", valdp.height, sValue));
                                } else {
                                    resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date,
                                            valdp.color, valdp.height, sValue));
                                }
                            } else {
                                //////////////////////
                                String sValue = "";
                                if (same && k != observationFactSet.getObservation().size() - 1) {
                                    //if(recorded) {
                                    facts.add(obsFactType);
                                    //recorded = false;
                                    continue;
                                    //}
                                    /*sValue = getSValueSame(obsFactType.getConceptCd().getName(),
                                          obsFactType, false);
                                    if ((curStartDate != null)
                                          && (obsFactType.getStartDate()
                                                .compare(curStartDate) == DatatypeConstants.EQUAL)) {
                                       resultString
                                             .append(getTimelineDateStringHeightSame(
                                     sStart_date, sEnd_date,
                                     "slateblue",
                                     pset.height, sValue));
                                    } else {
                                       resultString
                                             .append(getTimelineDateStringHeightSame(
                                     sStart_date, sEnd_date,
                                     pset.color,
                                     pset.height, sValue));
                                    }*/
                                }
                                //else {
                                if (facts.size() == 0) {
                                    facts.add(obsFactType);
                                }
                                sValue = getSValue(curFact.getConceptCd().getName(), facts, false);
                                //}

                                sStart_date = curFact.getStartDate().getMonth() + "-"
                                        + curFact.getStartDate().getDay() + "-"
                                        + curFact.getStartDate().getYear();

                                if (curFact.getEndDate() == null) {
                                    sEnd_date = sStart_date;
                                } else {
                                    sEnd_date = curFact.getEndDate().getMonth() + "-"
                                            + curFact.getEndDate().getDay() + "-"
                                            + curFact.getEndDate().getYear();
                                }

                                //if ((curStartDate != null)
                                //      && (obsFactType.getStartDate()
                                //      .compare(curStartDate) == DatatypeConstants.EQUAL)) {
                                //resultString
                                //.append(getTimelineDateStringHeight(
                                //sStart_date, sEnd_date,
                                //"slateblue",
                                //pset.height, sValue));
                                //} else {
                                resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date,
                                        pset.color, pset.height, sValue));
                                //}
                            }

                            total++;
                            recorded = false;
                            facts.clear();
                            facts.add(obsFactType);
                            curStartDate = obsFactType.getStartDate();
                            curFact = obsFactType;

                            /////
                            if (!same && k == observationFactSet.getObservation().size() - 1) {
                                String sValue = "";
                                sValue = getSValue(obsFactType.getConceptCd().getName(), facts, false);
                                //}

                                sStart_date = obsFactType.getStartDate().getMonth() + "-"
                                        + obsFactType.getStartDate().getDay() + "-"
                                        + obsFactType.getStartDate().getYear();

                                if (obsFactType.getEndDate() == null) {
                                    sEnd_date = sStart_date;
                                } else {
                                    sEnd_date = obsFactType.getEndDate().getMonth() + "-"
                                            + obsFactType.getEndDate().getDay() + "-"
                                            + obsFactType.getEndDate().getYear();
                                }

                                //if ((curStartDate != null)
                                //      && (obsFactType.getStartDate()
                                //      .compare(curStartDate) == DatatypeConstants.EQUAL)) {
                                //resultString
                                //.append(getTimelineDateStringHeight(
                                //sStart_date, sEnd_date,
                                //"slateblue",
                                //pset.height, sValue));
                                //} else {
                                resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date,
                                        pset.color, pset.height, sValue));
                                //}
                                total++;
                            }
                            ////
                        } else {
                            if (recorded || facts.size() == 0) {
                                curPNum = new String(pnum);
                                continue;
                            }
                            sStart_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-"
                                    + curStartDate.getYear();

                            //if (obsFactType.getEndDate() == null) {
                            //sEnd_date = sStart_date;
                            //} else {
                            sEnd_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-"
                                    + curStartDate.getYear() + " 12:00";
                            //}
                            //curFact = null;
                            String sValue = getSValue(curFact.getConceptCd().getName(), facts, false);
                            //if ((curStartDate != null)
                            //&& (obsFactType.getStartDate()
                            //.compare(curStartDate) == DatatypeConstants.EQUAL)) {
                            //resultString
                            //.append(getTimelineDateStringHeight(
                            //sStart_date, sEnd_date,
                            //"slateblue",
                            //pset.height, sValue));
                            //} else {
                            resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date, pset.color,
                                    pset.height, sValue));
                            //}
                            total++;
                            recorded = true;
                            facts.clear();
                            curStartDate = null;//obsFactType.getStartDate();
                            curFact = null;//obsFactType;
                            curPNum = new String(pnum);
                        }
                    }
                }

                if (total > 0) {
                    // log.debug("-- "+path+" has "+total+" events");
                    resultFile.append(getTimelineConceptString(row.displayName, total));

                    // log.debug(resultString.toString());
                    resultFile.append(resultString);
                    total = 0;
                    recorded = true;
                } else {
                    // display all
                    if (displayAll) {
                        // log.debug("-- "+path+" has "+total+" events");
                        resultFile.append(getTimelineConceptString(row.displayName, 1));

                        // log.debug(getTimelineEmptyDateString());
                        resultFile.append(getTimelineEmptyDateString());
                    }
                }

                if (recorded || facts.size() == 0) {
                    curPNum = new String(pnum);
                    continue;
                }
                sStart_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-"
                        + curStartDate.getYear();

                //if (obsFactType.getEndDate() == null) {
                //sEnd_date = sStart_date;
                //} else {
                sEnd_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-"
                        + curStartDate.getYear();
                //}
                //curFact = null;
                String sValue = getSValue(curFact.getConceptCd().getName(), facts, false);

                resultString
                        .append(getTimelineDateStringHeight(sStart_date, sEnd_date, "navyblue", "p10", sValue));

                total++;
                recorded = true;
                facts.clear();
                //curStartDate = obsFactType.getStartDate();
                //curFact = obsFactType;
                curPNum = new String(pnum);
                if (total > 0) {
                    // log.debug("-- "+path+" has "+total+" events");
                    resultFile.append(getTimelineConceptString(row.displayName, total));

                    // log.debug(resultString.toString());
                    resultFile.append(resultString);
                }
            }
        }

        resultFile.append(GetTimelineFooter());

        if (writeFile) {
            String i2b2File = System.getProperty("user.dir") + "/temp/" + "i2b2xml.lld";
            File oDelete = new File(i2b2File);
            if (oDelete != null)
                oDelete.delete();
            RandomAccessFile f = new RandomAccessFile(i2b2File, "rw");
            append(f, resultFile.toString());
            f.close();
        }

        // log.debug("\nThe lld file: \n"+resultFile.toString());
        return resultFile.toString();
    } catch (org.apache.axis2.AxisFault e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return null;
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return "error";
    }
}

From source file:juicebox.tools.utils.original.Preprocessor.java

private void updateMasterIndex() throws IOException {
    RandomAccessFile raf = null;
    try {/*www . j  a  v  a 2  s  .c om*/
        raf = new RandomAccessFile(outputFile, "rw");

        // Master index
        raf.getChannel().position(masterIndexPositionPosition);
        BufferedByteWriter buffer = new BufferedByteWriter();
        buffer.putLong(masterIndexPosition);
        raf.write(buffer.getBytes());

    } finally {
        if (raf != null)
            raf.close();
    }
}