Example usage for java.io FileNotFoundException toString

List of usage examples for java.io FileNotFoundException toString

Introduction

In this page you can find the example usage for java.io FileNotFoundException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:eu.sisob.uma.extractors.adhoc.websearchers.WebSearchersExtractorCommons.java

/**
 *
 * @param input_file/*from   w  ww  .  java 2  s  . c  om*/
 * @param output_file
 * @param notfound_output_file
 * @param error_sw
 */
public void scrap_duckduckgo(File input_file, File output_file, File notfound_output_file,
        StringWriter error_sw) {
    CSVReader reader = null;
    try {
        reader = new CSVReader(new FileReader(input_file), CSV_SEPARATOR);
    } catch (FileNotFoundException ex) {
        Logger.getRootLogger().error("Error reading " + input_file.getName() + " - " + ex.toString());
        return;
    }

    int idStaffIdentifier = -1;
    int idName = -1;
    int idFirstName = -1;
    int idLastName = -1;
    int idInitials = -1;
    int idSubject = -1;
    int idInstitutionName = -1;
    int idWebAddress = -1;

    Logger.getRootLogger().info("Going to search researchers using duckduckgo");

    String[] nextLine;
    try {
        if ((nextLine = reader.readNext()) != null) {
            //Locate indexes            
            //Locate indexes                        
            for (int i = 0; i < nextLine.length; i++) {
                String column_name = nextLine[i];
                if (column_name.equals(FileFormatConversor.CSV_COL_ID))
                    idStaffIdentifier = i;
                else if (column_name.equals(FileFormatConversor.CSV_COL_NAME))
                    idName = i;
                else if (column_name.equals(FileFormatConversor.CSV_COL_FIRSTNAME))
                    idFirstName = i;
                else if (column_name.equals(FileFormatConversor.CSV_COL_LASTNAME))
                    idLastName = i;
                else if (column_name.equals(FileFormatConversor.CSV_COL_INITIALS))
                    idInitials = i;
                else if (column_name.equals(FileFormatConversor.CSV_COL_SUBJECT))
                    idSubject = i;
                else if (column_name.equals(FileFormatConversor.CSV_COL_INSTITUTION_NAME))
                    idInstitutionName = i;
                else if (column_name.equals(FileFormatConversor.CSV_COL_INSTITUTION_URL))
                    idWebAddress = i;
            }
        }
    } catch (IOException ex) {
        String error_msg = "Error reading headers of " + input_file.getName();
        Logger.getRootLogger().error(error_msg + " - " + ex.toString());
        if (error_sw != null)
            error_sw.append(error_msg + "\r\n");

        return;
    }

    Logger.getRootLogger().info("Headers info of result file writed");

    if (idLastName != -1 && idInitials != -1 && idStaffIdentifier != -1 && idWebAddress != -1
            && idSubject != -1) {
        try {
            String header = "";
            header += "\"" + FileFormatConversor.CSV_COL_ID + "\";";
            header += "\"" + FileFormatConversor.CSV_COL_LASTNAME + "\";";
            header += "\"" + FileFormatConversor.CSV_COL_INITIALS + "\";";
            if (idFirstName != -1)
                header += "\"" + FileFormatConversor.CSV_COL_FIRSTNAME + "\";";
            if (idName != -1)
                header += "\"" + FileFormatConversor.CSV_COL_NAME + "\";";
            header += "\"" + FileFormatConversor.CSV_COL_RESEARCHER_PAGE_URL + "\";";
            header += "\"" + FileFormatConversor.CSV_COL_RESEARCHER_PAGE_EXT + "\";";
            header += "\"" + FileFormatConversor.CSV_COL_RESEARCHER_PAGE_TYPE + "\";";
            header += "\"" + FileFormatConversor.CSV_COL_SCORE_URL + "\";";
            header += "\r\n";
            FileUtils.write(output_file, header, "UTF-8", false);

            header = "";
            header += "\"" + FileFormatConversor.CSV_COL_ID + "\";";
            header += "\"" + FileFormatConversor.CSV_COL_LASTNAME + "\";";
            header += "\"" + FileFormatConversor.CSV_COL_INITIALS + "\";";
            if (idFirstName != -1)
                header += "\"" + FileFormatConversor.CSV_COL_FIRSTNAME + "\";";
            if (idName != -1)
                header += "\"" + FileFormatConversor.CSV_COL_NAME + "\";";
            if (idInstitutionName != -1)
                header += "\"" + FileFormatConversor.CSV_COL_INSTITUTION_NAME + "\";";
            header += "\"" + FileFormatConversor.CSV_COL_INSTITUTION_URL + "\";";
            header += "\"" + FileFormatConversor.CSV_COL_SCORE_URL + "\";";
            header += "\r\n";
            FileUtils.write(notfound_output_file, header, "UTF-8", false);

        } catch (IOException ex) {
            Logger.getLogger("root").error(ex.toString());
            error_sw.append("Error creating output files\r\n");
        }

        try {
            while ((nextLine = reader.readNext()) != null) {
                nextLine[idLastName] = nextLine[idLastName].replaceAll("[^a-zA-Z]", " ").toLowerCase();
                nextLine[idInitials] = nextLine[idInitials].replaceAll("[^a-zA-Z]", " ").toLowerCase();
                if (idFirstName != -1)
                    nextLine[idFirstName] = nextLine[idFirstName].replaceAll("[^a-zA-Z]", " ").toLowerCase();
                if (idName != -1)
                    nextLine[idName] = nextLine[idName].replaceAll("[^a-zA-Z]", " ").toLowerCase();

                String expression = "";

                String aux = nextLine[idLastName];
                expression += aux + " AND ";

                if (idFirstName != -1) {
                    String ss[] = nextLine[idFirstName].split(" ");
                    for (String s : ss) {
                        if (s.length() > 1)
                            expression += s + " AND ";
                    }
                    expression = expression.substring(0, expression.length() - 5);
                } else {
                    String ss[] = nextLine[idInitials].split(" ");
                    for (String s : ss) {
                        expression += s + " AND ";
                    }
                    //expression += aux + " ";
                    expression = expression.substring(0, expression.length() - 5);
                }

                String final_result = get_result(nextLine, idStaffIdentifier, idName, idFirstName, idLastName,
                        idInitials, idSubject, idInstitutionName, idWebAddress, expression, null);

                if (!final_result.equals("")) {
                    try {
                        FileUtils.write(output_file, final_result, "UTF-8", true);
                        Logger.getRootLogger().info("Writed results");
                    } catch (IOException ex) {
                        Logger.getLogger("root").error(ex.toString());
                    }
                } else {
                    final_result = "";
                    final_result += "\"" + nextLine[idStaffIdentifier] + "\";";
                    final_result += "\"" + nextLine[idLastName] + "\";";
                    final_result += "\"" + nextLine[idInitials] + "\";";
                    if (idFirstName != -1)
                        final_result += "\"" + nextLine[idFirstName] + "\";";
                    if (idName != -1)
                        final_result += "\"" + nextLine[idName] + "\";";
                    if (idInstitutionName != -1)
                        final_result += "\"" + nextLine[idInstitutionName] + "\";";
                    final_result += "\"" + nextLine[idWebAddress] + "\"";
                    final_result += "\r\n";

                    try {
                        Logger.getRootLogger().info("No results");
                        FileUtils.write(notfound_output_file, final_result, "UTF-8", true);
                    } catch (IOException ex) {
                        Logger.getLogger("root").error(ex.toString());
                    }
                }
            }

            reader.close();

            Logger.getRootLogger().info("Researchers data info of results file writed");

        } catch (Exception ex) {
            String error_msg = "Error extracting web researchers from DuckDuckGo " + input_file.getName();
            Logger.getRootLogger().error(error_msg + " - " + ex.toString());
            if (error_sw != null)
                error_sw.append(error_msg + "\r\n");
            return;
        }
    }
}

