Example usage for java.io RandomAccessFile read

List of usage examples for java.io RandomAccessFile read

Introduction

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

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this file into an array of bytes.

Usage

From source file:au.org.ala.layers.intersect.Grid.java

public float[] getGrid() {
    int maxArrayLength = Integer.MAX_VALUE - 10;

    if (grid_data != null) {
        return grid_data;
    }//from  w  w  w  . j av  a 2s .  c o  m

    Grid loadedAlready = getLoadedGrid(filename);
    if (loadedAlready != null && loadedAlready.grid_data != null) {
        return loadedAlready.grid_data;
    }

    int length = nrows * ncols;

    float[] ret = new float[length];

    RandomAccessFile afile = null;
    File f2 = new File(filename + ".GRI");

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        byte[] b = new byte[(int) Math.min(afile.length(), maxArrayLength)];

        int i = 0;
        int max = 0;
        int len;
        while ((len = afile.read(b)) > 0) {
            ByteBuffer bb = ByteBuffer.wrap(b);

            if (byteorderLSB) {
                bb.order(ByteOrder.LITTLE_ENDIAN);
            }

            if (datatype.equalsIgnoreCase("UBYTE")) {
                max += len;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.get();
                    if (ret[i] < 0) {
                        ret[i] += 256;
                    }
                }
            } else if (datatype.equalsIgnoreCase("BYTE")) {
                max += len;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.get();
                }
            } else if (datatype.equalsIgnoreCase("SHORT")) {
                max += len / 2;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getShort();
                }
            } else if (datatype.equalsIgnoreCase("INT")) {
                max += len / 4;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getInt();
                }
            } else if (datatype.equalsIgnoreCase("LONG")) {
                max += len / 8;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getLong();
                }
            } else if (datatype.equalsIgnoreCase("FLOAT")) {
                max += len / 4;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getFloat();
                }
            } else if (datatype.equalsIgnoreCase("DOUBLE")) {
                max += len / 8;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = (float) bb.getDouble();
                }
            } else {
                // / should not happen; catch anyway...
                max += len / 4;
                for (; i < max; i++) {
                    ret[i] = Float.NaN;
                }
            }
        }

        //replace not a number
        for (i = 0; i < length; i++) {
            if ((float) ret[i] == (float) nodatavalue) {
                ret[i] = Float.NaN;
            } else {
                ret[i] *= rescale;
            }
        }
    } catch (Exception e) {
        logger.error("An error has occurred - probably a file error", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    grid_data = ret;
    return ret;
}

From source file:au.org.ala.layers.intersect.Grid.java

public void getClassInfo(Map<Float, float[]> info) {

    long length = ((long) nrows) * ((long) ncols);

    RandomAccessFile afile = null;
    File f2 = new File(filename + ".GRI");

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {//from  w  ww .j ava 2s. c om
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        byte[] b = new byte[65536];

        long i = 0;
        long max = 0;
        long len;
        float v;
        float ndv = (float) nodatavalue;

        while ((len = afile.read(b)) > 0) {
            ByteBuffer bb = ByteBuffer.wrap(b);

            if (byteorderLSB) {
                bb.order(ByteOrder.LITTLE_ENDIAN);
            }

            if (datatype.equalsIgnoreCase("UBYTE")) {
                max += len;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.get();
                    if (v < 0)
                        v += 256;
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("BYTE")) {
                max += len;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.get();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("SHORT")) {
                max += len / 2;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getShort();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("INT")) {
                max += len / 4;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getInt();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("LONG")) {
                max += len / 8;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getLong();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("FLOAT")) {
                max += len / 4;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getFloat();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("DOUBLE")) {
                max += len / 8;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = (float) bb.getDouble();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else {
                max += len / 4;
                for (; i < max; i++) {
                    // should not happen; catch anyway...
                }
            }
        }
    } catch (Exception e) {
        logger.error("An error has occurred getting grid class stats", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

}

From source file:au.org.ala.layers.intersect.Grid.java

/**
 * Increase sampleEveryNthPoint to return a smaller grid.
 *
 * Grid max and min values may be skipped.
 *
 * This does not used previously cached data.
 *
 * @param sampleEveryNthPoint//  w w w.ja va  2  s. co m
 * @return
 */
public float[] getGrid(int sampleEveryNthPoint) {
    int maxArrayLength = Integer.MAX_VALUE - 10;

    if (subgrids != null) {
        //sample points
        int size = 1000;
        double[][] points = new double[size * size][2];
        int pos = 0;
        for (int i = 0; i < 1000; i++) {
            for (int j = 0; j < 1000; j++) {
                points[pos][0] = xmin + (xmax - xmin) * j / (double) size;
                points[pos][1] = ymax - (ymax - ymin) * i / (double) size;
                pos++;
            }
        }

        return getValues3(points, 64);
    }

    int length = (nrows / sampleEveryNthPoint) * (ncols);

    float[] ret = new float[length];

    RandomAccessFile afile = null;
    File f2 = new File(filename + ".GRI");

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        int sz = (int) Math.min(afile.length() / sampleEveryNthPoint / sampleEveryNthPoint, maxArrayLength);
        sz += 8 - sz % 8;
        byte[] b = new byte[sz];

        long i = 0;
        long max = 0;
        int len;
        while ((len = afile.read(b)) > 0) {
            ByteBuffer bb = ByteBuffer.wrap(b);

            if (byteorderLSB) {
                bb.order(ByteOrder.LITTLE_ENDIAN);
            }

            if (datatype.equalsIgnoreCase("UBYTE")) {
                max += len;
                max = Math.min(max, ret.length * (long) sampleEveryNthPoint);
                for (; i < max; i++) {
                    ret[(int) (i / sampleEveryNthPoint)] = bb.get();
                    if (ret[(int) (i / sampleEveryNthPoint)] < 0) {
                        ret[(int) (i / sampleEveryNthPoint)] += 256;
                    }
                }
            } else if (datatype.equalsIgnoreCase("BYTE")) {
                max += len;
                max = Math.min(max, ret.length * (long) sampleEveryNthPoint);
                for (; i < max; i++) {
                    ret[(int) (i / sampleEveryNthPoint)] = bb.get();
                }
            } else if (datatype.equalsIgnoreCase("SHORT")) {
                max += len / 2;
                max = Math.min(max, ret.length * (long) sampleEveryNthPoint);
                for (; i < max; i++) {
                    ret[(int) (i / sampleEveryNthPoint)] = bb.getShort();
                }
            } else if (datatype.equalsIgnoreCase("INT")) {
                max += len / 4;
                max = Math.min(max, ret.length * (long) sampleEveryNthPoint);
                for (; i < max; i++) {
                    ret[(int) (i / sampleEveryNthPoint)] = bb.getInt();
                }
            } else if (datatype.equalsIgnoreCase("LONG")) {
                max += len / 8;
                max = Math.min(max, ret.length * (long) sampleEveryNthPoint);
                for (; i < max; i++) {
                    ret[(int) (i / sampleEveryNthPoint)] = bb.getLong();
                }
            } else if (datatype.equalsIgnoreCase("FLOAT")) {
                max += len / 4;
                max = Math.min(max, ret.length * (long) sampleEveryNthPoint);
                for (; i < max; i++) {
                    ret[(int) (i / sampleEveryNthPoint)] = bb.getFloat();
                }
            } else if (datatype.equalsIgnoreCase("DOUBLE")) {
                max += len / 8;
                max = Math.min(max, ret.length * (long) sampleEveryNthPoint);
                for (; i < max; i++) {
                    ret[(int) (i / (long) sampleEveryNthPoint)] = (float) bb.getDouble();
                }
            } else {
                // / should not happen; catch anyway...
                max += len / 4;
                for (; i < max; i++) {
                    ret[(int) (i / (long) sampleEveryNthPoint)] = Float.NaN;
                }
            }
        }

        //replace not a number
        for (i = 0; i < length; i++) {
            if ((float) ret[(int) i] == (float) nodatavalue) {
                ret[(int) i] = Float.NaN;
            } else {
                ret[(int) i] *= rescale;
            }
        }
    } catch (Exception e) {
        logger.error("An error has occurred - probably a file error", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    grid_data = ret;
    return ret;
}

From source file:au.org.ala.layers.intersect.Grid.java

public void replaceValues(Map<Integer, Integer> translation) {

    long length = ((long) nrows) * ((long) ncols);

    Integer minv = null;/*from www.j  ava  2  s  .c o  m*/
    Integer maxv = null;
    for (Integer i : translation.values()) {
        if (minv == null || i < minv)
            minv = i;
        if (maxv == null || i > maxv)
            maxv = i;
    }

    RandomAccessFile afile = null;
    RandomAccessFile out = null;
    File f2 = new File(filename + ".GRI");
    File newGrid = new File(filename + ".gri.new");

    try { //read of random access file can throw an exception
        out = new RandomAccessFile(newGrid, "rw");

        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        byte[] b = new byte[65536];
        byte[] bout = new byte[65536];

        long i = 0;
        long max = 0;
        long len;
        float v;
        float ndv = (float) nodatavalue;

        while ((len = afile.read(b)) > 0) {
            ByteBuffer bb = ByteBuffer.wrap(b);
            ByteBuffer bbout = ByteBuffer.wrap(bout);

            if (byteorderLSB) {
                bb.order(ByteOrder.LITTLE_ENDIAN);
                bbout.order(ByteOrder.LITTLE_ENDIAN);
            }

            if (datatype.equalsIgnoreCase("UBYTE")) {
                throw new Exception("UBYTE translation not supported");
            } else if (datatype.equalsIgnoreCase("BYTE")) {
                throw new Exception("BYTE translation not supported");
            } else if (datatype.equalsIgnoreCase("SHORT")) {
                max += len / 2;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getShort();
                    if (v != ndv && translation.get((int) (v * rescale)) == null) {
                        v = v;
                    }
                    if (v != ndv && translation.get((int) (v * rescale)) != null)
                        v = translation.get((int) (v * rescale));
                    bbout.putShort((short) v);
                }
            } else if (datatype.equalsIgnoreCase("INT")) {
                max += len / 4;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getInt();
                    if (v != ndv && translation.get((int) (v * rescale)) != null)
                        v = translation.get((int) (v * rescale));
                    bbout.putInt((int) v);
                }
            } else if (datatype.equalsIgnoreCase("LONG")) {
                max += len / 8;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getLong();
                    if (v != ndv && translation.get((int) (v * rescale)) != null)
                        v = translation.get((int) (v * rescale));
                    bbout.putLong((long) v);
                }
            } else if (datatype.equalsIgnoreCase("FLOAT")) {
                throw new Exception("FLOAT translation not supported");
            } else if (datatype.equalsIgnoreCase("DOUBLE")) {
                throw new Exception("DOUBLE translation not supported");
            } else {
                max += len / 4;
                for (; i < max; i++) {
                    // should not happen; catch anyway...
                }
            }

            out.write(bout, 0, (int) len);
        }

        writeHeader(filename + ".new", xmin, ymin, xmin + xres * ncols, ymin + yres * nrows, xres, yres, nrows,
                ncols, minv, maxv, datatype, nodatavalue + "");
    } catch (Exception e) {
        logger.error("An error has occurred getting grid class stats", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }

        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    try {
        if (!new File(filename + ".gri.old").exists())
            FileUtils.moveFile(new File(filename + ".gri"), new File(filename + ".gri.old"));
        if (!new File(filename + ".grd.old").exists())
            FileUtils.moveFile(new File(filename + ".grd"), new File(filename + ".grd.old"));

        FileUtils.moveFile(new File(filename + ".gri.new"), new File(filename + ".gri"));
        FileUtils.moveFile(new File(filename + ".new.grd"), new File(filename + ".grd"));
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:se.kth.ssvl.tslab.bytewalla.androiddtn.servlib.bundling.BundleDaemon.java

protected void handle_bundle_received(BundleReceivedEvent event) {

    Bundle bundle = event.bundle();//from   ww  w  .j  a  v a 2  s.  c o  m

    String notify_msg = "";
    String ID = local_eid().toString() + "/";
    //      Log.v(TAG, "daemon_bundle_id" + (int) bundle.bundleid());
    //      Log.v(TAG,"daemon_source" + bundle.source().toString());
    //      Log.v(TAG,"daemon_destination" + bundle.custodian().toString());
    //   Toast.makeText(,"local : "+local_eid().toString()+"\nDest : "+bundle.act_dest().toString(),Toast.LENGTH_SHORT).show();

    //      Log.d(TAG, " time ID " +  bundle.creation_ts().seconds());

    //  Log.d(TAG, " custodian ID " +  ID);
    //   Log.d(TAG, " LOCAL ID " +  local_eid().toString());
    Log.d(TAG, " handle bundle received from " + event.source() + ", id = " + bundle.bundleid());

    // "update statistics and store an appropriate event descriptor" [DTN2]
    String source_str = "";
    switch (event.source()) {
    case EVENTSRC_PEER:
        stats_.received_bundles_++;

        // MultiHopStorage.getInstance().impt_sqlite_().get_records("bundle","id>0","id");

        String output = "";

        byte[] result = new byte[bundle.payload().length()];
        RandomAccessFile file_handle = null;
        try {
            file_handle = new RandomAccessFile(bundle.payload().file(), "r");
            file_handle.read(result);
            output = new String(result, "US-ASCII");

        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, e.getMessage());
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        } finally {
            try {
                file_handle.close();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            }
        }
        if (bundle.custodian() != null && !bundle.custodian().equals(EndpointID.NULL_EID())) {
            //String encrypted = bundle.custodian().toString();
            //String [] both = encrypted.split("\n");
            //bundle.set_custodian();
            //String custodian = both[0];
            //if(!custodian.equals(ID)) {
            if (!bundle.custodian().toString().equals(ID)) {
                //String msg = both[1];
                //bundle.set_owner(msg);
                notify_msg += "Guest ";

                // if this was my bundle that i have sent but some one sent me, discard it
                if (bundle.source().toString().equals(BundleDaemon.getInstance().local_eid().toString()))
                    return;
                //
                ArrayList<String> items = new ArrayList<String>(Arrays.asList(output.split("  ,")));
                output = items.get(0);
                bundle.set_bundleid((Integer.parseInt(items.get(1))));

                // Checking if already sent to actual destination

                if (MultiHopStorage
                        .getInstance().impt_sqlite_().get_records("Forwards", "bundle_id = " + bundle.bundleid()
                                + " and destination = '" + bundle.custodian().toString() + "'", "id")
                        .size() > 0) {
                    return;
                }
                // check if this bundle already exists in my database, discard it
                if (MultiHopStorage.getInstance().impt_sqlite_()
                        .get_records("bundle",
                                "bundle_id = " + bundle.bundleid() + " and source = '" + bundle.source() + "'"

                                        + " and destination = '" + bundle.custodian().toString() + "'",
                                "id")
                        .size() > 0) {
                    return;
                } else {
                    // so its a new bundle destined to some node , i am the intermediate one.
                    // add this bundle to db after adding current alive nodes to forward list to indicate that
                    // bundle is already been sent to these nodes
                    // LinkSet EntriesList = ContactManager.getInstance().links();
                    Iterator<String> i = DTNDiscovery.getNodes().iterator();
                    // Link.set_link_counter(0);

                    while (i.hasNext()) {
                        // Link element = i.next();
                        String Eid = i.next();

                        MultiHopStorage.getInstance().add(bundle.bundleid(), Eid + "/");
                        // here it is adding in forwards table
                    }
                    MultiHopStorage.getInstance().add(bundle, output);
                }
            } else if (!bundle.source().toString().contains("prophet")) {
                if (output.contains("  ,")) {
                    ArrayList<String> items = new ArrayList<String>(Arrays.asList(output.split("  ,")));
                    output = items.get(0);
                }
                MultiHopStorage.getInstance().add_messages(bundle.source().toString() + "/", output);
                //                  DTNMessageView.update();
            }
        }

        //         else Toast.makeText(DTNManager.getInstance().getApplicationContext(),"From " + bundle.source().toString(),Toast.LENGTH_LONG).show();
        Log.d("RECIVINGS", "forwarded From " + bundle.source().toString());
        DTNManager.getInstance().notify_user(notify_msg + "DTN Bundle Received",
                "From " + bundle.source().toString());

        break;

    case EVENTSRC_APP:
        stats_.received_bundles_++;
        source_str = " (from app)";
        break;

    case EVENTSRC_STORE:
        source_str = " (from data store)";
        break;

    case EVENTSRC_ADMIN:
        stats_.generated_bundles_++;
        source_str = " (generated)";
        break;

    case EVENTSRC_FRAGMENTATION:
        stats_.generated_bundles_++;
        source_str = " (from fragmentation)";
        break;

    case EVENTSRC_ROUTER:
        stats_.generated_bundles_++;
        source_str = " (from router)";
        break;

    default:
        Log.e(TAG, "Bundle Daemon: handle_bundle_received");
    }

    StringBuffer buf = new StringBuffer();
    bundle.format(buf);
    Log.i(TAG, String.format("BUNDLE_RECEIVED %s bundle id (%d) prevhop %s (%d bytes recvd)", source_str,
            bundle.bundleid(), event.prevhop().toString(), event.bytes_received()));

    // log the reception in the bundle's forwarding log
    if (event.source() == event_source_t.EVENTSRC_PEER && event.link() != null) {
        bundle.fwdlog().add_entry(event.link(), ForwardingInfo.action_t.FORWARD_ACTION,
                ForwardingInfo.state_t.RECEIVED);
    } else if (event.source() == event_source_t.EVENTSRC_APP) {
        if (event.registration() != null) {
            bundle.fwdlog().add_entry(event.registration(), ForwardingInfo.action_t.FORWARD_ACTION,
                    ForwardingInfo.state_t.RECEIVED);
        }
    }

    // "log a warning if the bundle doesn't have any expiration time or
    // has a creation time that's in the future. in either case, we
    // proceed as normal" [DTN2]

    if (bundle.expiration() == 0) {
        Log.w(TAG, String.format("bundle id %d arrived with zero expiration time", bundle.bundleid()));
    }

    long now = TimeHelper.current_seconds_from_ref();
    if ((bundle.creation_ts().seconds() > now) && (bundle.creation_ts().seconds() - now > 30000)) {
        Log.w(TAG, String.format("bundle id %d arrived with creation time in the future " + "(%d > %d)",
                bundle.bundleid(), bundle.creation_ts().seconds(), now));
    }

    /*
     * "If a previous hop block wasn't included, but we know the remote
     * endpoint id of the link where the bundle arrived, assign the prevhop_
     * field in the bundle so it's available for routing." [DTN2]
     */
    if (event.source() == event_source_t.EVENTSRC_PEER) {

        if (bundle.prevhop() == null || bundle.prevhop().uri() == null) {
            bundle.set_prevhop(new EndpointID(EndpointID.NULL_EID()));
        }

        if (bundle.prevhop().is_null()) {
            bundle.prevhop().assign(event.prevhop());
        }

        if (!bundle.prevhop().equals(event.prevhop())) {
            Log.w(TAG,
                    String.format(
                            "previous hop mismatch: prevhop header contains '%s' but "
                                    + "convergence layer indicates prevhop is '%s'",
                            bundle.prevhop().toString(), event.prevhop().toString()));
        }
    }

    /*
     * "validate a bundle, including all bundle blocks, received from a peer" [DTN2]
     */
    if (event.source() == event_source_t.EVENTSRC_PEER) {

        /*
         * "Check all BlockProcessors to validate the bundle. Initialize the
         * value in case the Bundle Protocol didn't give reason" [DTN2]
         */
        status_report_reason_t[] reception_reason = new status_report_reason_t[1];
        reception_reason[0] = status_report_reason_t.REASON_NO_ADDTL_INFO;
        status_report_reason_t[] deletion_reason = new status_report_reason_t[1];
        deletion_reason[0] = status_report_reason_t.REASON_NO_ADDTL_INFO;

        boolean valid = BundleProtocol.validate(bundle, reception_reason, deletion_reason);

        /*
         * "Send the reception receipt if requested within the primary block
         * or some other error occurs that requires a reception status
         * report but may or may not require deleting the whole bundle." [DTN2]
         */
        if (bundle.receive_rcpt()
                || reception_reason[0] != BundleProtocol.status_report_reason_t.REASON_NO_ADDTL_INFO) {
            generate_status_report(bundle, BundleStatusReport.flag_t.STATUS_RECEIVED, reception_reason[0]);
        }

        /* 
         * "If the bundle is valid, probe the router to see if it wants to
         * accept the bundle." [DTN2]
         */
        boolean accept_bundle = false;
        if (valid) {
            BundleProtocol.status_report_reason_t[] reason = new BundleProtocol.status_report_reason_t[1];
            // "initialize the value in case the router didn't set the value
            // reason for us" [DTN2]
            reason[0] = status_report_reason_t.REASON_NO_ADDTL_INFO;
            accept_bundle = router_.accept_bundle(bundle, reason);
            deletion_reason[0] = reason[0];
        }

        /*
         * "Delete a bundle if a validation error was encountered or the
         * router doesn't want to accept the bundle, in both cases not
         * giving the reception event to the router." [DTN2]
         */
        if (!accept_bundle) {
            delete_bundle(bundle, deletion_reason[0]);
            event.set_daemon_only(true);
            return;
        }
    }

    /*
     * "Check if the bundle is a duplicate, i.e. shares a source id,
     * timestamp, and fragmentation information with some other bundle in
     * the system." [DTN2]
     */
    Bundle duplicate = find_duplicate(bundle);
    if (duplicate != null) {
        Log.i(TAG,
                String.format("got duplicate bundle: %s . %s creation timestamp %d.%d",
                        bundle.source().toString(), bundle.dest().toString(), bundle.creation_ts().seconds(),
                        bundle.creation_ts().seqno()));

        stats_.duplicate_bundles_++;

        if (bundle.custody_requested() && duplicate.local_custody()) {
            generate_custody_signal(bundle, false,
                    BundleProtocol.custody_signal_reason_t.CUSTODY_REDUNDANT_RECEPTION);
        }

        if (params_.suppress_duplicates_) {
            // "since we don't want the bundle to be processed by the rest
            // of the system, we mark the event as daemon_only (meaning it
            // won't be forwarded to routers) and return, which should
            // eventually remove all references on the bundle and then it
            // will be deleted" [DTN2]
            event.set_daemon_only(true);
            return;
        }

        // "The BP says that the "dispatch pending" retention constraint
        // must be removed from this bundle if there is a duplicate we
        // currently have custody of. This would cause the bundle to have
        // no retention constraints and it now "may" be discarded. Assuming
        // this means it is supposed to be discarded, we have to suppress
        // a duplicate in this situation regardless of the parameter
        // setting. We would then be relying on the custody transfer timer
        // to cause a new forwarding attempt in the case of routing loops
        // instead of the receipt of a duplicate, so in theory we can indeed
        // suppress this bundle. It may not be strictly required to do so,
        // in which case we can remove the following block." [DTN2]
        if (bundle.custody_requested() && duplicate.local_custody()) {
            event.set_daemon_only(true);
            return;
        }

    }

    /*
     * "Add the bundle to the master pending queue and the data store (unless
     * the bundle was just reread from the data store on startup)
     * 
     * Note that if add_to_pending returns false, the bundle has already
     * expired so we immediately return instead of trying to deliver and/or
     * forward the bundle. Otherwise there's a chance that expired bundles
     * will persist in the network." [DTN2]
     */
    boolean ok_to_route = add_to_pending(bundle, (event.source() != event_source_t.EVENTSRC_STORE));

    if (!ok_to_route) {
        event.set_daemon_only(true);
        return;
    }

    /*
     * "If the bundle is a custody bundle and we're configured to take
     * custody, then do so. In case the event was delivered due to a reload
     * from the data store, then if we have local custody, make sure it's
     * added to the custody bundles list." [DTN2]
     */
    if (bundle.custody_requested() && params_.accept_custody_
            && (duplicate == null || !duplicate.local_custody())) {
        if (event.source() != event_source_t.EVENTSRC_STORE) {
            accept_custody(bundle);

        } else if (bundle.local_custody()) {
            custody_bundles_.push_back(bundle);
        }
    }

    /*
     * "If this bundle is a duplicate and it has not been suppressed, we can
     * assume the bundle it duplicates has already been delivered or added
     * to the fragment manager if required, so do not do so again. We can
     * bounce out now. Comments/jmmikkel If the extension blocks differ and
     * we care to do something with them, we can't bounce out quite yet." [DTN2]
     */
    if (duplicate != null) {
        // We have to delete the Bundle here
        delete_bundle(bundle, status_report_reason_t.REASON_NO_ADDTL_INFO);
        return;
    }

    /*
     * "Check if this is a complete (non-fragment) bundle that obsoletes any
     * fragments that we know about." [DTN2]
     */
    if (!bundle.is_fragment() && DTNService.context().getResources()
            .getString(R.string.DTNEnableProactiveFragmentation).equals("true")) {
        fragmentmgr_.delete_obsoleted_fragments(bundle);
    }

    /*
     * "Deliver the bundle to any local registrations that it matches, unless
     * it's generated by the router or is a bundle fragment. Delivery of
     * bundle fragments is deferred until after re-assembly." [DTN2]
     */
    boolean is_local = check_local_delivery(bundle,
            (event.source() != event_source_t.EVENTSRC_ROUTER) && (bundle.is_fragment() == false));

    /*
     * "Re-assemble bundle fragments that are destined to the local node." [DTN2]
     */
    if (bundle.is_fragment() && is_local) {
        Log.d(TAG, String.format("deferring delivery of bundle %d " + "since bundle is a fragment",
                bundle.bundleid()));
        fragmentmgr_.process_for_reassembly(bundle);
    }

    /*
     * "Finally, bounce out so the router(s) can do something further with
     * the bundle in response to the event." [DTN2]
     */
}

From source file:au.org.ala.layers.intersect.Grid.java

float[] getGrid(double xmin, double ymin, double xmax, double ymax) {
    //expects largest y at the top
    //expects input ranges inside of grid ranges

    int width = (int) ((xmax - xmin) / xres);
    int height = (int) ((ymax - ymin) / yres);
    int startx = (int) ((xmin - this.xmin) / xres);
    int endx = startx + width;
    int starty = (int) ((ymin - this.ymin) / yres);
    //int endy = starty + height;

    int length = width * height;

    float[] ret = new float[length];
    int pos = 0;/*from   ww w.j ava2s .co  m*/

    int i;
    RandomAccessFile afile = null;
    File f2 = new File(filename + ".GRI");

    int size = 4;
    if (datatype.equals("BYTE") || datatype.equals("UBYTE")) {
        size = 1;
    } else if (datatype.equals("SHORT")) {
        size = 2;
    } else if (datatype.equals("INT")) {
        size = 4;
    } else if (datatype.equals("LONG")) {
        size = 8;
    } else if (datatype.equals("FLOAT")) {
        size = 4;
    } else if (datatype.equals("DOUBLE")) {
        size = 8;
    }

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        //seek to first raster
        afile.seek(((long) this.ncols) * starty * size);

        //read relevant rasters
        int readSize = this.ncols * height * size;
        int readLen = this.ncols * height;
        byte[] b = new byte[readSize];
        afile.read(b);
        ByteBuffer bb = ByteBuffer.wrap(b);

        if (byteorderLSB) {
            bb.order(ByteOrder.LITTLE_ENDIAN);
        }

        if (datatype.equalsIgnoreCase("BYTE")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.get();
                } else {
                    ret[pos++] = bb.get();
                }
            }
        } else if (datatype.equalsIgnoreCase("UBYTE")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.get();
                } else {
                    ret[pos] = bb.get();
                    if (ret[pos] < 0) {
                        ret[pos] += 256;
                    }
                    pos++;
                }
            }
        } else if (datatype.equalsIgnoreCase("SHORT")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.getShort();
                } else {
                    ret[pos++] = bb.getShort();
                }
            }
        } else if (datatype.equalsIgnoreCase("INT")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.getInt();
                } else {
                    ret[pos++] = bb.getInt();
                }
            }
        } else if (datatype.equalsIgnoreCase("LONG")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.getLong();
                } else {
                    ret[pos++] = bb.getLong();
                }
            }
        } else if (datatype.equalsIgnoreCase("FLOAT")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.getFloat();
                } else {
                    ret[pos++] = bb.getFloat();
                }
            }
        } else if (datatype.equalsIgnoreCase("DOUBLE")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.getDouble();
                } else {
                    ret[pos++] = (float) bb.getDouble();
                }
            }
        } else {
            // / should not happen; catch anyway...
            for (i = 0; i < length; i++) {
                ret[i] = Float.NaN;
            }
        }
        //replace not a number
        for (i = 0; i < length; i++) {
            if ((float) ret[i] == (float) nodatavalue) {
                ret[i] = Float.NaN;
            } else {
                ret[i] *= rescale;
            }
        }
    } catch (Exception e) {
        logger.error("GRID: " + e.toString(), e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    grid_data = ret;
    return ret;
}

From source file:au.org.ala.layers.intersect.Grid.java

/**
 * @return calculated min and max values of a grid file as float [] where [0] is min and [1] is max.
 *///w  w  w  .  j  ava 2  s.c  o  m
public float[] calculatetMinMax() {

    float[] ret = new float[2];
    ret[0] = Float.MAX_VALUE;
    ret[1] = Float.MAX_VALUE * -1;

    long i;
    int size;
    byte[] b;
    RandomAccessFile afile = null;

    try { //read of random access file can throw an exception
        File f2 = new File(filename + ".GRI");
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        long length = ((long) nrows) * ((long) ncols);
        float f;

        if (datatype.equalsIgnoreCase("BYTE")) {
            size = 1;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                f = afile.readByte();
                if (f != (float) nodatavalue) {
                    ret[0] = Math.min(f * rescale, ret[0]);
                    ret[1] = Math.max(f * rescale, ret[1]);
                }
            }
        } else if (datatype.equalsIgnoreCase("UBYTE")) {
            size = 1;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                f = afile.readByte();
                if (f < 0) {
                    f += 256;
                }
                if (f != (float) nodatavalue) {
                    ret[0] = Math.min(f * rescale, ret[0]);
                    ret[1] = Math.max(f * rescale, ret[1]);
                }
            }
        } else if (datatype.equalsIgnoreCase("SHORT")) {
            size = 2;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                afile.read(b);
                if (byteorderLSB) {
                    f = (short) (((0xFF & b[1]) << 8) | (b[0] & 0xFF));
                } else {
                    f = (short) (((0xFF & b[0]) << 8) | (b[1] & 0xFF));
                }
                if (f != (float) nodatavalue) {
                    ret[0] = Math.min(f * rescale, ret[0]);
                    ret[1] = Math.max(f * rescale, ret[1]);
                }
            }
        } else if (datatype.equalsIgnoreCase("INT")) {
            size = 4;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                afile.read(b);
                if (byteorderLSB) {
                    f = ((0xFF & b[3]) << 24) | ((0xFF & b[2]) << 16) + ((0xFF & b[1]) << 8) + (b[0] & 0xFF);
                } else {
                    f = ((0xFF & b[0]) << 24)
                            | ((0xFF & b[1]) << 16) + ((0xFF & b[2]) << 8) + ((0xFF & b[3]) & 0xFF);
                }
                if (f != (float) nodatavalue) {
                    ret[0] = Math.min(f * rescale, ret[0]);
                    ret[1] = Math.max(f * rescale, ret[1]);
                }
            }
        } else if (datatype.equalsIgnoreCase("LONG")) {
            size = 8;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                afile.read(b);
                if (byteorderLSB) {
                    f = ((long) (0xFF & b[7]) << 56) + ((long) (0xFF & b[6]) << 48)
                            + ((long) (0xFF & b[5]) << 40) + ((long) (0xFF & b[4]) << 32)
                            + ((long) (0xFF & b[3]) << 24) + ((long) (0xFF & b[2]) << 16)
                            + ((long) (0xFF & b[1]) << 8) + (0xFF & b[0]);
                } else {
                    f = ((long) (0xFF & b[0]) << 56) + ((long) (0xFF & b[1]) << 48)
                            + ((long) (0xFF & b[2]) << 40) + ((long) (0xFF & b[3]) << 32)
                            + ((long) (0xFF & b[4]) << 24) + ((long) (0xFF & b[5]) << 16)
                            + ((long) (0xFF & b[6]) << 8) + (0xFF & b[7]);
                }
                if (f != (float) nodatavalue) {
                    ret[0] = Math.min(f * rescale, ret[0]);
                    ret[1] = Math.max(f * rescale, ret[1]);
                }
            }
        } else if (datatype.equalsIgnoreCase("FLOAT")) {
            size = 4;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                afile.read(b);
                ByteBuffer bb = ByteBuffer.wrap(b);
                if (byteorderLSB) {
                    bb.order(ByteOrder.LITTLE_ENDIAN);
                }
                f = bb.getFloat();
                if (f != (float) nodatavalue) {
                    ret[0] = Math.min(f * rescale, ret[0]);
                    ret[1] = Math.max(f * rescale, ret[1]);
                }
            }
        } else if (datatype.equalsIgnoreCase("DOUBLE")) {
            size = 8;
            b = new byte[8];
            for (i = 0; i < length; i++) {
                afile.read(b);
                ByteBuffer bb = ByteBuffer.wrap(b);
                if (byteorderLSB) {
                    bb.order(ByteOrder.LITTLE_ENDIAN);
                }
                f = (float) bb.getDouble();
                if (f != (float) nodatavalue) {
                    ret[0] = Math.min(f * rescale, ret[0]);
                    ret[1] = Math.max(f * rescale, ret[1]);
                }
            }
        } else {
            logger.error("datatype not supported in Grid.getValues: " + datatype);
        }
    } catch (Exception e) {
        logger.error("error calculating min/max of a grid file", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    return ret;
}

From source file:au.org.ala.layers.intersect.Grid.java

/**
 * @param points input array for longitude and latitude
 *               double[number_of_points][2]
 * @return array of .gri file values corresponding to the
 * points provided//  w  w w.  j a  v  a  2 s .co  m
 */
public float[] getValues(double[][] points) {

    //confirm inputs since they come from somewhere else
    if (points == null || points.length == 0) {
        return null;
    }

    //use preloaded grid data if available
    Grid g = Grid.getLoadedGrid(filename);
    if (g != null) {
        return g.getValues2(points);
    }

    if (subgrids != null) {
        return getValues3(points, Math.min(1024 * 1024, 64 * points.length));
    }

    float[] ret = new float[points.length];

    int length = points.length;
    long size;
    int i, pos;
    byte[] b;
    RandomAccessFile afile = null;
    File f2 = new File(filename + ".GRI");

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        if (datatype.equalsIgnoreCase("BYTE")) {
            size = 1;
            b = new byte[(int) size];
            for (i = 0; i < length; i++) {
                pos = (int) getcellnumber(points[i][0], points[i][1]);
                if (pos >= 0) {
                    afile.seek(pos * size);
                    ret[i] = afile.readByte();
                } else {
                    ret[i] = Float.NaN;
                }
            }
        } else if (datatype.equalsIgnoreCase("UBYTE")) {
            size = 1;
            b = new byte[(int) size];
            for (i = 0; i < length; i++) {
                pos = (int) getcellnumber(points[i][0], points[i][1]);
                if (pos >= 0) {
                    afile.seek(pos * size);
                    ret[i] = afile.readByte();
                    if (ret[i] < 0) {
                        ret[i] += 256;
                    }
                } else {
                    ret[i] = Float.NaN;
                }
            }
        } else if (datatype.equalsIgnoreCase("SHORT")) {
            size = 2;
            b = new byte[(int) size];
            for (i = 0; i < length; i++) {
                pos = (int) getcellnumber(points[i][0], points[i][1]);
                if (pos >= 0) {
                    afile.seek(pos * size);
                    afile.read(b);
                    if (byteorderLSB) {
                        ret[i] = (short) (((0xFF & b[1]) << 8) | (b[0] & 0xFF));
                    } else {
                        ret[i] = (short) (((0xFF & b[0]) << 8) | (b[1] & 0xFF));
                    }
                    //ret[i] = afile.readShort();
                } else {
                    ret[i] = Float.NaN;
                }
            }
        } else if (datatype.equalsIgnoreCase("INT")) {
            size = 4;
            b = new byte[(int) size];
            for (i = 0; i < length; i++) {
                pos = (int) getcellnumber(points[i][0], points[i][1]);
                if (pos >= 0) {
                    afile.seek(pos * size);
                    afile.read(b);
                    if (byteorderLSB) {
                        ret[i] = ((0xFF & b[3]) << 24)
                                | ((0xFF & b[2]) << 16) + ((0xFF & b[1]) << 8) + (b[0] & 0xFF);
                    } else {
                        ret[i] = ((0xFF & b[0]) << 24)
                                | ((0xFF & b[1]) << 16) + ((0xFF & b[2]) << 8) + ((0xFF & b[3]) & 0xFF);
                    }
                    //ret[i] = afile.readInt();
                } else {
                    ret[i] = Float.NaN;
                }
            }
        } else if (datatype.equalsIgnoreCase("LONG")) {
            size = 8;
            b = new byte[(int) size];
            for (i = 0; i < length; i++) {
                pos = (int) getcellnumber(points[i][0], points[i][1]);
                if (pos >= 0) {
                    afile.seek(pos * size);
                    afile.read(b);
                    if (byteorderLSB) {
                        ret[i] = ((long) (0xFF & b[7]) << 56) + ((long) (0xFF & b[6]) << 48)
                                + ((long) (0xFF & b[5]) << 40) + ((long) (0xFF & b[4]) << 32)
                                + ((long) (0xFF & b[3]) << 24) + ((long) (0xFF & b[2]) << 16)
                                + ((long) (0xFF & b[1]) << 8) + (0xFF & b[0]);
                    } else {
                        ret[i] = ((long) (0xFF & b[0]) << 56) + ((long) (0xFF & b[1]) << 48)
                                + ((long) (0xFF & b[2]) << 40) + ((long) (0xFF & b[3]) << 32)
                                + ((long) (0xFF & b[4]) << 24) + ((long) (0xFF & b[5]) << 16)
                                + ((long) (0xFF & b[6]) << 8) + (0xFF & b[7]);
                    }
                    //ret[i] = afile.readLong();
                } else {
                    ret[i] = Float.NaN;
                }
            }
        } else if (datatype.equalsIgnoreCase("FLOAT")) {
            size = 4;
            b = new byte[(int) size];
            for (i = 0; i < length; i++) {
                pos = (int) getcellnumber(points[i][0], points[i][1]);
                if (pos >= 0) {
                    afile.seek(pos * size);
                    afile.read(b);
                    ByteBuffer bb = ByteBuffer.wrap(b);
                    if (byteorderLSB) {
                        bb.order(ByteOrder.LITTLE_ENDIAN);
                    }
                    ret[i] = bb.getFloat();
                } else {
                    ret[i] = Float.NaN;
                }

            }
        } else if (datatype.equalsIgnoreCase("DOUBLE")) {
            size = 8;
            b = new byte[8];
            for (i = 0; i < length; i++) {
                pos = (int) getcellnumber(points[i][0], points[i][1]);
                if (pos >= 0) {
                    afile.seek(pos * size);
                    afile.read(b);
                    ByteBuffer bb = ByteBuffer.wrap(b);
                    if (byteorderLSB) {
                        bb.order(ByteOrder.LITTLE_ENDIAN);
                    }
                    ret[i] = (float) bb.getDouble();

                    //ret[i] = afile.readFloat();
                } else {
                    ret[i] = Float.NaN;
                }
            }
        } else {
            logger.error("datatype not supported in Grid.getValues: " + datatype);
            // / should not happen; catch anyway...
            for (i = 0; i < length; i++) {
                ret[i] = Float.NaN;
            }
        }
        //replace not a number
        for (i = 0; i < length; i++) {
            if ((float) ret[i] == (float) nodatavalue) {
                ret[i] = Float.NaN;
            } else {
                ret[i] *= rescale;
            }
        }
    } catch (Exception e) {
        logger.error("error getting grid file values", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    return ret;
}

From source file:com.portfolio.rest.RestServicePortfolio.java

@Path("/portfolios/portfolio/{portfolio-id}")
@GET//w  w w.j  a v a 2 s  .  c o  m
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "application/zip",
        MediaType.APPLICATION_OCTET_STREAM })
