Example usage for java.text NumberFormat getInstance

List of usage examples for java.text NumberFormat getInstance

Introduction

In this page you can find the example usage for java.text NumberFormat getInstance.

Prototype

public static final NumberFormat getInstance() 

Source Link

Document

Returns a general-purpose number format for the current default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:beast.math.MathUtils.java

/**
 * return double *.????/*  www  .ja v  a2 s  .co  m*/
 * @param value
 * @param sf
 * @return
 */
public static double round(double value, int sf) {
    NumberFormatter formatter = new NumberFormatter(sf);
    try {
        return NumberFormat.getInstance().parse(formatter.format(value)).doubleValue();
    } catch (ParseException e) {
        return value;
    }
}

From source file:au.org.theark.lims.web.component.biospecimen.batchaliquot.form.BatchAliquotBiospecimenForm.java

/**
 * //from   w  ww .  j a va 2s. c  o  m
 * @return the listEditor of Biospecimens to aliquot
 */
public AbstractListEditor<Biospecimen> buildListEditor() {
    listEditor = new AbstractListEditor<Biospecimen>("aliquots",
            new PropertyModel(getModelObject(), "aliquots")) {

        private static final long serialVersionUID = 1L;

        @SuppressWarnings("serial")
        @Override
        protected void onPopulateItem(final ListItem<Biospecimen> item) {
            item.setOutputMarkupId(true);

            Biospecimen parentBiospecimen = BatchAliquotBiospecimenForm.this.getModelObject()
                    .getParentBiospecimen();
            try {
                PropertyUtils.copyProperties(item.getModelObject(), parentBiospecimen);
            } catch (IllegalAccessException e1) {
                log.error(e1.getMessage());
            } catch (InvocationTargetException e1) {
                log.error(e1.getMessage());
            } catch (NoSuchMethodException e1) {
                log.error(e1.getMessage());
            }

            if (copyBiospecimen) {
                item.getModelObject().setParent(parentBiospecimen);
                item.getModelObject().setParentUid(parentBiospecimen.getBiospecimenUid());
                item.getModelObject().setQuantity(biospecimenToCopy.getQuantity());
                item.getModelObject().setTreatmentType(biospecimenToCopy.getTreatmentType());
                item.getModelObject().setConcentration(biospecimenToCopy.getConcentration());
            } else {
                item.getModelObject().setParent(parentBiospecimen);
                item.getModelObject().setParentUid(parentBiospecimen.getBiospecimenUid());
                item.getModelObject().setQuantity(null);
                item.getModelObject().setConcentration(null);
            }

            biospecimenUidTxtFld = new TextField<String>("biospecimenUid",
                    new PropertyModel(item.getModelObject(), "biospecimenUid"));
            if (parentBiospecimen.getStudy().getAutoGenerateBiospecimenUid()) {
                biospecimenUidTxtFld.setEnabled(false);
                biospecimenUidTxtFld.setModelObject(Constants.AUTO_GENERATED);
            } else {
                biospecimenUidTxtFld.setEnabled(true);
                biospecimenUidTxtFld.setModelObject(null);
            }

            quantityTxtFld = new TextField<Double>("quantity",
                    new PropertyModel(item.getModelObject(), "quantity")) {
                private static final long serialVersionUID = 1L;

                @Override
                public <C> IConverter<C> getConverter(Class<C> type) {
                    DoubleConverter doubleConverter = new DoubleConverter();
                    NumberFormat numberFormat = NumberFormat.getInstance();
                    numberFormat.setMinimumFractionDigits(1);
                    doubleConverter.setNumberFormat(getLocale(), numberFormat);
                    return (IConverter<C>) doubleConverter;
                }
            };

            initTreatmentTypeDdc(item);
            concentrationTxtFld = new TextField<Number>("concentration",
                    new PropertyModel(item.getModelObject(), "concentration"));

            item.add(biospecimenUidTxtFld.add(new AjaxFormComponentUpdatingBehavior("onchange") {
                @Override
                protected void onUpdate(AjaxRequestTarget target) {
                    if (!item.getModelObject().getStudy().getAutoGenerateBiospecimenUid()) {
                        // Check BiospecimenUID is unique
                        String biospecimenUid = (getComponent().getDefaultModelObject().toString() != null
                                ? getComponent().getDefaultModelObject().toString()
                                : new String());
                        Biospecimen biospecimen = iLimsService.getBiospecimenByUid(biospecimenUid,
                                item.getModelObject().getStudy());
                        if (biospecimen != null && biospecimen.getId() != null) {
                            error("Biospecimen UID must be unique. Please try again.");
                            target.focusComponent(getComponent());
                        }
                    }
                    target.add(feedbackPanel);
                    biospecimenToCopy.setBiospecimenUid(getComponent().getDefaultModelObject().toString());
                }
            }));

            item.add(quantityTxtFld.add(new AjaxFormComponentUpdatingBehavior("onchange") {
                @Override
                protected void onUpdate(AjaxRequestTarget target) {
                    if (!totalQuantityLessThanParentQuantity()) {
                        target.focusComponent(getComponent());
                    }
                    target.add(feedbackPanel);
                    biospecimenToCopy.setQuantity((Double) getComponent().getDefaultModelObject());
                    item.getModelObject().setQuantity((Double) getComponent().getDefaultModelObject());
                }

                @Override
                protected void onError(AjaxRequestTarget target, RuntimeException e) {
                    target.add(feedbackPanel);
                }
            }));
            item.add(treatmentTypeDdc.add(new AjaxFormComponentUpdatingBehavior("onchange") {
                @Override
                protected void onUpdate(AjaxRequestTarget target) {
                    biospecimenToCopy.setTreatmentType((TreatmentType) getComponent().getDefaultModelObject());
                    item.getModelObject()
                            .setTreatmentType((TreatmentType) getComponent().getDefaultModelObject());
                }
            }));
            item.add(concentrationTxtFld.add(new AjaxFormComponentUpdatingBehavior("onchange") {
                @Override
                protected void onUpdate(AjaxRequestTarget target) {
                    biospecimenToCopy.setConcentration((Double) getComponent().getDefaultModelObject());
                    item.getModelObject().setConcentration((Double) getComponent().getDefaultModelObject());
                }
            }));

            // Copy button allows entire row details to be copied
            item.add(new AjaxEditorButton(Constants.COPY) {
                private static final long serialVersionUID = 1L;

                @Override
                protected void onError(AjaxRequestTarget target, Form<?> form) {
                    target.add(feedbackPanel);
                }

                @Override
                protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                    Biospecimen biospecimen = new Biospecimen();
                    copyBiospecimen = true;
                    try {
                        PropertyUtils.copyProperties(biospecimen, getItem().getModelObject());
                        PropertyUtils.copyProperties(biospecimenToCopy, getItem().getModelObject());
                        listEditor.addItem(biospecimen);
                        target.add(form);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }
            }.setDefaultFormProcessing(false));

            item.add(new AjaxEditorButton(Constants.DELETE) {
                private static final long serialVersionUID = 1L;

                @Override
                protected void onError(AjaxRequestTarget target, Form<?> form) {
                    target.add(feedbackPanel);
                }

                @Override
                protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                    listEditor.removeItem(item);
                    target.add(form);
                }
            }.setDefaultFormProcessing(false).setVisible(item.getIndex() > 0));

            item.add(new AttributeModifier(Constants.CLASS, new AbstractReadOnlyModel() {

                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    return (item.getIndex() % 2 == 1) ? Constants.EVEN : Constants.ODD;
                }
            }));
        }

    };
    return listEditor;
}