From source file:eu.planets_project.tb.impl.system.ServiceExecutionHandlerImpl.java

/**
 * In the case of a value calls (e.g. as base64 data transmission) this method
 * extracts and decodes the data to a local file and provides a file reference
 * An output file type (e.g. doc) can be specified, which will be used as the result's file type
 * @return/* ww w .  ja v a  2 s .  com*/
 */
@SuppressWarnings("unused")
private Map<String, String> createFilesFromBase64Result(Map<String, String> migrationResults,
        String outputFileType) {
    Map<String, String> ret = new HashMap<String, String>();
    if ((migrationResults == null) || (migrationResults.size() <= 0))
        return ret;

    Iterator<String> itKeys = migrationResults.keySet().iterator();
    while (itKeys.hasNext()) {
        String key = itKeys.next();
        String sBase64value = migrationResults.get(key);

        //decode the base64 String
        byte[] b = DataHandlerImpl.decodeToByteArray(sBase64value);
        try {
            //get the file's new name (same as it's input file) - input and output should have the same key
            String sInputFileName = new File(this.hmInputFiles.get(key)).getName();
            String sOutputFileName = "";
            char delimP = '.';
            int p = sInputFileName.lastIndexOf(delimP);
            String origInputFileMathNr = sInputFileName.substring(0, p);
            sOutputFileName = origInputFileMathNr + "." + outputFileType;

            //now copy the byteArray into the file-location
            String ref = dh.storeBytearray(b, sOutputFileName).toString();

            //finally update the returned migration output reference
            ret.put(key, ref);

        } catch (FileNotFoundException e) {
            System.out.println(e.toString());
        } catch (IOException e) {
            System.out.println(e.toString());
        }
    }

    return ret;
}

