Example usage for java.lang NumberFormatException getCause

List of usage examples for java.lang NumberFormatException getCause

Introduction

In this page you can find the example usage for java.lang NumberFormatException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:org.ph.commonjoiner.CommonJoiner.java

public static void main(String[] args) {

    try {/*ww  w . j  a va2 s. c om*/
        Options options = new Options();
        options.addOption("f", true, "archivo de entrada inicial.");
        options.addOption("g", true, "archivo de entrada a comparar.");
        options.addOption("o", true, "archivo de salida (omitir para salida por pantalla).");
        options.addOption("h", false, "muestra esta ayuda.");
        options.addOption("l", false, "muestra la licencia GPL v.3 al completo.");
        options.addOption("s", false, "muestra estadisticas al finalizar el proceso.");
        options.addOption("v", false, "muestra la version del software.");

        options.addOption("c", true,
                "copia los archivos concidentes con los cargados en la lista mediante -f a la carpeta indicada.");

        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);

        if ((args.length == 1)) {
            if (cmd.hasOption("l"))
                System.out.println(GNULicense.FULLLICENSE);
            if (cmd.hasOption("v"))
                System.out.println(InfoCommonJoiner.INFO);
            if (cmd.hasOption("h"))
                printSmallHelp(options);

        } else {
            String entrada1, salida;

            // <editor-fold defaultstate="expanded" desc=" opciones de comparacin de contenido de dos archivos ">
            if (cmd.hasOption("f") && cmd.hasOption("g") && cmd.hasOption("o")) {
                entrada1 = cmd.getOptionValue("f");
                String entrada2 = cmd.getOptionValue("g");
                salida = cmd.getOptionValue("o");

                File fEntrada1 = new File(entrada1);
                File fEntrada2 = new File(entrada2);
                File fSalida = new File(salida);

                boolean okEntrada1 = fEntrada1.exists();
                boolean okEntrada2 = fEntrada2.exists();
                boolean okSalida = !(fSalida.exists());

                if (okEntrada1 && okEntrada2) {
                    String thisLine = null;
                    HashSet nums1 = new HashSet<Integer>();
                    ArrayList numComun = new ArrayList<Integer>();

                    System.out.println(InfoCommonJoiner.INTRO);

                    try {
                        Timer tF1 = new Timer("Inicio lectura archivo " + entrada1);
                        BufferedReader br1 = new BufferedReader(new FileReader(fEntrada1));
                        while ((thisLine = br1.readLine()) != null) {
                            nums1.add(Integer.parseInt(thisLine));
                        }
                        tF1.setT1();
                        br1.close();
                        System.out
                                .println("Nmero de elementos nicos en '" + entrada1 + "': " + nums1.size());

                        Timer tF2 = new Timer("Inicio lectura archivo " + entrada2);
                        long readedLines = 0;
                        BufferedReader br2 = new BufferedReader(new FileReader(fEntrada2));
                        while ((thisLine = br2.readLine()) != null) {
                            readedLines++;
                            if (!nums1.add(Integer.parseInt(thisLine))) {
                                numComun.add(Integer.parseInt(thisLine));
                            }
                        }
                        tF2.setT1();
                        br2.close();
                        System.out
                                .println("Nmero de elementos ledos en '" + entrada2 + "': " + readedLines);

                        Timer tF3 = new Timer("Inicio escritura de archivo");
                        if (!okSalida) {
                            System.out.println("Nmero de elementos comunes: " + numComun.size());
                            System.out.println("" + Arrays.toString(numComun.toArray()));
                        } else {
                            // escritura del archivo
                            BufferedWriter bw = new BufferedWriter(new FileWriter(fSalida));
                            // ordenamiento de los resultados
                            Collections.sort(numComun);

                            for (Object i : numComun) {
                                bw.write(i.toString());
                                bw.newLine();
                            }
                            bw.close();
                            tF3.setT1();

                            System.out.println("Nmero de elementos comunes escritos: " + numComun.size());
                        }

                        if (cmd.hasOption("s")) {
                            System.out.println("\nESTADISTICAS");
                            System.out.println("  Tiempo de operacin de lectura de archivo " + entrada1 + ": "
                                    + tF1.getEllapsedTime() + "ns");
                            System.out.println("  Tiempo de operacin de lectura de archivo " + entrada2 + ": "
                                    + tF2.getEllapsedTime() + "ns");
                            if (okSalida) {
                                System.out.println("  Tiempo de operacin de escritura de archivo " + salida
                                        + ": " + tF3.getEllapsedTime() + "ns");
                            }
                            long tiempoTotal = tF1.getEllapsedTime() + tF2.getEllapsedTime()
                                    + ((okSalida) ? tF3.getEllapsedTime() : 0);
                            System.out
                                    .println("  Tiempo total de las operaciones " + ": " + tiempoTotal + "ms");
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            // </editor-fold>

            if (cmd.hasOption("c") && cmd.hasOption("f")) {
                boolean copiar = false;
                entrada1 = cmd.getOptionValue("f");
                salida = cmd.getOptionValue("c");
                File archivoEntrada = new File(entrada1);
                File carpetaActual = new File(".");
                File carpetaSalida = new File(salida);

                if (!carpetaSalida.exists()) {
                    System.out.println("Se crear la estructura de carpetas " + carpetaSalida);
                    carpetaSalida.mkdirs();
                }

                copiar = carpetaSalida.isDirectory();
                copiar = (copiar) ? archivoEntrada.canRead() : false;

                if (copiar) {
                    String thisLine;
                    ArrayList<Integer> nums1 = new ArrayList<>();
                    Timer tF1 = new Timer("Inicio lectura archivo " + entrada1);
                    BufferedReader br1 = new BufferedReader(new FileReader(archivoEntrada));
                    while ((thisLine = br1.readLine()) != null) {
                        nums1.add(Integer.parseInt(thisLine));
                    }

                    System.out.println("Archivo de entrada ledo correctamente.");

                    boolean cpy;
                    int progreso = 0/*, totalArchivos = carpetaActual.listFiles().length*/;
                    int totalArchivos = nums1.size();

                    String f, subF;
                    for (File file : carpetaActual.listFiles()) {
                        cpy = false;
                        //                            progreso++;
                        f = (file.getName().contains("."))
                                ? file.getName().substring(0, file.getName().lastIndexOf("."))
                                : "";

                        if (f.length() > 0 && !file.isDirectory()) {
                            for (Integer i : nums1) {
                                if (f.endsWith(i.toString())) {
                                    subF = f.substring(f.length() - i.toString().length() - 1);

                                    try {
                                        if (Math.abs(Integer.parseInt(subF)) == i) {
                                            if (String.valueOf(Integer.parseInt(subF)).length() == subF
                                                    .length()) {
                                                cpy = true;
                                                break;
                                            }
                                        }
                                    } catch (NumberFormatException ex) {
                                        // error -> cadena alfanumrica
                                        cpy = true;
                                    }
                                }
                            }
                        }

                        if (cpy) {
                            //
                            progreso++;
                            //                                System.out.println("    " + file.getName() + " -> " + carpetaSalida.getPath() + "/" + file.getName());
                            //                                if(progreso == 1) System.out.print("" + );
                            if (progreso == 1)
                                System.out.print("Copiando archivos: ");
                            System.out.print("" + progreso + "/" + totalArchivos + "     ");
                            //                                if((progreso * 1.0 / totalArchivos)*100 % 20 == 0) System.out.print("....." + ((progreso * 1.0 / totalArchivos)*100) + "%");
                            Archives.copy(file, carpetaSalida);
                        }
                    }

                    tF1.setT1();
                    System.out.println("\nOperacin finalizada en " + tF1.getEllapsedTime() + " ns");
                } else {
                    System.out.println("No se ha podido realizar la operacin. Posibles causas:");
                    System.out.println("Carpeta de salida: " + carpetaSalida.getName() + " -> "
                            + carpetaSalida.isDirectory());
                    System.out.println("Archivo de entrada: " + archivoEntrada.getName() + " -> "
                            + archivoEntrada.canRead());
                }

            } else {
                printSmallHelp(options);
            }
        }

    } catch (ParseException | IOException ex) {
        System.out.println("Error: " + ex.getMessage() + "\n" + ex.getCause());
    }

}

From source file:org.apache.taverna.databundle.DataBundles.java

public static List<Path> getList(Path list) throws IOException {
    if (list == null)
        return null;
    List<Path> paths = new ArrayList<>();
    try (DirectoryStream<Path> ds = newDirectoryStream(list)) {
        for (Path entry : ds)
            try {
                long entryNum = getEntryNumber(entry);
                while (paths.size() <= entryNum)
                    // Fill any gaps
                    paths.add(null);//from   w w w .  ja  v  a2 s  .  c om
                // NOTE: Don't use add() as these could come in any order!
                paths.set((int) entryNum, entry);
            } catch (NumberFormatException ex) {
            }
    } catch (DirectoryIteratorException ex) {
        throw ex.getCause();
    }
    return paths;
}

From source file:org.apache.taverna.databundle.DataBundles.java

public static long getListSize(Path list) throws IOException {
    // Should fail if list is not a directory
    try (DirectoryStream<Path> ds = newDirectoryStream(list)) {
        long max = -1L;
        for (Path entry : ds)
            try {
                long entryNum = getEntryNumber(entry);
                if (entryNum > max)
                    max = entryNum;/*from   w w w  . j  a v a2s.  c  om*/
            } catch (NumberFormatException ex) {
            }
        return max + 1;
    } catch (DirectoryIteratorException ex) {
        throw ex.getCause();
    }
}

From source file:net.mypapit.mobile.myrepeater.RepeaterListActivity.java

public static ArrayList<String> loadStringData(InputStream stream) {
    ArrayList<String> mlist = new ArrayList<String>(150);
    int line = 0;

    try {//from  w w  w . j a  v a2  s.c om
        InputStreamReader is = new InputStreamReader(stream);
        BufferedReader in = new BufferedReader(is);
        CSVReader csv = new CSVReader(in, ';', '\"', 0);
        String data[];

        while ((data = csv.readNext()) != null) {
            line++;
            mlist.add(data[1]);
        }

        in.close();

    } catch (IOException ioe) {
        Log.e("Read CSV Error mypapit", "Some CSV Error: ", ioe.getCause());

    } catch (NumberFormatException nfe) {
        Log.e("Number error", "parse number error - line: " + line + "  " + nfe.getMessage(), nfe.getCause());
    } catch (Exception ex) {
        Log.e("Some Exception", "some exception at line :" + line + " \n " + ex.getCause());
        ex.printStackTrace(System.err);
    }
    // Collections.sort(mlist);

    return mlist;

}

From source file:net.mypapit.mobile.myrepeater.RepeaterListActivity.java

public static RepeaterList loadData(int resource, Activity activity) {
    RepeaterList mlist = new RepeaterList(150);
    int line = 0;
    try {/*from w  w  w .  j av a 2 s  .com*/

        InputStreamReader is = new InputStreamReader(activity.getResources().openRawResource(resource));
        BufferedReader in = new BufferedReader(is);
        CSVReader csv = new CSVReader(in, ';', '\"', 0);
        String data[];

        while ((data = csv.readNext()) != null) {
            line++;
            mlist.add(new Repeater("", data[1], data[2], data[3], data[9], Double.parseDouble(data[4]),
                    Double.parseDouble(data[5]), Double.parseDouble(data[6]), Double.parseDouble(data[7]),
                    Double.parseDouble(data[8])));

        }

        in.close();

    } catch (IOException ioe) {
        Log.e("Read CSV Error mypapit", "Some CSV Error: ", ioe.getCause());

    } catch (NumberFormatException nfe) {
        Log.e("Number error", "parse number error - line: " + line + "  " + nfe.getMessage(), nfe.getCause());
    } catch (Exception ex) {
        Log.e("Some Exception", "some exception at line :" + line + " \n " + ex.getCause());
        ex.printStackTrace(System.err);
    }

    return mlist;

}

From source file:cz.fi.muni.pa165.calorycounter.frontend.restserver.ActivityRestResource.java

/**
 *
 * @param activityId/*w  w  w  . ja  v a2s  . com*/
 * @return information about activity with given name for all weight
 * categories
 */
@GET
@Path("/id/{activityId}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getById(@PathParam("activityId") String activityId) {
    log.debug("Server: getById(activityId) with id: " + activityId);
    if (activityId == null || activityId.isEmpty()) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
    Long id;
    try {
        id = Long.parseLong(activityId);
    } catch (NumberFormatException ex) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
    ActivityDto activity = null;
    try {
        activity = activityService.get(id);
    } catch (RecoverableDataAccessException ex) {
        if (ex.getCause().getClass().equals(NoResultException.class)) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        } else {
            throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR);
        }
    }
    return Response.status(Response.Status.OK).entity(activity).build();
}

From source file:cz.fi.muni.pa165.calorycounter.frontend.restserver.RecordRestResource.java

@DELETE
@Path("/remove/{id}")
public Response remove(@PathParam("id") String id) {
    log.debug("Server: remove(id) with id: " + id);
    if (id == null || id.isEmpty()) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }/*w w w.j  a  va2s  .  c  o m*/
    Long idL;
    try {
        idL = Long.parseLong(id);
    } catch (NumberFormatException ex) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
    try {
        recordService.remove(idL);
    } catch (RecoverableDataAccessException ex) {
        if (ex.getCause().getClass().equals(IllegalArgumentException.class)
                || ex.getCause().getClass().equals(NoResultException.class)) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        }
        throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR);
    }
    Response.ResponseBuilder builder = Response.status(Response.Status.OK);
    return makeCORS(builder);
}