From source file:com.glaf.core.jdbc.QueryHelper.java

/**
 * @param conn//from ww w .  j a  v  a2 s .  co  m
 *            ?
 * @param sqlExecutor
 *            
 * @return
 */
@SuppressWarnings("unchecked")
public List<Map<String, Object>> getResultList(Connection conn, SqlExecutor sqlExecutor) {
    if (!DBUtils.isLegalQuerySql(sqlExecutor.getSql())) {
        throw new RuntimeException(" SQL statement illegal ");
    }
    List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
    PreparedStatement psmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    try {
        psmt = conn.prepareStatement(sqlExecutor.getSql());
        if (sqlExecutor.getParameter() != null) {
            List<Object> values = (List<Object>) sqlExecutor.getParameter();
            JdbcUtils.fillStatement(psmt, values);
        }

        rs = psmt.executeQuery();

        if (conf.getBoolean("useMyBatisResultHandler", false)) {

            resultList = this.getResults(rs);

        } else {

            rsmd = rs.getMetaData();

            int count = rsmd.getColumnCount();
            List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();

            for (int index = 1; index <= count; index++) {
                int sqlType = rsmd.getColumnType(index);
                ColumnDefinition column = new ColumnDefinition();
                column.setIndex(index);
                column.setColumnName(rsmd.getColumnName(index));
                column.setColumnLabel(rsmd.getColumnLabel(index));
                column.setJavaType(FieldType.getJavaType(sqlType));
                column.setPrecision(rsmd.getPrecision(index));
                column.setScale(rsmd.getScale(index));
                if (column.getScale() == 0 && sqlType == Types.NUMERIC) {
                    column.setJavaType("Long");
                }
                column.setName(StringTools.camelStyle(column.getColumnLabel().toLowerCase()));
                columns.add(column);
            }
            int startIndex = 1;
            while (rs.next() && startIndex <= 50000) {
                int index = 0;
                startIndex++;
                Map<String, Object> rowMap = new HashMap<String, Object>();
                Iterator<ColumnDefinition> iterator = columns.iterator();
                while (iterator.hasNext()) {
                    ColumnDefinition column = iterator.next();
                    String columnLabel = column.getColumnLabel();
                    String columnName = column.getColumnName();
                    if (StringUtils.isEmpty(columnName)) {
                        columnName = column.getColumnLabel();
                    }
                    columnName = columnName.toLowerCase();
                    String javaType = column.getJavaType();
                    index = index + 1;
                    if ("String".equals(javaType)) {
                        String value = rs.getString(column.getIndex());
                        if (value != null) {
                            value = value.trim();
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, value);
                        }
                    } else if ("Integer".equals(javaType)) {
                        try {
                            Integer value = rs.getInt(column.getIndex());
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, value);
                        } catch (Exception e) {
                            String str = rs.getString(column.getIndex());
                            logger.error("integer:" + str);
                            str = StringTools.replace(str, "$", "");
                            str = StringTools.replace(str, "", "");
                            str = StringTools.replace(str, ",", "");
                            NumberFormat fmt = NumberFormat.getInstance();
                            Number num = fmt.parse(str);
                            rowMap.put(columnName, num.intValue());
                            rowMap.put(columnLabel, rowMap.get(columnName));
                            logger.debug("?:" + num.intValue());
                        }
                    } else if ("Long".equals(javaType)) {
                        try {
                            Long value = rs.getLong(column.getIndex());
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, rowMap.get(columnName));
                        } catch (Exception e) {
                            String str = rs.getString(column.getIndex());
                            logger.error("long:" + str);
                            str = StringTools.replace(str, "$", "");
                            str = StringTools.replace(str, "", "");
                            str = StringTools.replace(str, ",", "");
                            NumberFormat fmt = NumberFormat.getInstance();
                            Number num = fmt.parse(str);
                            rowMap.put(columnName, num.longValue());
                            rowMap.put(columnLabel, num.longValue());
                            logger.debug("?:" + num.longValue());
                        }
                    } else if ("Double".equals(javaType)) {
                        try {
                            Double d = rs.getDouble(column.getIndex());
                            rowMap.put(columnName, d);
                            rowMap.put(columnLabel, d);
                        } catch (Exception e) {
                            String str = rs.getString(column.getIndex());
                            logger.error("double:" + str);
                            str = StringTools.replace(str, "$", "");
                            str = StringTools.replace(str, "", "");
                            str = StringTools.replace(str, ",", "");
                            NumberFormat fmt = NumberFormat.getInstance();
                            Number num = fmt.parse(str);
                            rowMap.put(columnName, num.doubleValue());
                            rowMap.put(columnLabel, num.doubleValue());
                            logger.debug("?:" + num.doubleValue());
                        }
                    } else if ("Boolean".equals(javaType)) {
                        rowMap.put(columnName, rs.getBoolean(column.getIndex()));
                        rowMap.put(columnLabel, rowMap.get(columnName));
                    } else if ("Date".equals(javaType)) {
                        rowMap.put(columnName, rs.getTimestamp(column.getIndex()));
                        rowMap.put(columnLabel, rowMap.get(columnName));
                    } else if ("Blob".equals(javaType)) {
                        // ignore
                    } else {
                        Object value = rs.getObject(column.getIndex());
                        if (value != null) {
                            if (value instanceof String) {
                                value = (String) value.toString().trim();
                            }
                            rowMap.put(columnName, value);
                            rowMap.put(columnLabel, rowMap.get(columnName));
                        }
                    }
                }
                rowMap.put("startIndex", startIndex);
                resultList.add(rowMap);
            }
        }

        logger.debug(">resultList size=" + resultList.size());
        return resultList;
    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(psmt);
        JdbcUtils.close(rs);
    }
}