From source file:com.opentransport.rdfmapper.nmbs.ScrapeTrip.java

private GtfsRealtime.FeedEntity.Builder parseJson(int identifier, String fileName, boolean canceled,
        String trainName) {//from   ww w  .jav  a  2s.  c  om
    GtfsRealtime.FeedEntity.Builder feedEntity = GtfsRealtime.FeedEntity.newBuilder();
    feedEntity.setId(Integer.toString(identifier));
    feedEntity.setIsDeleted(false);

    //Data that doesnt Update
    GtfsRealtime.TripUpdate.Builder tripUpdate = GtfsRealtime.TripUpdate.newBuilder();
    GtfsRealtime.VehicleDescriptor.Builder vehicleDescription = GtfsRealtime.VehicleDescriptor.newBuilder();
    GtfsRealtime.TripDescriptor.Builder tripDescription = GtfsRealtime.TripDescriptor.newBuilder();
    GtfsRealtime.TripUpdate.StopTimeUpdate.Builder stopTimeUpdate = GtfsRealtime.TripUpdate.StopTimeUpdate
            .newBuilder();

    //Each StopTime Update contains StopTimeEvents with the stop Arrival and Departure Time 
    GtfsRealtime.TripUpdate.StopTimeEvent.Builder stopTimeArrival = GtfsRealtime.TripUpdate.StopTimeEvent
            .newBuilder();
    GtfsRealtime.TripUpdate.StopTimeEvent.Builder stopTimeDeparture = GtfsRealtime.TripUpdate.StopTimeEvent
            .newBuilder();

    JSONParser parser = new JSONParser();
    try {
        FileReader fr = new FileReader(fileName);
        JSONObject json = (JSONObject) parser.parse(fr);
        String trainId = (String) json.get("vehicle");
        //Setting the VehicleData
        String routeId = trainName;
        vehicleDescription.setId(routeId);
        vehicleDescription.setLicensePlate(trainId);

        //Handling Departure Date
        String unixSeconds = (String) json.get("timestamp");
        Long unixSec = Long.parseLong(unixSeconds);

        Date date = new Date(unixSec * 1000L); // *1000 is to convert seconds to milliseconds
        SimpleDateFormat sdfStartDate = new SimpleDateFormat("yyyyMMdd"); // the format of your date
        sdfStartDate.setTimeZone(TimeZone.getTimeZone("GMT+2")); // give a timezone reference for formating
        SimpleDateFormat sdfStartTimeHour = new SimpleDateFormat("HH:mm:ss");

        String formattedDepartureDate = sdfStartDate.format(date);
        // String formattedDepartureHour = sdfStartTimeHour.format(date);

        // Setting the Trip Description
        // tripDescription.setStartTime(formattedDepartureHour);
        //YYYYMMDD format
        tripDescription.setStartDate(formattedDepartureDate);
        tripDescription.setRouteId(routeId);

        String tripId = tr.getTripIdFromRouteId(routeId, cdr);
        tripDescription.setTripId(tripId);

        //Get Information about stops
        JSONObject rootStop = (JSONObject) json.get("stops");
        JSONArray stops = (JSONArray) rootStop.get("stop");
        String arrivalDelay = "0";
        String departureDelay = "0";
        int maxDelay = 0;

        String firstStopName = "";
        String lastStopName = "";

        boolean wholeTripCanceled = true; // True when all stoptimes since now are canceled

        for (int i = 0; i < stops.size(); i++) {
            //Information about the stops
            JSONObject stop = (JSONObject) stops.get(i);
            // String stopSeq = (String) stop.get("id");

            stopTimeUpdate.setStopSequence(i);
            try {

                JSONObject station = (JSONObject) stop.get("stationinfo");
                // tripDescription.setRouteId((String) station.get("@id"));

                String stopId = (String) station.get("id");
                stopId = stopId.replaceFirst("[^0-9]+", "") + ":";
                stopId = stopId.substring(2); // remove first '00'
                if (!stop.get("platform").equals("") && !stop.get("platform").equals("?")) {
                    stopId += stop.get("platform");
                } else {
                    stopId += "0";
                }

                stopTimeUpdate.setStopId(stopId);

                // Constructing route long name from first and last stop
                if (i == 0) {
                    firstStopName = (String) station.get("standardname");
                } else if (i == stops.size() - 1) {
                    lastStopName = (String) station.get("standardname");
                }

            } catch (Exception e) {
                errorWriter.writeError(e.toString() + fileName);
                System.out.println(fileName);
                System.out.println(e);
            }

            // delays
            arrivalDelay = (String) stop.get("arrivalDelay");
            departureDelay = (String) stop.get("departureDelay");

            int arrivalDelayInt = Integer.parseInt(arrivalDelay);
            int departureDelayInt = Integer.parseInt(departureDelay);

            if (maxDelay < arrivalDelayInt) {
                maxDelay = arrivalDelayInt;
            }
            if (maxDelay < departureDelayInt) {
                maxDelay = departureDelayInt;
            }

            long now = System.currentTimeMillis();

            //Calculate arrival times
            long scheduledArrivalTimeUnixSeconds = Long.parseLong((String) stop.get("scheduledArrivalTime"));
            java.util.Date scheduledArrivalTime = new java.util.Date(
                    (long) scheduledArrivalTimeUnixSeconds * 1000);
            // add arrivalDelay to get real arrival time
            long arrivalTimeMillis = (DateUtils.addSeconds(scheduledArrivalTime, arrivalDelayInt)).getTime();

            //Calculate departure times
            long scheduledDepartureTimeUnixSeconds = Long
                    .parseLong((String) stop.get("scheduledDepartureTime"));
            java.util.Date scheduledDepartureTime = new java.util.Date(
                    (long) scheduledDepartureTimeUnixSeconds * 1000);
            // add departureDelay to get real departure time
            long departureTimeMillis = (DateUtils.addSeconds(scheduledDepartureTime, departureDelayInt))
                    .getTime();

            // If stoptime is (partially) canceled
            String isCanceled = (String) stop.get("canceled");
            if (!isCanceled.equals("0")) {
                // Set ScheduleRelationship of stoptime to SKIPPED
                stopTimeUpdate.setScheduleRelationship(
                        GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SKIPPED);
            } else {
                // If a current or future stoptime isn't canceled, the whole trip isn't canceled
                if (wholeTripCanceled && arrivalTimeMillis >= now) {
                    wholeTripCanceled = false;
                }
            }

            // Set Arrival in the object
            stopTimeArrival.setDelay(arrivalDelayInt);
            //    setTime takes parameter in seconds
            stopTimeArrival.setTime(arrivalTimeMillis / 1000);
            stopTimeUpdate.setArrival(stopTimeArrival);
            // Do the same for departure
            stopTimeDeparture.setDelay(Integer.parseInt(departureDelay));
            //    setTime takes parameter in seconds
            stopTimeDeparture.setTime(departureTimeMillis / 1000);
            stopTimeUpdate.setDeparture(stopTimeDeparture);
            tripUpdate.addStopTimeUpdate(stopTimeUpdate);
        }

        tripDescription.setScheduleRelationship(GtfsRealtime.TripDescriptor.ScheduleRelationship.SCHEDULED);
        if (wholeTripCanceled) {
            // Can be partially canceled
            tripDescription.setScheduleRelationship(GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED);
        }

        String route_long_name = firstStopName + " - " + lastStopName;
        vehicleDescription.setLabel(route_long_name);
        tripUpdate.setTrip(tripDescription);
        tripUpdate.setVehicle(vehicleDescription);
        tripUpdate.setDelay(maxDelay);
        feedEntity.setTripUpdate(tripUpdate);

        fr.close();
    } catch (FileNotFoundException ex) {
        System.out.println(ex);
        errorWriter.writeError(ex.toString());

    } catch (IOException ex) {
        System.out.println("IO exception" + ex);

    } catch (ParseException ex) {
        System.out.println("Parse exception " + ex + " " + fileName);
    } catch (NullPointerException npe) {
        System.out.println(npe.toString());
    }

    return feedEntity;
}