From source file:cz.fi.muni.pa165.calorycounter.frontend.restserver.RecordRestResource.java

@GET
@Path("/id/{id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getRecord(@PathParam("id") String id) {
    log.debug("Server: getRecord(id) with id: " + id);
    if (id == null || id.isEmpty()) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }// www  .j  a va 2 s.  co m
    Long idL;
    try {
        idL = Long.parseLong(id);
    } catch (NumberFormatException ex) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
    ActivityRecordDto record = null;
    try {
        record = recordService.get(idL);
    } catch (RecoverableDataAccessException ex) {
        if (ex.getCause().getClass().equals(NoResultException.class)) {
            return Response.status(Response.Status.NOT_FOUND).build();
        } else {
            throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR);
        }
    }
    return Response.status(Response.Status.OK).entity(record).build();
}

From source file:org.idempiere.webservices.AbstractService.java

/**
 * /*from  ww w . j  a  v a 2 s.co  m*/
 * @param strValue
 * @param columnClass
 * @param colName
 * @param m_webservicetype
 * @return
 */
protected Object convertToObj(String strValue, Class<?> columnClass, String colName) {

    Object value = null;

    if (columnClass == Boolean.class) {
        if ("Y".equalsIgnoreCase(strValue) || "true".equalsIgnoreCase(strValue))
            value = new Boolean(true);
        else if ("N".equalsIgnoreCase(strValue) || "false".equalsIgnoreCase(strValue))
            value = new Boolean(false);
        else
            throw new IdempiereServiceFault(" input column " + colName + " wrong value " + strValue,
                    new QName("setValueAccordingToClass"));
    } else if (columnClass == Integer.class) {
        try {
            value = Integer.parseInt(strValue);
        } catch (NumberFormatException e) {
            throw new IdempiereServiceFault(e.getClass().toString() + " " + e.getMessage() + " for " + colName,
                    e.getCause(), new QName("setValueAccordingToClass"));
        }
    } else if (columnClass == BigDecimal.class) {
        try {
            value = new BigDecimal(strValue);
        } catch (Exception e) {
            throw new IdempiereServiceFault(e.getClass().toString() + " " + e.getMessage() + " for " + colName,
                    e.getCause(), new QName("setValueAccordingToClass"));
        }
    } else if (columnClass == Timestamp.class) {
        try {
            value = Timestamp.valueOf(strValue);
        } catch (Exception e) {
            throw new IdempiereServiceFault(e.getClass().toString() + " " + e.getMessage() + " for " + colName,
                    e.getCause(), new QName("setValueAccordingToClass"));
        }
    } else if (columnClass == byte[].class) {
        try {
            value = Base64.decodeBase64(strValue.getBytes());
        } catch (Exception e) {
            throw new IdempiereServiceFault(e.getClass().toString() + " " + e.getMessage() + " for " + colName,
                    e.getCause(), new QName("setValueAccordingToClass"));
        }
    } else {
        value = strValue;
    }

    return value;
}