From source file:com.cypress.cysmart.BLEServiceFragments.CSCService.java

/**
 * Display live cycling data//  w  ww.j  a va2 s.  c om
 */
private void displayLiveData(final ArrayList<String> csc_data) {
    if (csc_data != null) {
        weightString = mWeightEdittext.getText().toString();
        try {
            Number cycledDist = NumberFormat.getInstance().parse(csc_data.get(0));
            NumberFormat distformatter = NumberFormat.getNumberInstance();
            distformatter.setMinimumFractionDigits(2);
            distformatter.setMaximumFractionDigits(2);
            String distanceRanInt = distformatter.format(cycledDist);
            mDistanceRan.setText(distanceRanInt);
            mCadence.setText(csc_data.get(1));
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        if (mCurrentTime == 0) {
            mGraphLastXValue = 0;
            mCurrentTime = Utils.getTimeInSeconds();
        } else {
            mPreviosTime = mCurrentTime;
            mCurrentTime = Utils.getTimeInSeconds();
            mGraphLastXValue = mGraphLastXValue + (mCurrentTime - mPreviosTime) / 1000;
        }
        try {
            float val = Float.valueOf(csc_data.get(1));
            mDataSeries.add(mGraphLastXValue, val);
            mChart.repaint();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

From source file:com.cypress.cysmart.BLEServiceFragments.RSCService.java

/**
 * Display live running data//ww  w  .j  a v a2  s.co  m
 */
private void displayLiveData(final ArrayList<String> rsc_data) {
    if (rsc_data != null) {
        try {
            /**
             * Number formatting to two fractional decimals
             */
            Number cycledDist = NumberFormat.getInstance().parse(rsc_data.get(1));
            Number averageSpeed = NumberFormat.getInstance().parse(rsc_data.get(0));
            NumberFormat distformatter = NumberFormat.getNumberInstance();
            distformatter.setMinimumFractionDigits(2);
            distformatter.setMaximumFractionDigits(2);
            String distRan = distformatter.format(cycledDist);
            avgSpeed = distformatter.format(averageSpeed);
            mDistanceRan.setText(distRan);
            mAverageSpeed.setText(avgSpeed);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        if (mCurrentTime == 0) {
            mGraphLastXValue = 0;
            mCurrentTime = Utils.getTimeInSeconds();
        } else {
            mPreviosTime = mCurrentTime;
            mCurrentTime = Utils.getTimeInSeconds();
            mGraphLastXValue = mGraphLastXValue + (mCurrentTime - mPreviosTime) / 1000;
        }
        try {
            float val = Float.valueOf(avgSpeed);
            mDataSeries.add(mGraphLastXValue, val);
            mChart.repaint();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:biz.wolschon.fileformats.gnucash.jwsdpimpl.GnucashInvoiceEntryImpl.java

/**
*
* @return the number-format to use for non-currency-numbers if no locale is given.
*///from   w  w  w. j  av a  2 s  .co m
protected NumberFormat getNumberFormat() {
    if (numberFormat == null) {
        numberFormat = NumberFormat.getInstance();
    }

    return numberFormat;
}

From source file:hudson.gridmaven.MavenBuilder.java

/**
 * This code is executed inside the maven jail process on destination node.
 *///from w  ww .j a v a 2 s.co m
public Result call() throws IOException {

    // hold a ref on correct classloader for finally call as something is changing tccl 
    // and not restore it !
    ClassLoader mavenJailProcessClassLoader = Thread.currentThread().getContextClassLoader();

    try {
        PrintStream logger = listener.getLogger();
        initializeAsynchronousExecutions();
        Adapter a = new Adapter(this);
        callSetListenerWithReflectOnInterceptors(a, mavenJailProcessClassLoader);

        /*
         PluginManagerInterceptor.setListener(a);
         LifecycleExecutorInterceptor.setListener(a);
         */

        markAsSuccess = false;

        registerSystemProperties();

        // Hadoop configuration
        Configuration conf = new Configuration();
        conf.set("fs.default.name", info.hdfsUrl);
        conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
        conf.set("fs.file.impl", "org.apache.hadoop.fs.LocalFileSystem");
        String moduleTar = info.mArtifact + "-" + info.mVersion + ".tar";
        String hdfsSource = "/tar/" + info.jobName + "/" + info.rName + "/" + moduleTar;
        fs = FileSystem.get(conf);

        String installCommand = "";

        // Untar sources from hadoop directly
        logger.println("Untaring sources for artifact: " + info.mArtifact + "-" + info.mVersion + "."
                + info.mPackaging);
        try {
            getAndUntar(fs, hdfsSource, buildPath);
        } catch (Exception fe) {
            logger.println(
                    "Source data for this module not found in hdfs repository or hdfs error. Please try rebuild main project.");
            //fe.printStackTrace();
            return Result.FAILURE;
        }
        logger.println("Untared file: " + hdfsSource + " to " + buildPath + "\n");

        // Check if repository exists + is HDFS working
        Path repo = new Path("/repository");
        FileStatus[] status = fs.listStatus(repo);
        if (status != null) {
            if (status.length < 1) {
                logger.println("Zero files stored in HDFS");
            }
            //                // Print files stored in hdfs for debug
            //                for (int i = 0; i < status.length; i++) {
            //                    logger.println("Reading file: " + status[i].getPath());
            //                }
        } else {
            logger.println("Creating hdfs repository.");
            if (!fs.mkdirs(repo)) {
                logger.println("Cannot create hdfs repository");
                return Result.FAILURE;
            }
        }

        // Install prerequisite artifacts
        if (info.upStreamDeps.size() > 0) {
            logger.println("Preinstalling artifacts:");
        }
        for (UpStreamDep dep : info.upStreamDeps) {

            // Fetch deps from hdfs repository
            String artifactName = dep.art + "-" + dep.ver + "." + dep.pkg;
            Path hdfsPath = new Path("/repository/" + dep.art + "-" + dep.ver);
            Path absPath = new Path(buildPath + "/deps");

            boolean success = (new File(buildPath + "/deps")).mkdirs();
            if (!success) {
                //IOException e = new IOException();
                //e.printStackTrace();
            }
            logger.println("Copying from hadoop path: " + hdfsPath + " to local path:" + absPath);
            // Copy selected artifact from HDFS
            try {
                FileStatus[] statusP = fs.listStatus(hdfsPath);
                if (statusP == null)
                    throw new IOException2("This irtifact is not in hdfs repository!", null);
                for (FileStatus file : statusP) {
                    if (!file.isDir())
                        fs.copyToLocalFile(file.getPath(), absPath);
                }
            } catch (Exception e) {
                logger.println("Prerequisite artifact needed for module build missing: " + artifactName);
                return Result.FAILURE;
            }
            String s = "install:install-file -Dfile=deps" + File.separator + dep.art + "-" + dep.ver + "."
                    + dep.pkg + " -DgroupId=" + dep.group + " -DartifactId=" + dep.art + " -Dversion=" + dep.ver
                    + " -Dpackaging=" + dep.pkg + " -DpomFile=" + "deps" + File.separator + dep.art + "-"
                    + dep.ver + ".pom";
            logger.println("Preinstalling artifact: " + s + "\n");
            installCommand += info.mavenExePath + " " + s + ";";
        }

        //logger.println("Executing: " + installCommand);
        try {
            if (!performWrapper(installCommand)) {
                logger.println("Artifact installation failed!");
            }
        } catch (Exception e) {
            logger.println(
                    "Execute process of installing artifacts to local repository failed: " + installCommand);
            e.printStackTrace();
            return Result.FAILURE;
        }
        logger.println("Artifact installation finished\n");

        // End of preinstalation phase

        logger.println("Executing main goal");

        // Lauch MAIN maven process
        logger.println(formatArgs(goals));
        int r = Main.launch(goals.toArray(new String[goals.size()]));

        // now check the completion status of async ops
        long startTime = System.nanoTime();

        Result waitForAsyncExecutionsResult = waitForAsynchronousExecutions();
        if (waitForAsyncExecutionsResult != null) {
            return waitForAsyncExecutionsResult;
        }

        a.overheadTime += System.nanoTime() - startTime;

        if (profile) {
            NumberFormat n = NumberFormat.getInstance();
            logger.println("Total overhead was " + format(n, a.overheadTime) + "ms");
            Channel ch = Channel.current();
            logger.println("Class loading " + format(n, ch.classLoadingTime.get()) + "ms, "
                    + ch.classLoadingCount + " classes");
            logger.println("Resource loading " + format(n, ch.resourceLoadingTime.get()) + "ms, "
                    + ch.resourceLoadingCount + " times");
        }

        // Building successfully finished?
        if (r != 0) {
            return Result.FAILURE;
        }

        // Install produced artifacts to HDFS repository
        logger.println("Packaging...");
        try {
            // Package artifact
            performWrapper(info.mavenExePath
                    + " -N -B package -Dmaven.test.skip=true -Dmaven.test.failure.ignore=true");
        } catch (InterruptedException ex) {
            logger.println("Artifact packaging failed!");
            Logger.getLogger(MavenBuilder.class.getName()).log(Level.SEVERE, null, ex);
            return Result.FAILURE;
        }
        logger.println("Package created\n");

        // Insert compiled artifact to hdfs repository
        String absolute = buildPath;
        String artPath = absolute + "/target/" + artifact + "-" + version + "." + packaging;
        File normalPom = new File(artPath);

        // If its bundle, e.g. OSGi bundle, treat that as jar
        if (!normalPom.exists()) {
            artPath = absolute + "/target/" + artifact + "." + "jar";
            File specialJar = new File(artPath);
            if (!specialJar.exists()) {
                artPath = "";
                packaging = "jar";
            }
        }

        // Copy created artifact only
        try {
            if (upStreamDeps.size() > 0 && !artPath.equals("")) {
                String destName;
                File target = new File(absolute + File.separator + "target");
                logger.println("Produced artifacts found:");
                File[] files = target.listFiles();

                if (target.length() > 0) {
                    //                        for (File file : files) {
                    //                            if (file.isFile()) {
                    //                                logger.println(file.getPath());
                    //                                artPath = file.getAbsolutePath();
                    //                                if (artPath.contains("pom") || artPath.contains("jar") || artPath.contains("war") || artPath.contains("ear")) {
                    //                                    String suffix = artPath.substring(artPath.lastIndexOf('.') + 1, artPath.length());
                    Path absArtifactPath = new Path(artPath);
                    destName = "/repository/" + artifact + "-" + version + "/" + artifact + "-" + version + "."
                            + packaging;

                    Path nameP = new Path(artPath);
                    FileStatus[] status3 = fs.listStatus(nameP);
                    if (status3 == null) {
                        logger.println(
                                "\nCopying from local path:" + absArtifactPath + " to hadoop:" + destName);
                        try {
                            fs.copyFromLocalFile(absArtifactPath, new Path(destName));
                        } catch (Exception e) {
                            logger.println("Exception in inserting artifact!");
                            return Result.FAILURE;
                        }
                    }
                    //                                }
                    //                            }
                    //                        }
                }
            }

            // Copy only parent pom or archive at least main pom
            Path pomPath = new Path(absolute + "/pom.xml");
            logger.println("\nCopying from local path:" + pomPath + " to hadoop: /repository/" + artifact + "-"
                    + version + ".pom");
            String name = "/repository/" + artifact + "-" + version + "/" + artifact + "-" + version + ".pom";

            Path nameP = new Path(name);
            FileStatus[] status2 = fs.listStatus(nameP);
            if (status2 == null) {
                try {
                    fs.copyFromLocalFile(pomPath, new Path(name));
                } catch (Exception e) {
                    logger.println("Exception in inserting main pom artifact!");
                }
            }
            //}
        } catch (Exception e) {
            logger.println(
                    "Failed to insert packaged artifact to hdfs repository! Maybe artifact only exists and this is not error.");
            e.printStackTrace();
            return Result.FAILURE;
        }

        logger.println("Inserting to hadoop finished");
        // EOF Hadoop stuff, maven plugin continues      

        if (r == 0) {
            return Result.SUCCESS;
        }

        if (markAsSuccess) {
            logger.println(Messages.MavenBuilder_Failed());
            return Result.SUCCESS;
        }
        return Result.FAILURE;
    } catch (NoSuchMethodException e) {
        throw new IOException2(e);
    } catch (IllegalAccessException e) {
        throw new IOException2(e);
    } catch (RuntimeException e) {
        throw new IOException2(e);
    } catch (InvocationTargetException e) {
        throw new IOException2(e);
    } catch (ClassNotFoundException e) {
        throw new IOException2(e);
    } catch (NoSuchRealmException ex) {
        throw new IOException2(ex);
    } finally {

        //PluginManagerInterceptor.setListener(null);
        //LifecycleExecutorInterceptor.setListener(null);
        callSetListenerWithReflectOnInterceptorsQuietly(null, mavenJailProcessClassLoader);
    }

}

From source file:com.panet.imeta.core.util.StringUtil.java

public static double str2num(String pattern, String decimal, String grouping, String currency, String value)
        throws KettleValueException {
    // 0 : pattern
    // 1 : Decimal separator
    // 2 : Grouping separator
    // 3 : Currency symbol

    NumberFormat nf = NumberFormat.getInstance();
    DecimalFormat df = (DecimalFormat) nf;
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();

    if (!Const.isEmpty(pattern))
        df.applyPattern(pattern);//from  w  ww .  j a  va  2  s  .com
    if (!Const.isEmpty(decimal))
        dfs.setDecimalSeparator(decimal.charAt(0));
    if (!Const.isEmpty(grouping))
        dfs.setGroupingSeparator(grouping.charAt(0));
    if (!Const.isEmpty(currency))
        dfs.setCurrencySymbol(currency);
    try {
        df.setDecimalFormatSymbols(dfs);
        return df.parse(value).doubleValue();
    } catch (Exception e) {
        String message = "Couldn't convert string to number " + e.toString();
        if (!isEmpty(pattern))
            message += " pattern=" + pattern;
        if (!isEmpty(decimal))
            message += " decimal=" + decimal;
        if (!isEmpty(grouping))
            message += " grouping=" + grouping.charAt(0);
        if (!isEmpty(currency))
            message += " currency=" + currency;
        throw new KettleValueException(message);
    }
}

From source file:com.crearo.gpslogger.ui.fragments.display.GpsDetailedViewFragment.java

public void displayLocationInfo(Location locationInfo) {
    if (locationInfo == null) {
        return;/*from www. j a  v  a 2s  .co  m*/
    }

    showPreferencesAndMessages();

    TextView tvLatitude = (TextView) rootView.findViewById(R.id.detailedview_lat_text);
    TextView tvLongitude = (TextView) rootView.findViewById(R.id.detailedview_lon_text);
    TextView tvDateTime = (TextView) rootView.findViewById(R.id.detailedview_datetime_text);

    TextView tvAltitude = (TextView) rootView.findViewById(R.id.detailedview_altitude_text);

    TextView txtSpeed = (TextView) rootView.findViewById(R.id.detailedview_speed_text);

    TextView txtSatellites = (TextView) rootView.findViewById(R.id.detailedview_satellites_text);
    TextView txtDirection = (TextView) rootView.findViewById(R.id.detailedview_direction_text);
    TextView txtAccuracy = (TextView) rootView.findViewById(R.id.detailedview_accuracy_text);
    TextView txtTravelled = (TextView) rootView.findViewById(R.id.detailedview_travelled_text);
    TextView txtTime = (TextView) rootView.findViewById(R.id.detailedview_duration_text);
    String providerName = locationInfo.getProvider();
    if (providerName.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
        providerName = getString(R.string.providername_gps);
    } else {
        providerName = getString(R.string.providername_celltower);
    }

    tvDateTime.setText(android.text.format.DateFormat.getDateFormat(getActivity())
            .format(new Date(Session.getLatestTimeStamp())) + " - " + providerName);

    NumberFormat nf = NumberFormat.getInstance();

    nf.setMaximumFractionDigits(6);
    tvLatitude.setText(String.valueOf(nf.format(locationInfo.getLatitude())));
    tvLongitude.setText(String.valueOf(nf.format(locationInfo.getLongitude())));

    nf.setMaximumFractionDigits(3);

    if (locationInfo.hasAltitude()) {
        tvAltitude.setText(Strings.getDistanceDisplay(getActivity(), locationInfo.getAltitude(),
                preferenceHelper.shouldDisplayImperialUnits()));
    } else {
        tvAltitude.setText(R.string.not_applicable);
    }

    if (locationInfo.hasSpeed()) {
        txtSpeed.setText(Strings.getSpeedDisplay(getActivity(), locationInfo.getSpeed(),
                preferenceHelper.shouldDisplayImperialUnits()));

    } else {
        txtSpeed.setText(R.string.not_applicable);
    }

    if (locationInfo.hasBearing()) {

        float bearingDegrees = locationInfo.getBearing();
        String direction;

        direction = Strings.getBearingDescription(bearingDegrees, getActivity().getApplicationContext());

        txtDirection.setText(direction + "(" + String.valueOf(Math.round(bearingDegrees))
                + getString(R.string.degree_symbol) + ")");
    } else {
        txtDirection.setText(R.string.not_applicable);
    }

    if (!Session.isUsingGps()) {
        txtSatellites.setText(R.string.not_applicable);
    }

    if (locationInfo.hasAccuracy()) {

        float accuracy = locationInfo.getAccuracy();
        txtAccuracy.setText(getString(R.string.accuracy_within, Strings.getDistanceDisplay(getActivity(),
                accuracy, preferenceHelper.shouldDisplayImperialUnits()), ""));

    } else {
        txtAccuracy.setText(R.string.not_applicable);
    }

    double distanceValue = Session.getTotalTravelled();
    txtTravelled.setText(Strings.getDistanceDisplay(getActivity(), distanceValue,
            preferenceHelper.shouldDisplayImperialUnits()) + " (" + Session.getNumLegs() + " points)");

    long startTime = Session.getStartTimeStamp();
    Date d = new Date(startTime);
    long currentTime = System.currentTimeMillis();

    String duration = Strings.getDescriptiveDurationString((int) (currentTime - startTime) / 1000,
            getActivity());

    DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
    DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getActivity().getApplicationContext());
    txtTime.setText(duration + " (started at " + dateFormat.format(d) + " " + timeFormat.format(d) + ")");

}

From source file:TexBug.java

public void init() {

    // initialize the code base
    try {//from   w w w.  ja v  a2 s  .  c om
        java.net.URL codeBase = getCodeBase();
        codeBaseString = codeBase.toString();
    } catch (Exception e) {
        // probably running as an application, try the application
        // code base
        codeBaseString = "file:./";
    }

    // set up a NumFormat object to print out float with only 3 fraction
    // digits
    nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(3);

    setLayout(new BorderLayout());
    GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();

    canvas = new Canvas3D(config);
    add("Center", canvas);

    // Create a simple scene and attach it to the virtual universe
    BranchGroup scene = createSceneGraph();
    u = new SimpleUniverse(canvas);

    // set up sound
    u.getViewer().createAudioDevice();

    // get the view
    view = u.getViewer().getView();

    // Get the viewing platform
    ViewingPlatform viewingPlatform = u.getViewingPlatform();

    // Move the viewing platform back to enclose the -2 -> 2 range
    double viewRadius = 2.0; // want to be able to see circle
    // of viewRadius size around origin
    // get the field of view
    double fov = u.getViewer().getView().getFieldOfView();

    // calc view distance to make circle view in fov
    float viewDistance = (float) (viewRadius / Math.tan(fov / 2.0));
    tmpVector.set(0.0f, 0.0f, viewDistance);// setup offset
    tmpTrans.set(tmpVector); // set trans to translate
    // move the view platform
    viewingPlatform.getViewPlatformTransform().setTransform(tmpTrans);

    // add an orbit behavior to move the viewing platform
    OrbitBehavior orbit = new OrbitBehavior(canvas);
    BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0);
    orbit.setSchedulingBounds(bounds);
    viewingPlatform.setViewPlatformBehavior(orbit);

    u.addBranchGraph(scene);

    add("South", guiPanel());
}