From source file:tweetcrawler.Worker.java

private void workOnFile(File f) {
    String line;/*from   ww w . j av a 2 s . c  o m*/
    boolean proceed = false;
    synchronized (Worker.processedFiles) {
        if (!processedFiles.containsKey(f.getAbsolutePath())) {
            processedFiles.put(f.getAbsolutePath(), "started");
            proceed = true;
        }
    }
    if (proceed) {
        try {
            BufferedReader br = getBufferedReaderForCompressedFile(f.getAbsolutePath());
            while ((line = br.readLine()) != null) {
                JSONObject js = new JSONObject(line);
                if (js.has("text")) {
                    line = js.getString("text").toLowerCase();
                    if (StringUtils.contains(line, TweetCrawler.productName)
                            && StringUtils.containsAny(line, TweetCrawler.keywords)
                            && !StringUtils.containsAny(line, TweetCrawler.forbiddenWords)) {
                        for (int i = 0; i < TweetCrawler.keywords.length; i++) {
                            if (StringUtils.contains(line, TweetCrawler.keywords[i])) {
                                TweetCrawler.appendContents(i, stripJSON(js));
                            }
                        }
                    }
                }
            }

            synchronized (Worker.processedFiles) {
                processedFiles.put(f.getAbsolutePath(), "done by " + this.id);
                System.out.println("Thread " + this.id + "\tdid " + f.getPath() + " -- "
                        + 100 * ((double) TweetCrawler.numFilesProcessed++ / TweetCrawler.numFiles)
                        + "% complete");
            }
        } catch (FileNotFoundException ex) {
            System.out.println("File not found: " + f.getAbsolutePath());
        } catch (CompressorException ex) {
            System.out.println("Compressor exception: " + ex.getMessage());
        } catch (IOException ex) {
            System.out.println("Problem reading the file: " + f.getAbsolutePath());
        } catch (JSONException ex) {
            System.out.println("Exception: " + ex.toString());
            TweetCrawler.errOut(id, "Exception:" + ex.toString());
        } catch (ArrayIndexOutOfBoundsException ex) {
            System.out.println("probably corrupted file at " + f.getAbsolutePath() + "Exception:" + ex);
            TweetCrawler.errOut(id,
                    "probably corrupted file at " + f.getAbsolutePath() + "Exception:" + ex.toString());
        } catch (RuntimeException ex) {
            System.out.println("Exception: " + ex.toString());
            TweetCrawler.errOut(id, "Exception:" + ex.toString());
        }
    }
}