public Object getPortfolio(@CookieParam("user") String user, @CookieParam("credential") String token,
        @QueryParam("group") int groupId, @PathParam("portfolio-id") String portfolioUuid,
        @Context ServletConfig sc, @Context HttpServletRequest httpServletRequest,
        @HeaderParam("Accept") String accept, @QueryParam("user") Integer userId,
        @QueryParam("group") Integer group, @QueryParam("resources") String resource,
        @QueryParam("files") String files, @QueryParam("export") String export,
        @QueryParam("lang") String lang) {
    UserInfo ui = checkCredential(httpServletRequest, user, token, null);

    Response response = null;
    try {
        String portfolio = dataProvider.getPortfolio(new MimeType("text/xml"), portfolioUuid, ui.userId, 0,
                this.label, resource, "", ui.subId).toString();

        if ("faux".equals(portfolio)) {
            response = Response.status(403).build();
        }

        if (response == null) {
            Date time = new Date();
            Document doc = DomUtils.xmlString2Document(portfolio, new StringBuffer());
            NodeList codes = doc.getDocumentElement().getElementsByTagName("code");
            // Le premier c'est celui du root
            Node codenode = codes.item(0);
            String code = "";
            if (codenode != null)
                code = codenode.getTextContent();

            if (export != null) {
                response = Response.ok(portfolio).header("content-disposition",
                        "attachment; filename = \"" + code + "-" + time + ".xml\"").build();
            } else if (resource != null && files != null) {
                //// Cas du renvoi d'un ZIP

                /// Temp file in temp directory
                File tempDir = new File(System.getProperty("java.io.tmpdir", null));
                File tempZip = File.createTempFile(portfolioUuid, ".zip", tempDir);

                FileOutputStream fos = new FileOutputStream(tempZip);
                ZipOutputStream zos = new ZipOutputStream(fos);
                //               BufferedOutputStream bos = new BufferedOutputStream(zos);

                /// zos.setComment("Some comment");

                /// Write xml file to zip
                ZipEntry ze = new ZipEntry(portfolioUuid + ".xml");
                zos.putNextEntry(ze);

                byte[] bytes = portfolio.getBytes("UTF-8");
                zos.write(bytes);

                zos.closeEntry();

                /// Find all fileid/filename
                XPath xPath = XPathFactory.newInstance().newXPath();
                String filterRes = "//asmResource/fileid";
                NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

                /// Direct link to data
                // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";

                /*
                String langatt = "";
                if( lang != null )
                   langatt = "?lang="+lang;
                else
                   langatt = "?lang=fr";
                //*/

                /// Fetch all files
                for (int i = 0; i < nodelist.getLength(); ++i) {
                    Node res = nodelist.item(i);
                    Node p = res.getParentNode(); // resource -> container
                    Node gp = p.getParentNode(); // container -> context
                    Node uuidNode = gp.getAttributes().getNamedItem("id");
                    String uuid = uuidNode.getTextContent();

                    String filterName = "./filename[@lang and text()]";
                    NodeList textList = (NodeList) xPath.compile(filterName).evaluate(p,
                            XPathConstants.NODESET);
                    String filename = "";
                    if (textList.getLength() != 0) {
                        Element fileNode = (Element) textList.item(0);
                        filename = fileNode.getTextContent();
                        lang = fileNode.getAttribute("lang");
                        if ("".equals(lang))
                            lang = "fr";
                    }

                    String servlet = httpServletRequest.getRequestURI();
                    servlet = servlet.substring(0, servlet.indexOf("/", 7));
                    String server = httpServletRequest.getServerName();
                    int port = httpServletRequest.getServerPort();
                    //                  "http://"+ server + /resources/resource/file/ uuid ? lang= size=
                    // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";
                    String url = "http://" + server + ":" + port + servlet + "/resources/resource/file/" + uuid
                            + "?lang=" + lang;
                    HttpGet get = new HttpGet(url);

                    // Transfer sessionid so that local request still get security checked
                    HttpSession session = httpServletRequest.getSession(true);
                    get.addHeader("Cookie", "JSESSIONID=" + session.getId());

                    // Send request
                    CloseableHttpClient client = HttpClients.createDefault();
                    CloseableHttpResponse ret = client.execute(get);
                    HttpEntity entity = ret.getEntity();

                    // Put specific name for later recovery
                    if ("".equals(filename))
                        continue;
                    int lastDot = filename.lastIndexOf(".");
                    if (lastDot < 0)
                        lastDot = 0;
                    String filenameext = filename.substring(0); /// find extension
                    int extindex = filenameext.lastIndexOf(".");
                    filenameext = uuid + "_" + lang + filenameext.substring(extindex);

                    // Save it to zip file
                    //                  int length = (int) entity.getContentLength();
                    InputStream content = entity.getContent();

                    //                  BufferedInputStream bis = new BufferedInputStream(entity.getContent());

                    ze = new ZipEntry(filenameext);
                    try {
                        int totalread = 0;
                        zos.putNextEntry(ze);
                        int inByte;
                        byte[] buf = new byte[4096];
                        //                     zos.write(bytes,0,inByte);
                        while ((inByte = content.read(buf)) != -1) {
                            totalread += inByte;
                            zos.write(buf, 0, inByte);
                        }
                        System.out.println("FILE: " + filenameext + " -> " + totalread);
                        content.close();
                        //                     bis.close();
                        zos.closeEntry();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    EntityUtils.consume(entity);
                    ret.close();
                    client.close();
                }

                zos.close();
                fos.close();

                /// Return zip file
                RandomAccessFile f = new RandomAccessFile(tempZip.getAbsoluteFile(), "r");
                byte[] b = new byte[(int) f.length()];
                f.read(b);
                f.close();

                response = Response.ok(b, MediaType.APPLICATION_OCTET_STREAM)
                        .header("content-disposition", "attachment; filename = \"" + code + "-" + time + ".zip")
                        .build();

                // Temp file cleanup
                tempZip.delete();
            } else {
                //try { this.userId = userId; } catch(Exception ex) { this.userId = -1; };
                //              String returnValue = dataProvider.getPortfolio(new MimeType("text/xml"),portfolioUuid,this.userId, this.groupId, this.label, resource, files).toString();
                if (portfolio.equals("faux")) {

                    throw new RestWebApplicationException(Status.FORBIDDEN,
                            "Vous n'avez pas les droits necessaires");
                }

                if (accept.equals(MediaType.APPLICATION_JSON)) {
                    portfolio = XML.toJSONObject(portfolio).toString();
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_JSON).build();
                } else
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_XML).build();

                logRestRequest(httpServletRequest, null, portfolio, Status.OK.getStatusCode());
            }
        }
    } catch (RestWebApplicationException ex) {
        throw new RestWebApplicationException(Status.FORBIDDEN, ex.getResponse().getEntity().toString());
    } catch (SQLException ex) {
        logRestRequest(httpServletRequest, null, "Portfolio " + portfolioUuid + " not found",
                Status.NOT_FOUND.getStatusCode());

        throw new RestWebApplicationException(Status.NOT_FOUND, "Portfolio " + portfolioUuid + " not found");
    } catch (Exception ex) {
        ex.printStackTrace();
        logRestRequest(httpServletRequest, null, ex.getMessage() + "\n\n" + ex.getStackTrace(),
                Status.INTERNAL_SERVER_ERROR.getStatusCode());

        throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    } finally {
        if (dataProvider != null)
            dataProvider.disconnect();
    }

    return response;
}