From source file:net.iponweb.hadoop.streaming.parquet.TextRecordWriterWrapper.java

@Override
public void write(Text key, Text value) throws IOException {

    Group grp = factory.newGroup();

    String[] strK = key.toString().split(TAB, -1);
    String[] strV = value == null ? new String[0] : value.toString().split(TAB, -1);
    String kv_combined[] = (String[]) ArrayUtils.addAll(strK, strV);

    Iterator<PathAction> ai = recorder.iterator();

    Stack<Group> groupStack = new Stack<>();
    groupStack.push(grp);// ww w  .  j  av a  2  s  . c om
    int i = 0;

    try {
        while (ai.hasNext()) {

            PathAction a = ai.next();
            switch (a.getAction()) {
            case GROUPEND:
                grp = groupStack.pop();
                break;

            case GROUPSTART:
                groupStack.push(grp);
                grp = grp.addGroup(a.getName());
                break;

            case FIELD:
                String s = null;
                PrimitiveType.PrimitiveTypeName primType = a.getType();
                String colName = a.getName();

                if (i < kv_combined.length)
                    s = kv_combined[i++];

                if (s == null) {
                    if (a.getRepetition() == Type.Repetition.OPTIONAL) {
                        i++;
                        continue;
                    }
                    s = primType == PrimitiveType.PrimitiveTypeName.BINARY ? "" : "0";
                }

                // If we have 'repeated' field, assume that we should expect JSON-encoded array
                // Convert array and append all values
                int repetition = 1;
                boolean repeated = false;
                ArrayList<String> s_vals = null;
                if (a.getRepetition() == Type.Repetition.REPEATED) {
                    repeated = true;
                    s_vals = new ArrayList<>();
                    ObjectMapper mapper = new ObjectMapper();
                    JsonNode node = mapper.readTree(s);
                    Iterator<JsonNode> itr = node.iterator();
                    repetition = 0;
                    while (itr.hasNext()) {

                        String o;
                        switch (primType) {
                        case BINARY:
                            o = itr.next().getTextValue(); // No array-of-objects!
                            break;
                        case BOOLEAN:
                            o = String.valueOf(itr.next().getBooleanValue());
                            break;
                        default:
                            o = String.valueOf(itr.next().getNumberValue());
                        }

                        s_vals.add(o);
                        repetition++;
                    }
                }

                for (int j = 0; j < repetition; j++) {

                    if (repeated)
                        // extract new s
                        s = s_vals.get(j);

                    try {
                        switch (primType) {

                        case INT32:
                            grp.append(colName, new Double(Double.parseDouble(s)).intValue());
                            break;
                        case INT64:
                        case INT96:
                            grp.append(colName, new Double(Double.parseDouble(s)).longValue());
                            break;
                        case DOUBLE:
                            grp.append(colName, Double.parseDouble(s));
                            break;
                        case FLOAT:
                            grp.append(colName, Float.parseFloat(s));
                            break;
                        case BOOLEAN:
                            grp.append(colName, s.equalsIgnoreCase("true") || s.equals("1"));
                            break;
                        case BINARY:
                            grp.append(colName, Binary.fromString(s));
                            break;
                        default:
                            throw new RuntimeException("Can't handle type " + primType);
                        }
                    } catch (NumberFormatException e) {

                        grp.append(colName, 0);
                    }
                }
            }
        }

        realWriter.write(null, (SimpleGroup) grp);

    } catch (InterruptedException e) {
        Thread.interrupted();
        throw new IOException(e);
    } catch (Exception e) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        e.printStackTrace(new PrintStream(out));
        throw new RuntimeException("Failed on record " + grp + ", schema=" + schema + ", path action="
                + recorder + " exception = " + e.getClass() + ", msg=" + e.getMessage() + ", cause="
                + e.getCause() + ", trace=" + out.toString());
    }

}