From source file:org.opencms.setup.xml.CmsSetupXmlHelper.java

/**
 * Writes the given file back to disk.<p>
 * //from   w  w  w .  java  2  s.c om
 * @param xmlFilename the xml config file (could be relative to the base path)
 * 
 * @throws CmsXmlException if something wrong while writing 
 */
public void write(String xmlFilename) throws CmsXmlException {

    // try to get it from the cache
    Document document = m_cache.get(xmlFilename);

    if (document != null) {
        try {
            OutputStream out = new FileOutputStream(getFile(xmlFilename));
            CmsXmlUtils.marshal(document, out, CmsEncoder.ENCODING_UTF_8);
        } catch (FileNotFoundException e) {
            throw new CmsXmlException(new CmsMessageContainer(null, e.toString()));
        }
    }
}

From source file:org.opencms.setup.xml.CmsSetupXmlHelper.java

/**
 * Returns the document for the given filename.<p>
 * It can be new read or come from the document cache.<p>
 * //from   ww w.  j  av  a 2  s.c om
 * @param xmlFilename the filename to read
 * 
 * @return the document for the given filename
 * 
 * @throws CmsXmlException if something goes wrong while reading 
 */
public Document getDocument(String xmlFilename) throws CmsXmlException {

    // try to get it from the cache
    Document document = m_cache.get(xmlFilename);

    if (document == null) {
        try {
            document = CmsXmlUtils.unmarshalHelper(new InputSource(new FileReader(getFile(xmlFilename))),
                    NO_ENTITY_RESOLVER);
        } catch (FileNotFoundException e) {
            throw new CmsXmlException(new CmsMessageContainer(null, e.toString()));
        }
        // cache the doc
        m_cache.put(xmlFilename, document);
    }
    return document;
}

From source file:com.vkassin.mtrade.Common.java

public static void saveAccountDetails() {

    FileOutputStream fos;/*from w ww . j a v  a 2  s .c  om*/
    try {

        fos = app_ctx.openFileOutput(ACCOUNT_FNAME, Context.MODE_PRIVATE);
        ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(myaccount);
        os.close();
        fos.close();
        Log.i(TAG, "saved username: " + myaccount.get("name") + " password: " + myaccount.get("password")
                + " keypassword: " + myaccount.get("keypassword"));
    } catch (FileNotFoundException e) {

        Toast.makeText(app_ctx, "  ? " + e.toString(), Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    } catch (IOException e) {

        Toast.makeText(app_ctx, "  ?: " + e.toString(), Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }

}

From source file:inc.bait.jubilee.ui.fragments.ContactsListFragment.java

private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) {
    if (!isAdded() || getActivity() == null) {
        return null;
    }/*from ww  w.  j a  va  2s  .c  o  m*/
    AssetFileDescriptor afd = null;
    try {
        Uri thumbUri;
        if (ApiHelper.hasHoneycomb()) {
            thumbUri = Uri.parse(photoData);
        } else {
            final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData);
            thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
        }
        afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r");
        FileDescriptor fileDescriptor = afd.getFileDescriptor();

        if (fileDescriptor != null) {
            return ImgLoader.decodeSampledBitmapFromDescriptor(fileDescriptor, imageSize, imageSize);
        }
    } catch (FileNotFoundException e) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData + ": " + e.toString());
        }
    } finally {
        if (afd != null) {
            try {
                afd.close();
            } catch (IOException e) {
            }
        }
    }
    return null;
}

From source file:com.vkassin.mtrade.Common.java

public static void saveFavrList() {

    Log.i(TAG, "saveFavrList()");
    FileOutputStream fos;/*w w  w .  ja va  2  s .  c o m*/
    try {

        fos = app_ctx.openFileOutput(FLIST_FNAME, Context.MODE_PRIVATE);
        ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(favrList);
        os.close();
        fos.close();

    } catch (FileNotFoundException e) {

        Toast.makeText(app_ctx, "  ? " + e.toString(), Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    } catch (IOException e) {

        Toast.makeText(app_ctx, "  ?: " + e.toString(), Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }

    // Toast.makeText(app_ctx, " ?? ?",
    // Toast.LENGTH_SHORT).show();

}

From source file:rn.beleg.protocol.Protocol.java

/**
 * Encode the file/*  w ww . j av a  2  s.  co m*/
 *
 * @return Return an iterable byte[] could sent
 */
public Iterable<byte[]> encode() {
    LinkedList<byte[]> list = new LinkedList<byte[]>();
    byte[] data = new byte[(int) file.length()];
    byte[] session = ByteUtilities.random(2);

    try {
        FileInputStream in = new FileInputStream(this.file);
        //noinspection ResultOfMethodCallIgnored
        in.read(data);
        in.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        output.error("File " + file.getAbsolutePath() + " not found.");
        System.exit(1);
    } catch (IOException e) {
        output.error(e.toString());
        System.exit(1);
    } finally {
        // Create first package
        FirstPackage firstPackage = null;
        try {
            firstPackage = new FirstPackage(session, 0, "Start".getBytes("ASCII"), file.length(),
                    file.getName().length(), file.getName());

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            System.exit(1);
        }

        output.info(String.format("Session        %s", ByteUtilities.byteToHex(session)));
        output.info(String.format("FileNameLength %s", firstPackage.getFileNameLength()));
        output.info(String.format("Filename       %s", firstPackage.getFileName()));
        output.info(String.format("FileLength     %s", firstPackage.getFileLength()));

        list.add(firstPackage.serialize());

        // Create data packages
        int step = 1;
        for (int start = 0; start < data.length; start += DATA_PACKAGE_SIZE) {
            int end = start + DATA_PACKAGE_SIZE;
            int packageId = step % 2;
            DataPackage dataPackage;
            if (end < data.length) {
                // normal package
                byte[] packageData = Arrays.copyOfRange(data, start, end);
                dataPackage = new DataPackage(session, packageId, packageData);
            } else {
                byte[] packageData = Arrays.copyOfRange(data, start, data.length);
                dataPackage = new DataPackage(session, packageId, packageData, CRC32.calc(data));
                // last package got crc, check length with crc
                if (dataPackage.packageSize() >= DATA_PACKAGE_SIZE) {
                    // package to big, split again
                    byte[] tmp = Arrays.copyOfRange(packageData, 0, packageData.length / 2);
                    DataPackage dtmp = new DataPackage(session, packageId, tmp);
                    list.add(dtmp.serialize());

                    tmp = Arrays.copyOfRange(packageData, packageData.length / 2, packageData.length);
                    dataPackage = new DataPackage(session, packageId, tmp, CRC32.calc(data));
                }
            }
            output.info(String.format("Data part package size %s", dataPackage.getData().length));
            list.add(dataPackage.serialize());
            step++;
        }
    }

    return list;
}