Java Examples for java.lang.NumberFormatException

The following java examples will help you to understand the usage of java.lang.NumberFormatException. These source code samples are taken from different open source projects.

Example 1
Project: pluotsorbet-master  File: constructor.java View source code
/**
     * Runs the test using the specified harness.
     *
     * @param harness  the test harness (<code>null</code> not permitted).
     */
public void test(TestHarness harness) {
    NumberFormatException object1 = new NumberFormatException();
    harness.check(object1 != null);
    harness.check(object1.toString(), "java.lang.NumberFormatException");
    NumberFormatException object2 = new NumberFormatException("nothing happens");
    harness.check(object2 != null);
    harness.check(object2.toString(), "java.lang.NumberFormatException: nothing happens");
    NumberFormatException object3 = new NumberFormatException(null);
    harness.check(object3 != null);
    harness.check(object3.toString(), "java.lang.NumberFormatException");
}
Example 2
Project: urlaubsverwaltung-master  File: ErrorResponseTest.java View source code
@Test
public void ensureCorrectErrorResponse() {
    ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST, new NumberFormatException("foo"));
    Assert.assertTrue("Wrong timestamp", errorResponse.getTimestamp() > 0);
    Assert.assertEquals("Wrong status", 400, errorResponse.getStatus());
    Assert.assertEquals("Wrong error", "Bad Request", errorResponse.getError());
    Assert.assertEquals("Wrong error", "java.lang.NumberFormatException", errorResponse.getException());
    Assert.assertEquals("Wrong error", "foo", errorResponse.getMessage());
}
Example 3
Project: JMXMiniProbe-master  File: NumberUtility.java View source code
//////////////////////////////////////////////////////////
/** 
	 *	attempts to convert the object passed in to a BigDecimal.
	 *	The conversion may throw a java.lang.NumberFormatException
	 *	if the type cannot be converted.
	 *	It is left uncaught so the user can decicde how to deal with it.
	 */
public static BigDecimal convertToBigDecimal(Object value) {
    //java.lang.NumberFormatException
    BigDecimal retVal = null;
    if (value == null)
        return retVal;
    if (value instanceof BigDecimal) {
        retVal = (BigDecimal) value;
    } else if (value instanceof Number) {
        //NOTE, have seen this issue come and go under different jre versions.. but in some cases using the double constructor
        //for big decimal will change the data..
        //ex) doulbe -97.75389  changes to -97.75389099121094
        //using the string constrctor is more accurate..
        //retVal = new BigDecimal(((Number)value).doubleValue());
        retVal = new BigDecimal(((Number) value).toString());
    } else {
        //remove commas and dollar signs from the string value
        String strVal = MathUtility.cleanUpNumberString(value.toString());
        retVal = new BigDecimal(strVal);
    //if
    }
    return retVal;
}
Example 4
Project: SEEP-master  File: PUContextTest.java View source code
/**
	 * Run the void updateConnection(int,Operator,InetAddress) method test.
	 *
	 * @throws Exception
	 *
	 * @generatedBy CodePro at 18/10/13 19:07
	 */
public void testUpdateConnection_1() throws Exception {
    PUContext fixture = new PUContext(new WorkerNodeDescription(InetAddress.getLocalHost(), 1), new ArrayList());
    int opRecId = 1;
    Operator opToReconfigure = null;
    InetAddress newIp = InetAddress.getLocalHost();
    fixture.updateConnection(opRecId, opToReconfigure, newIp);
// add additional test code here
// An unexpected exception was thrown in user code while executing this test:
//    java.lang.NumberFormatException: null
//       at java.lang.Integer.parseInt(Integer.java:454)
//       at java.lang.Integer.<init>(Integer.java:677)
//       at uk.ac.imperial.lsds.seep.processingunit.PUContext.updateConnection(PUContext.java:313)
}
Example 5
Project: AndroidFunctionalTester-master  File: ArgumentTypeTest.java View source code
@Test
public void testParseValue() {
    Object value;
    try {
        ArgumentType.ON_OFF.parseValue("xx");
    } catch (IllegalArgumentException e) {
        Assert.assertEquals("Invalid value xx - should be 'on' or 'off'", e.getMessage());
    }
    value = ArgumentType.ON_OFF.parseValue("on");
    Assert.assertTrue(value instanceof Boolean);
    Assert.assertTrue((Boolean) value);
    try {
        ArgumentType.INTEGER.parseValue("xx");
    } catch (java.lang.NumberFormatException e) {
        Assert.assertEquals("For input string: \"xx\"", e.getMessage());
    }
    value = ArgumentType.INTEGER.parseValue("1000");
    Assert.assertTrue(value instanceof Integer);
    Assert.assertEquals(1000, ((Integer) value).intValue());
    value = ArgumentType.STRING.parseValue("Click");
    Assert.assertTrue(value instanceof String);
    Assert.assertEquals("Click", value.toString());
}
Example 6
Project: SOEMPI-master  File: ScalarLongDistanceMetric.java View source code
public double score(Object value1, Object value2) {
    if (missingValues(value1, value2)) {
        return handleMissingValues(value1, value2);
    }
    long v1 = 0L;
    if (value1 instanceof Long) {
        v1 = (Long) value1;
    } else {
        try {
            v1 = Long.valueOf(value1.toString());
        } catch (java.lang.NumberFormatException e) {
        }
    }
    long v2 = 0L;
    if (value2 instanceof Long) {
        v2 = (Long) value2;
    } else {
        try {
            v2 = Long.valueOf(value2.toString());
        } catch (java.lang.NumberFormatException e) {
        }
    }
    double distance = Math.abs(v1 - v2);
    log.trace("Computed the distance between :" + value1.toString() + ": and :" + value2.toString() + ": to be " + distance);
    return distance;
}
Example 7
Project: i2p.i2p-master  File: ConfigSummaryHandler.java View source code
@Override
protected void processForm() {
    if (_action == null)
        return;
    String group = getJettyString("group");
    boolean deleting = _action.equals(_t("Delete selected"));
    boolean adding = _action.equals(_t("Add item"));
    boolean saving = _action.equals(_t("Save order"));
    boolean moving = _action.startsWith("move_");
    if (_action.equals(_t("Save")) && "0".equals(group)) {
        try {
            int refreshInterval = Integer.parseInt(getJettyString("refreshInterval"));
            if (refreshInterval >= CSSHelper.MIN_REFRESH) {
                _context.router().saveConfig(CSSHelper.PROP_REFRESH, "" + refreshInterval);
                addFormNotice(_t("Refresh interval changed"));
            } else
                addFormError(_t("Refresh interval must be at least {0} seconds", CSSHelper.MIN_REFRESH));
        } catch (java.lang.NumberFormatException e) {
            addFormError(_t("Refresh interval must be a number"));
            return;
        }
    } else if (_action.equals(_t("Restore full default"))) {
        _context.router().saveConfig(SummaryHelper.PROP_SUMMARYBAR + "default", SummaryHelper.DEFAULT_FULL);
        addFormNotice(_t("Full summary bar default restored.") + " " + _t("Summary bar will refresh shortly."));
    } else if (_action.equals(_t("Restore minimal default"))) {
        _context.router().saveConfig(SummaryHelper.PROP_SUMMARYBAR + "default", SummaryHelper.DEFAULT_MINIMAL);
        addFormNotice(_t("Minimal summary bar default restored.") + " " + _t("Summary bar will refresh shortly."));
    } else if (adding || deleting || saving || moving) {
        Map<Integer, String> sections = new TreeMap<Integer, String>();
        for (Object o : _settings.keySet()) {
            if (!(o instanceof String))
                continue;
            String k = (String) o;
            if (!k.startsWith("order_"))
                continue;
            String v = getJettyString(k);
            k = k.substring(6);
            k = k.substring(k.indexOf('_') + 1);
            try {
                int order = Integer.parseInt(v);
                sections.put(order, k);
            } catch (java.lang.NumberFormatException e) {
                addFormError(_t("Order must be an integer"));
                return;
            }
        }
        if (adding) {
            String name = getJettyString("name");
            if (name == null || name.length() <= 0) {
                addFormError(_t("No section selected"));
                return;
            }
            String order = getJettyString("order");
            if (order == null || order.length() <= 0) {
                addFormError(_t("No order entered"));
                return;
            }
            name = DataHelper.escapeHTML(name).replace(",", ",");
            order = DataHelper.escapeHTML(order).replace(",", ",");
            try {
                int ki = Integer.parseInt(order);
                sections.put(ki, name);
                addFormNotice(_t("Added") + ": " + name);
            } catch (java.lang.NumberFormatException e) {
                addFormError(_t("Order must be an integer"));
                return;
            }
        } else if (deleting) {
            Set<Integer> toDelete = new HashSet<Integer>();
            for (Object o : _settings.keySet()) {
                if (!(o instanceof String))
                    continue;
                String k = (String) o;
                if (!k.startsWith("delete_"))
                    continue;
                k = k.substring(7);
                try {
                    int ki = Integer.parseInt(k);
                    toDelete.add(ki);
                } catch (java.lang.NumberFormatException e) {
                    continue;
                }
            }
            for (Iterator<Integer> iter = sections.keySet().iterator(); iter.hasNext(); ) {
                int i = iter.next();
                if (toDelete.contains(i)) {
                    String removedName = sections.get(i);
                    iter.remove();
                    addFormNotice(_t("Removed") + ": " + removedName);
                }
            }
        } else if (moving) {
            String parts[] = DataHelper.split(_action, "_");
            try {
                int from = Integer.parseInt(parts[1]);
                int to = 0;
                if ("up".equals(parts[2]))
                    to = from - 1;
                if ("down".equals(parts[2]))
                    to = from + 1;
                if ("bottom".equals(parts[2]))
                    to = sections.size() - 1;
                int n = -1;
                if ("down".equals(parts[2]) || "bottom".equals(parts[2]))
                    n = 1;
                for (int i = from; n * i < n * to; i += n) {
                    String temp = sections.get(i + n);
                    sections.put(i + n, sections.get(i));
                    sections.put(i, temp);
                }
                addFormNotice(_t("Moved") + ": " + sections.get(to));
            } catch (java.lang.NumberFormatException e) {
                addFormError(_t("Order must be an integer"));
                return;
            }
        }
        SummaryHelper.saveSummaryBarSections(_context, "default", sections);
        addFormNotice(_t("Saved order of sections.") + " " + _t("Summary bar will refresh shortly."));
    } else {
    //addFormError(_t("Unsupported"));
    }
}
Example 8
Project: fastjson-master  File: Issue1063_date.java View source code
public void test_for_issue() throws Exception {
    long currentMillis = System.currentTimeMillis();
    TimestampBean bean = new TimestampBean();
    bean.setTimestamp(new Date(currentMillis));
    String timestampJson = JSON.toJSONString(bean);
    // 这里能转��功
    TimestampBean beanOfJSON = JSON.parseObject(timestampJson, TimestampBean.class);
    // 这里抛异常 java.lang.NumberFormatException
    JSONObject jsonObject = JSON.parseObject(timestampJson);
    Timestamp timestamp2 = jsonObject.getObject("timestamp", Timestamp.class);
    assertEquals(currentMillis / 1000, timestamp2.getTime() / 1000);
}
Example 9
Project: KISS-master  File: QuerySearcher.java View source code
@Override
protected List<Pojo> doInBackground(Void... voids) {
    // Ask for records
    final List<Pojo> pojos = KissApplication.getDataHandler(activity).getResults(activity, query);
    // Convert `"number-of-display-elements"` to double first before truncating to int to avoid
    // `java.lang.NumberFormatException` crashes for values larger than `Integer.MAX_VALUE`
    int maxRecords = (new Double(prefs.getString("number-of-display-elements", String.valueOf(DEFAULT_MAX_RESULTS)))).intValue();
    // Possibly limit number of results post-mortem
    if (pojos.size() > maxRecords) {
        return pojos.subList(0, maxRecords);
    }
    return pojos;
}
Example 10
Project: logstash-gelf-master  File: StackTraceFilterUnitTests.java View source code
@Test
public void filterWholeStackTrace() {
    String filteredStackTrace = StackTraceFilter.getFilteredStackTrace(entryMethod(), true);
    List<String> lines = Arrays.asList(filteredStackTrace.split(System.getProperty("line.separator")));
    assertThat(lines).contains("\tSuppressed: java.lang.RuntimeException: suppressed");
    assertThat(lines).contains("\t\tCaused by: java.lang.NumberFormatException: For input string: \"text\"");
    assertThat(lines).contains("\t\t\t\t\t1 line skipped for [org.jboss]");
}
Example 11
Project: opencit-master  File: IntegerInput.java View source code
@Override
protected Integer convert(String input) {
    try {
        Integer value = Integer.valueOf(input);
        if (range == null) {
            return value;
        } else {
            if (range.contains(value)) {
                return value;
            } else {
                fault("Not in range [%d, %d]: %d", range.getMinimum(), range.getMaximum(), value);
            }
        }
    } catch (java.lang.NumberFormatException e) {
        fault(e, "Not a number: %s", input);
    }
    return null;
}
Example 12
Project: replication-benchmarker-master  File: GenericDataSet.java View source code
private int checkData(ArrayList<String> point, int old_dim) throws NumberFormatException {
    int new_dim = point.size();
    if (old_dim < 0)
        // if the array is still empty, any size is good size
        old_dim = new_dim;
    if (old_dim != new_dim)
        throw new ArrayIndexOutOfBoundsException("Point inserted differs in dimension: found " + new_dim + ", requested " + old_dim);
    for (int i = 0; i < point.size(); i++) if (!parser.isValid(point.get(i), i))
        throw new NumberFormatException("The point added with value \"" + point.get(i) + "\" and index " + i + " is not valid with parser " + parser.getClass().getName());
    return old_dim;
}
Example 13
Project: openhab1-addons-master  File: DigitalSTROMBindingConfig.java View source code
private void parseValue(DigitalSTROMBindingConfigEnum configKey, String valueStr) {
    switch(configKey) {
        case dsid:
            this.dsid = new DSID(valueStr);
            break;
        case consumption:
            try {
                this.consumption = ConsumptionConfig.valueOf(valueStr);
            } catch (Exception e) {
                logger.error("WRONG consumption type: " + valueStr + "; " + e.getLocalizedMessage());
            }
            if (consumption == null) {
                this.consumption = ConsumptionConfig.ACTIVE_POWER;
            }
            break;
        case sensor:
            try {
                this.sensor = SensorConfig.valueOf(valueStr);
            } catch (Exception e) {
                logger.error("WRONG sensor type: " + valueStr + "; " + e.getLocalizedMessage());
            }
            break;
        case timeinterval:
            int interval = -1;
            try {
                interval = Integer.parseInt(valueStr);
            } catch (java.lang.NumberFormatException e) {
                logger.error("Numberformat exception by parsing a string to int in timeinterval: " + valueStr);
            }
            if (interval != -1) {
                this.timeinterval = interval;
            }
            break;
        case dsmid:
            this.dsmid = new DSID(valueStr);
            break;
        case context:
            if (valueStr.toLowerCase().equals(ContextConfig.slat.name())) {
                this.context = ContextConfig.slat;
            } else if (valueStr.toLowerCase().equals(ContextConfig.apartment.name())) {
                this.context = ContextConfig.apartment;
            } else if (valueStr.toLowerCase().equals(ContextConfig.zone.name())) {
                this.context = ContextConfig.zone;
            } else if (valueStr.toLowerCase().equals(ContextConfig.awning.name())) {
                this.context = ContextConfig.awning;
            }
            break;
        case groupid:
            try {
                this.groupID = Short.parseShort(valueStr);
            } catch (java.lang.NumberFormatException e) {
                logger.error("Numberformat exception by parsing a string to short: " + valueStr + "; " + e.getLocalizedMessage());
            }
            break;
        case zoneid:
            try {
                this.zoneID = Integer.parseInt(valueStr);
            } catch (java.lang.NumberFormatException e) {
                logger.error("Numberformat exception by parsing a string to integer: " + valueStr + "; " + e.getLocalizedMessage());
            }
            break;
        default:
    }
}
Example 14
Project: ShowTree-master  File: GenerateButtonListener.java View source code
/*
	 * Makes sure arity is an integer. Non-positive arity represents unbounded degree, which
	 * has no meaning with the CompleteTree builder.
	 * If the value is good, saves it for use in current tree generation.
	 */
private int processArity() {
    int arity = 0;
    try {
        arity = TreeMenu.getInstance().getSelectedArity();
    } catch (java.lang.NumberFormatException e) {
        JOptionPane.showMessageDialog(TreeFrame.getInstance(), "arity must be an integer!\nnon-positive integer represents unbounded arity");
        return -1;
    }
    if (!TreeMenu.getInstance().getTreeBuilder().acceptsUnboundedDegree()) {
        if (arity == 0) {
            JOptionPane.showMessageDialog(TreeFrame.getInstance(), "Unbounded degree has no meaning with " + TreeMenu.getInstance().getTreeBuilder().toString() + "!");
            return -1;
        }
    }
    if (arity < 1) {
        arity = Integer.MAX_VALUE;
    }
    return arity;
}
Example 15
Project: grouper-client-master  File: ASTAddNode.java View source code
/**
     * {@inheritDoc} 
     */
public Object value(JexlContext context) throws Exception {
    Object left = ((SimpleNode) jjtGetChild(0)).value(context);
    Object right = ((SimpleNode) jjtGetChild(1)).value(context);
    /*
         *  the spec says 'and'
         */
    if (left == null && right == null) {
        return new Long(0);
    }
    /*
         *  if anything is float, double or string with ( "." | "E" | "e")
         *  coerce all to doubles and do it
         */
    if (left instanceof Float || left instanceof Double || right instanceof Float || right instanceof Double || (left instanceof String && (((String) left).indexOf(".") != -1 || ((String) left).indexOf("e") != -1 || ((String) left).indexOf("E") != -1)) || (right instanceof String && (((String) right).indexOf(".") != -1 || ((String) right).indexOf("e") != -1 || ((String) right).indexOf("E") != -1))) {
        try {
            Double l = Coercion.coerceDouble(left);
            Double r = Coercion.coerceDouble(right);
            return new Double(l.doubleValue() + r.doubleValue());
        } catch (java.lang.NumberFormatException nfe) {
            return left.toString().concat(right.toString());
        }
    }
    /*
         * attempt to use Longs
         */
    try {
        Long l = Coercion.coerceLong(left);
        Long r = Coercion.coerceLong(right);
        return new Long(l.longValue() + r.longValue());
    } catch (java.lang.NumberFormatException nfe) {
        return left.toString().concat(right.toString());
    }
}
Example 16
Project: moviedb-android-master  File: MovieModel.java View source code
@Override
public int compare(MovieModel movie1, MovieModel movie2) {
    String year1, year2;
    int compareYear1, compareYear2;
    try {
        year1 = movie1.getReleaseDate();
    } catch (java.lang.NullPointerException e) {
        year1 = "0";
    }
    try {
        year2 = movie2.getReleaseDate();
    } catch (java.lang.NullPointerException e) {
        year2 = "0";
    }
    try {
        compareYear1 = Integer.parseInt(year1);
    } catch (java.lang.NumberFormatException e) {
        compareYear1 = 0;
    }
    try {
        compareYear2 = Integer.parseInt(year2);
    } catch (java.lang.NumberFormatException e) {
        compareYear2 = 0;
    }
    if (compareYear1 == compareYear2)
        return 0;
    if (compareYear1 < compareYear2)
        return 1;
    else
        return -1;
}
Example 17
Project: opennms_dashboard-master  File: IpValidator.java View source code
/**
     * <p>isIpValid</p>
     *
     * @param ipAddr a {@link java.lang.String} object.
     * @return a boolean.
     */
public static boolean isIpValid(String ipAddr) {
    ThreadCategory log = ThreadCategory.getInstance(IpValidator.class);
    StringTokenizer token = new StringTokenizer(ipAddr, ".");
    if (token.countTokens() != 4) {
        if (log.isDebugEnabled())
            log.debug("Invalid format for IpAddress " + ipAddr);
        return false;
    }
    int temp;
    int i = 0;
    while (i < 4) {
        try {
            temp = Integer.parseInt(token.nextToken(), 10);
            if (temp < 0 || temp > 255) {
                if (log.isDebugEnabled())
                    log.debug("Invalid value " + temp + " in IpAddress");
                return false;
            }
            i++;
        } catch (NumberFormatException ex) {
            if (log.isDebugEnabled())
                log.debug("Invalid format for IpAddress, " + ex);
            return false;
        }
    }
    return true;
}
Example 18
Project: parkandrideAPI-master  File: ErrorHandlingITest.java View source code
@Test
public void request_parameter_binding_errors_are_detailed_as_violations() {
    when().get(UrlSchema.FACILITIES + "?ids=foo").then().spec(assertResponse(HttpStatus.BAD_REQUEST, BindException.class)).body("message", is("Invalid request parameters")).body("violations[0].path", is("ids")).body("violations[0].message", is("Failed to convert property value of type 'java.lang.String' to required type 'java.util.Set' for property " + "'ids'; nested exception is java.lang.NumberFormatException: For input string: \"foo\""));
}
Example 19
Project: beast-mcmc-master  File: Microsatellite.java View source code
/**
     *
     * @param srtRawLength  a String representing the raw length of a microsatellite allele in nucleotide units
     * @return int          the state of microsatellite allele corresponding to the length
     */
public int getState(String srtRawLength) {
    char chRawLength = srtRawLength.charAt(0);
    try {
        if (chRawLength == UNKNOWN_CHARACTER) {
            return getState(UNKNOWN_STATE_LENGTH);
        } else {
            return getState(Integer.parseInt(srtRawLength));
        }
    } catch (java.lang.NumberFormatException exp) {
        throw new java.lang.NumberFormatException(srtRawLength + " can not be converted. State needs to be an integer or unknown (?).");
    }
}
Example 20
Project: egovframe.rte.3.5-master  File: ExceptionResolverTest.java View source code
/**
	 *
	 *
	 * @throws Exception
	 */
@Test
public void testExceptionViewNameMapping() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();
    Object handler = new Object();
    Properties props = new Properties();
    props.setProperty("java.lang.Exception", "genericErrorView");
    props.setProperty("java.lang.NumberFormatException", "numberFormatErrorView");
    exceptionResolver.setExceptionMappings(props);
    ModelAndView mav = exceptionResolver.resolveException(request, response, handler, new Exception());
    assertEquals("genericErrorView", mav.getViewName());
    ModelAndView mav2 = exceptionResolver.resolveException(request, response, handler, new NumberFormatException());
    assertEquals("numberFormatErrorView", mav2.getViewName());
}
Example 21
Project: egovframework.rte.root-master  File: ExceptionResolverTest.java View source code
/**
	 * 
	 * 
	 * @throws Exception
	 */
@Test
public void testExceptionViewNameMapping() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();
    Object handler = new Object();
    Properties props = new Properties();
    props.setProperty("java.lang.Exception", "genericErrorView");
    props.setProperty("java.lang.NumberFormatException", "numberFormatErrorView");
    exceptionResolver.setExceptionMappings(props);
    ModelAndView mav = exceptionResolver.resolveException(request, response, handler, new Exception());
    assertEquals("genericErrorView", mav.getViewName());
    ModelAndView mav2 = exceptionResolver.resolveException(request, response, handler, new NumberFormatException());
    assertEquals("numberFormatErrorView", mav2.getViewName());
}
Example 22
Project: ieo-beast-master  File: Microsatellite.java View source code
/**
     *
     * @param srtRawLength  a String representing the raw length of a microsatellite allele in nucleotide units
     * @return int          the state of microsatellite allele corresponding to the length
     */
public int getState(String srtRawLength) {
    char chRawLength = srtRawLength.charAt(0);
    try {
        if (chRawLength == Microsatellite.UNKNOWN_CHARACTER) {
            return getState(UNKNOWN_STATE_LENGTH);
        } else {
            return getState(Integer.parseInt(srtRawLength));
        }
    } catch (java.lang.NumberFormatException exp) {
        throw new java.lang.NumberFormatException(srtRawLength + " can not be converted. State needs to be an integer or unknown (?).");
    }
}
Example 23
Project: xstream-for-android-master  File: ErrorTest.java View source code
public void testUnmarshallerThrowsExceptionWithDebuggingInfo() {
    try {
        xstream.fromXML("<thing>\n" + "  <one>string 1</one>\n" + "  <two>another string</two>\n" + "</thing>");
        fail("Error expected");
    } catch (ConversionException e) {
        assertEquals("java.lang.NumberFormatException", e.get("cause-exception"));
        if (JVM.is14()) {
            assertEquals("For input string: \"another string\"", e.get("cause-message"));
        } else {
            assertEquals("another string", e.get("cause-message"));
        }
        assertEquals(Thing.class.getName(), e.get("class"));
        assertEquals("/thing/two", e.get("path"));
        assertEquals("3", e.get("line number"));
        assertEquals("java.lang.Integer", e.get("required-type"));
    }
}
Example 24
Project: neembuunow-master  File: ImportYouTubeUserPlaylists.java View source code
/* Error */
private ArrayList<jp.co.asbit.pvstar.Video> getVideosFavorite(int paramInt) {
// Byte code:
//   0: new 44	java/util/ArrayList
//   3: dup
//   4: invokespecial 45	java/util/ArrayList:<init>	()V
//   7: astore_2
//   8: aconst_null
//   9: astore_3
//   10: aconst_null
//   11: astore 4
//   13: invokestatic 51	android/util/Xml:newPullParser	()Lorg/xmlpull/v1/XmlPullParser;
//   16: astore 13
//   18: iconst_2
//   19: anewarray 53	java/lang/Object
//   22: astore 14
//   24: aload 14
//   26: iconst_0
//   27: iconst_1
//   28: bipush 50
//   30: iload_1
//   31: iconst_1
//   32: isub
//   33: imul
//   34: iadd
//   35: invokestatic 59	java/lang/Integer:valueOf	(I)Ljava/lang/Integer;
//   38: aastore
//   39: aload 14
//   41: iconst_1
//   42: bipush 50
//   44: invokestatic 59	java/lang/Integer:valueOf	(I)Ljava/lang/Integer;
//   47: aastore
//   48: ldc 10
//   50: aload 14
//   52: invokestatic 65	java/lang/String:format	(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;
//   55: astore 15
//   57: new 67	java/net/URL
//   60: dup
//   61: aload 15
//   63: invokespecial 70	java/net/URL:<init>	(Ljava/lang/String;)V
//   66: astore 16
//   68: aload 16
//   70: invokevirtual 74	java/net/URL:openConnection	()Ljava/net/URLConnection;
//   73: checkcast 76	java/net/HttpURLConnection
//   76: astore_3
//   77: aload_3
//   78: ldc 78
//   80: new 80	java/lang/StringBuilder
//   83: dup
//   84: ldc 82
//   86: invokespecial 83	java/lang/StringBuilder:<init>	(Ljava/lang/String;)V
//   89: getstatic 88	jp/co/asbit/pvstar/video/YouTube:auth	Ljava/lang/String;
//   92: invokevirtual 92	java/lang/StringBuilder:append	(Ljava/lang/String;)Ljava/lang/StringBuilder;
//   95: invokevirtual 96	java/lang/StringBuilder:toString	()Ljava/lang/String;
//   98: invokevirtual 100	java/net/HttpURLConnection:setRequestProperty	(Ljava/lang/String;Ljava/lang/String;)V
//   101: aload_3
//   102: ldc 102
//   104: ldc 104
//   106: invokevirtual 100	java/net/HttpURLConnection:setRequestProperty	(Ljava/lang/String;Ljava/lang/String;)V
//   109: aload_3
//   110: sipush 5000
//   113: invokevirtual 108	java/net/HttpURLConnection:setReadTimeout	(I)V
//   116: aload_3
//   117: sipush 5000
//   120: invokevirtual 111	java/net/HttpURLConnection:setConnectTimeout	(I)V
//   123: aload_3
//   124: iconst_1
//   125: invokevirtual 115	java/net/HttpURLConnection:setUseCaches	(Z)V
//   128: aload_3
//   129: invokevirtual 119	java/net/HttpURLConnection:getInputStream	()Ljava/io/InputStream;
//   132: astore 4
//   134: aload 13
//   136: aload 4
//   138: ldc 121
//   140: invokeinterface 127 3 0
//   145: iconst_0
//   146: istore 17
//   148: aconst_null
//   149: astore 18
//   151: aconst_null
//   152: astore 19
//   154: aload 13
//   156: invokeinterface 131 1 0
//   161: istore 20
//   163: iload 20
//   165: istore 21
//   167: iload 21
//   169: iconst_1
//   170: if_icmpne +23 -> 193
//   173: aload_3
//   174: ifnull +7 -> 181
//   177: aload_3
//   178: invokevirtual 134	java/net/HttpURLConnection:disconnect	()V
//   181: aload 4
//   183: ifnull +601 -> 784
//   186: aload 4
//   188: invokevirtual 139	java/io/InputStream:close	()V
//   191: aload_2
//   192: areturn
//   193: iload 21
//   195: iconst_2
//   196: if_icmpne +174 -> 370
//   199: aload 13
//   201: invokeinterface 142 1 0
//   206: astore 19
//   208: aload 19
//   210: ldc 144
//   212: invokevirtual 148	java/lang/String:equals	(Ljava/lang/Object;)Z
//   215: ifeq +15 -> 230
//   218: iconst_1
//   219: istore 17
//   221: new 150	jp/co/asbit/pvstar/Video
//   224: dup
//   225: invokespecial 151	jp/co/asbit/pvstar/Video:<init>	()V
//   228: astore 18
//   230: iload 17
//   232: ifeq +138 -> 370
//   235: aload 19
//   237: ldc 153
//   239: invokevirtual 148	java/lang/String:equals	(Ljava/lang/Object;)Z
//   242: ifeq +32 -> 274
//   245: aload 13
//   247: aconst_null
//   248: ldc 155
//   250: invokeinterface 159 3 0
//   255: astore 35
//   257: aload 35
//   259: ldc 161
//   261: invokevirtual 165	java/lang/String:endsWith	(Ljava/lang/String;)Z
//   264: ifeq +10 -> 274
//   267: aload 18
//   269: aload 35
//   271: invokevirtual 168	jp/co/asbit/pvstar/Video:setThumbnailUrl	(Ljava/lang/String;)V
//   274: aload 19
//   276: ldc 170
//   278: invokevirtual 148	java/lang/String:equals	(Ljava/lang/Object;)Z
//   281: ifeq +89 -> 370
//   284: aload 13
//   286: aconst_null
//   287: ldc 172
//   289: invokeinterface 159 3 0
//   294: astore 30
//   296: aload 30
//   298: invokestatic 175	java/lang/Integer:valueOf	(Ljava/lang/String;)Ljava/lang/Integer;
//   301: invokevirtual 178	java/lang/Integer:intValue	()I
//   304: istore 31
//   306: aload 30
//   308: invokestatic 175	java/lang/Integer:valueOf	(Ljava/lang/String;)Ljava/lang/Integer;
//   311: invokevirtual 178	java/lang/Integer:intValue	()I
//   314: i2f
//   315: ldc 179
//   317: fdiv
//   318: f2d
//   319: invokestatic 185	java/lang/Math:floor	(D)D
//   322: d2i
//   323: istore 32
//   325: iload 31
//   327: i2f
//   328: ldc 179
//   330: frem
//   331: f2i
//   332: istore 33
//   334: iconst_2
//   335: anewarray 53	java/lang/Object
//   338: astore 34
//   340: aload 34
//   342: iconst_0
//   343: iload 32
//   345: invokestatic 59	java/lang/Integer:valueOf	(I)Ljava/lang/Integer;
//   348: aastore
//   349: aload 34
//   351: iconst_1
//   352: iload 33
//   354: invokestatic 59	java/lang/Integer:valueOf	(I)Ljava/lang/Integer;
//   357: aastore
//   358: aload 18
//   360: ldc 187
//   362: aload 34
//   364: invokestatic 65	java/lang/String:format	(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;
//   367: invokevirtual 190	jp/co/asbit/pvstar/Video:setDuration	(Ljava/lang/String;)V
//   370: iload 21
//   372: iconst_4
//   373: if_icmpne +196 -> 569
//   376: aload 13
//   378: invokeinterface 193 1 0
//   383: astore 24
//   385: aload 19
//   387: ldc 194
//   389: invokevirtual 148	java/lang/String:equals	(Ljava/lang/Object;)Z
//   392: ifeq +67 -> 459
//   395: aload_0
//   396: aload 24
//   398: invokestatic 175	java/lang/Integer:valueOf	(Ljava/lang/String;)Ljava/lang/Integer;
//   401: invokevirtual 178	java/lang/Integer:intValue	()I
//   404: putfield 30	jp/co/asbit/pvstar/api/ImportYouTubeUserPlaylists:totalResults	I
//   407: aload_0
//   408: getfield 30	jp/co/asbit/pvstar/api/ImportYouTubeUserPlaylists:totalResults	I
//   411: ifne +48 -> 459
//   414: aload_0
//   415: iconst_1
//   416: invokevirtual 198	jp/co/asbit/pvstar/api/ImportYouTubeUserPlaylists:cancel	(Z)Z
//   419: pop
//   420: aload_3
//   421: ifnull +7 -> 428
//   424: aload_3
//   425: invokevirtual 134	java/net/HttpURLConnection:disconnect	()V
//   428: aload_3
//   429: ifnull +7 -> 436
//   432: aload_3
//   433: invokevirtual 134	java/net/HttpURLConnection:disconnect	()V
//   436: aload 4
//   438: ifnull +8 -> 446
//   441: aload 4
//   443: invokevirtual 139	java/io/InputStream:close	()V
//   446: goto -255 -> 191
//   449: astore 29
//   451: aload 29
//   453: invokevirtual 201	java/lang/Exception:printStackTrace	()V
//   456: goto -10 -> 446
//   459: iload 17
//   461: ifeq +108 -> 569
//   464: aload 19
//   466: ldc 203
//   468: invokevirtual 148	java/lang/String:equals	(Ljava/lang/Object;)Z
//   471: ifeq +33 -> 504
//   474: aload 18
//   476: ldc 205
//   478: invokevirtual 208	jp/co/asbit/pvstar/Video:setSearchEngine	(Ljava/lang/String;)V
//   481: aload 24
//   483: ldc 210
//   485: invokevirtual 214	java/lang/String:split	(Ljava/lang/String;)[Ljava/lang/String;
//   488: astore 27
//   490: aload 18
//   492: aload 27
//   494: bipush 255
//   496: aload 27
//   498: arraylength
//   499: iadd
//   500: aaload
//   501: invokevirtual 217	jp/co/asbit/pvstar/Video:setId	(Ljava/lang/String;)V
//   504: aload 19
//   506: ldc 219
//   508: invokevirtual 148	java/lang/String:equals	(Ljava/lang/Object;)Z
//   511: ifeq +10 -> 521
//   514: aload 18
//   516: aload 24
//   518: invokevirtual 222	jp/co/asbit/pvstar/Video:setTitle	(Ljava/lang/String;)V
//   521: aload 19
//   523: ldc 224
//   525: invokevirtual 148	java/lang/String:equals	(Ljava/lang/Object;)Z
//   528: ifeq +41 -> 569
//   531: aload 24
//   533: bipush 10
//   535: bipush 32
//   537: invokevirtual 228	java/lang/String:replace	(CC)Ljava/lang/String;
//   540: astore 25
//   542: aload 25
//   544: invokevirtual 231	java/lang/String:length	()I
//   547: bipush 40
//   549: if_icmple +74 -> 623
//   552: aload 25
//   554: iconst_0
//   555: bipush 40
//   557: invokevirtual 235	java/lang/String:substring	(II)Ljava/lang/String;
//   560: astore 26
//   562: aload 18
//   564: aload 26
//   566: invokevirtual 238	jp/co/asbit/pvstar/Video:setDescription	(Ljava/lang/String;)V
//   569: iload 21
//   571: iconst_3
//   572: if_icmpne +35 -> 607
//   575: aload 13
//   577: invokeinterface 142 1 0
//   582: astore 19
//   584: aload 19
//   586: ldc 144
//   588: invokevirtual 148	java/lang/String:equals	(Ljava/lang/Object;)Z
//   591: ifeq +16 -> 607
//   594: aload_2
//   595: aload 18
//   597: invokevirtual 241	java/util/ArrayList:add	(Ljava/lang/Object;)Z
//   600: pop
//   601: iconst_0
//   602: istore 17
//   604: aconst_null
//   605: astore 19
//   607: aload 13
//   609: invokeinterface 244 1 0
//   614: istore 22
//   616: iload 22
//   618: istore 21
//   620: goto -453 -> 167
//   623: aload 25
//   625: astore 26
//   627: goto -65 -> 562
//   630: astore 11
//   632: aload 11
//   634: invokevirtual 245	org/xmlpull/v1/XmlPullParserException:printStackTrace	()V
//   637: aload_3
//   638: ifnull +7 -> 645
//   641: aload_3
//   642: invokevirtual 134	java/net/HttpURLConnection:disconnect	()V
//   645: aload 4
//   647: ifnull -456 -> 191
//   650: aload 4
//   652: invokevirtual 139	java/io/InputStream:close	()V
//   655: goto -464 -> 191
//   658: astore 12
//   660: aload 12
//   662: invokevirtual 201	java/lang/Exception:printStackTrace	()V
//   665: goto -474 -> 191
//   668: astore 9
//   670: aload 9
//   672: invokevirtual 246	java/io/IOException:printStackTrace	()V
//   675: aload_3
//   676: ifnull +7 -> 683
//   679: aload_3
//   680: invokevirtual 134	java/net/HttpURLConnection:disconnect	()V
//   683: aload 4
//   685: ifnull -494 -> 191
//   688: aload 4
//   690: invokevirtual 139	java/io/InputStream:close	()V
//   693: goto -502 -> 191
//   696: astore 10
//   698: aload 10
//   700: invokevirtual 201	java/lang/Exception:printStackTrace	()V
//   703: goto -512 -> 191
//   706: astore 7
//   708: aload 7
//   710: invokevirtual 247	java/lang/NumberFormatException:printStackTrace	()V
//   713: aload_3
//   714: ifnull +7 -> 721
//   717: aload_3
//   718: invokevirtual 134	java/net/HttpURLConnection:disconnect	()V
//   721: aload 4
//   723: ifnull -532 -> 191
//   726: aload 4
//   728: invokevirtual 139	java/io/InputStream:close	()V
//   731: goto -540 -> 191
//   734: astore 8
//   736: aload 8
//   738: invokevirtual 201	java/lang/Exception:printStackTrace	()V
//   741: goto -550 -> 191
//   744: astore 5
//   746: aload_3
//   747: ifnull +7 -> 754
//   750: aload_3
//   751: invokevirtual 134	java/net/HttpURLConnection:disconnect	()V
//   754: aload 4
//   756: ifnull +8 -> 764
//   759: aload 4
//   761: invokevirtual 139	java/io/InputStream:close	()V
//   764: aload 5
//   766: athrow
//   767: astore 6
//   769: aload 6
//   771: invokevirtual 201	java/lang/Exception:printStackTrace	()V
//   774: goto -10 -> 764
//   777: astore 36
//   779: aload 36
//   781: invokevirtual 201	java/lang/Exception:printStackTrace	()V
//   784: goto -593 -> 191
//   787: astore 5
//   789: goto -43 -> 746
//   792: astore 7
//   794: goto -86 -> 708
//   797: astore 9
//   799: goto -129 -> 670
//   802: astore 11
//   804: goto -172 -> 632
// Local variable table:
//   start	length	slot	name	signature
//   0	807	0	this	ImportYouTubeUserPlaylists
//   0	807	1	paramInt	int
//   7	588	2	localArrayList	ArrayList
//   9	742	3	localHttpURLConnection	java.net.HttpURLConnection
//   11	749	4	localInputStream	java.io.InputStream
//   744	21	5	localObject1	java.lang.Object
//   787	1	5	localObject2	java.lang.Object
//   767	3	6	localException1	Exception
//   706	3	7	localNumberFormatException1	java.lang.NumberFormatException
//   792	1	7	localNumberFormatException2	java.lang.NumberFormatException
//   734	3	8	localException2	Exception
//   668	3	9	localIOException1	java.io.IOException
//   797	1	9	localIOException2	java.io.IOException
//   696	3	10	localException3	Exception
//   630	3	11	localXmlPullParserException1	org.xmlpull.v1.XmlPullParserException
//   802	1	11	localXmlPullParserException2	org.xmlpull.v1.XmlPullParserException
//   658	3	12	localException4	Exception
//   16	592	13	localXmlPullParser	org.xmlpull.v1.XmlPullParser
//   22	29	14	arrayOfObject1	java.lang.Object[]
//   55	7	15	str1	String
//   66	3	16	localURL	java.net.URL
//   146	457	17	i	int
//   149	447	18	localVideo	jp.co.asbit.pvstar.Video
//   152	454	19	str2	String
//   161	3	20	j	int
//   165	454	21	k	int
//   614	3	22	m	int
//   383	149	24	str3	String
//   540	84	25	str4	String
//   560	66	26	str5	String
//   488	9	27	arrayOfString	String[]
//   449	3	29	localException5	Exception
//   294	13	30	str6	String
//   304	22	31	n	int
//   323	21	32	i1	int
//   332	21	33	i2	int
//   338	25	34	arrayOfObject2	java.lang.Object[]
//   255	15	35	str7	String
//   777	3	36	localException6	Exception
// Exception table:
//   from	to	target	type
//   432	446	449	java/lang/Exception
//   13	68	630	org/xmlpull/v1/XmlPullParserException
//   641	655	658	java/lang/Exception
//   13	68	668	java/io/IOException
//   679	693	696	java/lang/Exception
//   13	68	706	java/lang/NumberFormatException
//   717	731	734	java/lang/Exception
//   13	68	744	finally
//   632	637	744	finally
//   670	675	744	finally
//   708	713	744	finally
//   750	764	767	java/lang/Exception
//   177	191	777	java/lang/Exception
//   68	163	787	finally
//   199	428	787	finally
//   464	616	787	finally
//   68	163	792	java/lang/NumberFormatException
//   199	428	792	java/lang/NumberFormatException
//   464	616	792	java/lang/NumberFormatException
//   68	163	797	java/io/IOException
//   199	428	797	java/io/IOException
//   464	616	797	java/io/IOException
//   68	163	802	org/xmlpull/v1/XmlPullParserException
//   199	428	802	org/xmlpull/v1/XmlPullParserException
//   464	616	802	org/xmlpull/v1/XmlPullParserException
}
Example 25
Project: viutils-master  File: UnmodifiablePropertiesFile.java View source code
/**
     * {@inheritDoc}
     *
     * @throws java.lang.NullPointerException
     *         if {@code key} is null
     * @throws java.lang.IllegalArgumentException
     *         if {@code key} is empty
     * @throws net.visualillusionsent.utils.UnknownPropertyException
     *         if the {@code key} does not exist
     * @throws java.lang.NumberFormatException
     *         if a value is not a number or out of range
     */
@Override
public final byte getByte(String key) {
    notNull(key, "String key");
    if (numberCache.containsKey(key)) {
        // Caching check
        return numberCache.get(key).byteValue();
    }
    try {
        // decode
        byte value = Byte.decode(getString(key));
        // Cache
        numberCache.put(key, value);
        return value;
    } catch (NumberFormatException nfe) {
        throw new NumberFormatException(Verify.parse("prop.nan", key));
    }
}
Example 26
Project: musique-master  File: WvEncode.java View source code
public static void main(String[] args) {
    // This is the main module for the demonstration WavPack command-line
    // encoder using the "tiny encoder". It accepts a source WAV file, a
    // destination WavPack file (.wv) and an optional WavPack correction file
    // (.wvc) on the command-line. It supports all 4 encoding qualities in
    // pure lossless, hybrid lossy and hybrid lossless modes. Valid input are
    // mono or stereo integer WAV files with bitdepths from 8 to 24.
    // This program (and the tiny encoder) do not handle placing the WAV RIFF
    // header into the WavPack file. The latest version of the regular WavPack
    // unpacker (4.40) and the "tiny decoder" will generate the RIFF header
    // automatically on unpacking. However, older versions of the command-line
    // program will complain about this and require unpacking in "raw" mode.
    ///////////////////////////// local variable storage //////////////////////////
    String VERSION_STR = "4.40";
    String DATE_STR = "2007-01-16";
    String sign_on1 = "Java WavPack Encoder (c) 2008 Peter McQuillan";
    String sign_on2 = "based on TINYPACK - Tiny Audio Compressor  Version " + VERSION_STR + " " + DATE_STR + " Copyright (c) 1998 - 2007 Conifer Software.  All Rights Reserved.";
    String usage0 = "";
    String usage1 = " Usage:   java WvEncode [-options] infile.wav outfile.wv [outfile.wvc]";
    String usage2 = " (default is lossless)";
    String usage3 = "  Options: -b n = enable hybrid compression, n = 2.0 to 16.0 bits/sample - need space between b and number";
    String usage4 = "       -c  = create correction file (.wvc) for hybrid mode (=lossless)";
    String usage5 = "       -cc = maximum hybrid compression (hurts lossy quality & decode speed)";
    String usage6 = "       -f  = fast mode (fast, but some compromise in compression ratio)";
    String usage7 = "       -h  = high quality (better compression in all modes, but slower)";
    String usage8 = "       -hh = very high quality (best compression in all modes, but slowest";
    String usage9 = "                              and NOT recommended for portable hardware use)";
    String usage10 = "       -jn = joint-stereo override (0 = left/right, 1 = mid/side)";
    String usage11 = "       -sn = noise shaping override (hybrid only, n = -1.0 to 1.0, 0 = off)";
    //////////////////////////////////////////////////////////////////////////////
    // The "main" function for the command-line WavPack compressor.             //
    //////////////////////////////////////////////////////////////////////////////
    String infilename = "";
    String outfilename = "";
    String out2filename = "";
    WavpackConfig config = new WavpackConfig();
    int error_count = 0;
    int result;
    int i;
    int arg_idx = 0;
    // loop through command-line arguments
    while (arg_idx < args.length) {
        if (args[arg_idx].startsWith("-")) {
            if (args[arg_idx].startsWith("-c") || args[arg_idx].startsWith("-C")) {
                if (args[arg_idx].startsWith("-cc") || args[arg_idx].startsWith("-CC")) {
                    config.flags |= Defines.CONFIG_CREATE_WVC;
                    config.flags |= Defines.CONFIG_OPTIMIZE_WVC;
                } else {
                    config.flags |= Defines.CONFIG_CREATE_WVC;
                }
            } else if (args[arg_idx].startsWith("-f") || args[arg_idx].startsWith("-F")) {
                config.flags |= Defines.CONFIG_FAST_FLAG;
            } else if (args[arg_idx].startsWith("-h") || args[arg_idx].startsWith("-H")) {
                if (args[arg_idx].startsWith("-hh") || args[arg_idx].startsWith("-HH")) {
                    config.flags |= Defines.CONFIG_VERY_HIGH_FLAG;
                } else {
                    config.flags |= Defines.CONFIG_HIGH_FLAG;
                }
            } else if (args[arg_idx].startsWith("-k") || args[arg_idx].startsWith("-K")) {
                int passedInt = 0;
                if (args[arg_idx].length() > 2) {
                    try {
                        String substring = args[arg_idx].substring(2);
                        passedInt = Integer.parseInt(substring);
                    } catch (java.lang.NumberFormatException ne) {
                    }
                } else {
                    arg_idx++;
                    try {
                        passedInt = Integer.parseInt(args[arg_idx]);
                    } catch (java.lang.NumberFormatException ne) {
                    }
                }
                config.block_samples = passedInt;
            } else if (args[arg_idx].startsWith("-b") || args[arg_idx].startsWith("-B")) {
                int passedInt = 0;
                config.flags |= Defines.CONFIG_HYBRID_FLAG;
                if (args[arg_idx].length() > 2) {
                    try {
                        String substring = args[arg_idx].substring(2);
                        passedInt = Integer.parseInt(substring);
                        config.bitrate = (int) (passedInt * 256.0);
                    } catch (java.lang.NumberFormatException ne) {
                        config.bitrate = 0;
                    }
                } else {
                    arg_idx++;
                    try {
                        passedInt = Integer.parseInt(args[arg_idx]);
                        config.bitrate = (int) (passedInt * 256.0);
                    } catch (java.lang.NumberFormatException ne) {
                        config.bitrate = 0;
                    }
                }
                if ((config.bitrate < 512) || (config.bitrate > 4096)) {
                    System.err.println("hybrid spec must be 2.0 to 16.0!");
                    ++error_count;
                }
            } else if (args[arg_idx].startsWith("-j") || args[arg_idx].startsWith("-J")) {
                int passedInt = 2;
                if (// handle the case where the string is passed in form -j0 (number beside j)
                args[arg_idx].length() > 2) {
                    try {
                        String substring = args[arg_idx].substring(2);
                        passedInt = Integer.parseInt(substring);
                    } catch (java.lang.NumberFormatException ne) {
                    }
                } else // handle the case where the string is passed in form -j 0 (space between number and j)
                {
                    arg_idx++;
                    try {
                        passedInt = Integer.parseInt(args[arg_idx]);
                    } catch (java.lang.NumberFormatException ne) {
                    }
                }
                if (passedInt == 0) {
                    config.flags |= Defines.CONFIG_JOINT_OVERRIDE;
                    config.flags &= ~Defines.CONFIG_JOINT_STEREO;
                } else if (passedInt == 1) {
                    config.flags |= (Defines.CONFIG_JOINT_OVERRIDE | Defines.CONFIG_JOINT_STEREO);
                } else {
                    System.err.println("-j0 or -j1 only!");
                    ++error_count;
                }
            } else if (args[arg_idx].startsWith("-s") || args[arg_idx].startsWith("-S")) {
                // noise shaping off
                double passedDouble = 0;
                if (// handle the case where the string is passed in form -s0 (number beside s)
                args[arg_idx].length() > 2) {
                    try {
                        String substring = args[arg_idx].substring(2);
                        passedDouble = Double.parseDouble(substring);
                    } catch (java.lang.NumberFormatException ne) {
                    }
                } else // handle the case where the string is passed in form -s 0 (space between number and s)
                {
                    arg_idx++;
                    try {
                        passedDouble = Double.parseDouble(args[arg_idx]);
                    } catch (java.lang.NumberFormatException ne) {
                    }
                }
                config.shaping_weight = (int) (passedDouble * 1024.0);
                if (config.shaping_weight == 0) {
                    config.flags |= Defines.CONFIG_SHAPE_OVERRIDE;
                    config.flags &= ~Defines.CONFIG_HYBRID_SHAPE;
                } else if ((config.shaping_weight >= -1024) && (config.shaping_weight <= 1024)) {
                    config.flags |= (Defines.CONFIG_HYBRID_SHAPE | Defines.CONFIG_SHAPE_OVERRIDE);
                } else {
                    System.err.println("-s-1.00 to -s1.00 only!");
                    ++error_count;
                }
            } else {
                System.err.println("illegal option: " + args[arg_idx]);
                ++error_count;
            }
        } else if (infilename.length() == 0) {
            infilename = args[arg_idx];
        } else if (outfilename.length() == 0) {
            outfilename = args[arg_idx];
        } else if (out2filename.length() == 0) {
            out2filename = args[arg_idx];
        } else {
            System.err.println("extra unknown argument: " + args[arg_idx]);
            ++error_count;
        }
        arg_idx++;
    }
    // check for various command-line argument problems
    if ((~config.flags & (Defines.CONFIG_HIGH_FLAG | Defines.CONFIG_FAST_FLAG)) == 0) {
        System.err.println("high and fast modes are mutually exclusive!");
        ++error_count;
    }
    if ((config.flags & Defines.CONFIG_HYBRID_FLAG) != 0) {
        if (((config.flags & Defines.CONFIG_CREATE_WVC) != 0) && (out2filename.length() == 0)) {
            System.err.println("need name for correction file!");
            ++error_count;
        }
    } else {
        if ((config.flags & (Defines.CONFIG_SHAPE_OVERRIDE | Defines.CONFIG_CREATE_WVC)) != 0) {
            System.err.println("-s and -c options are for hybrid mode (-b) only!");
            ++error_count;
        }
    }
    if ((out2filename.length() != 0) && ((config.flags & Defines.CONFIG_CREATE_WVC) == 0)) {
        System.err.println("third filename specified without -c option!");
        ++error_count;
    }
    if (error_count == 0) {
        System.err.println(sign_on1);
        System.err.println(sign_on2);
    } else {
        System.exit(1);
    }
    if ((infilename.length() == 0) || (outfilename.length() == 0) || ((out2filename.length() == 0) && ((config.flags & Defines.CONFIG_CREATE_WVC) != 0))) {
        System.out.println(usage0);
        System.out.println(usage1);
        System.out.println(usage2);
        System.out.println(usage3);
        System.out.println(usage4);
        System.out.println(usage5);
        System.out.println(usage6);
        System.out.println(usage7);
        System.out.println(usage8);
        System.out.println(usage9);
        System.out.println(usage10);
        System.out.println(usage11);
        System.exit(1);
    }
    result = pack_file(infilename, outfilename, out2filename, config);
    if (result > 0) {
        System.err.println("error occured!");
        ++error_count;
    }
}
Example 27
Project: EclipseTrader-master  File: SocketMin.java View source code
static void init(String host, String portStr) {
    Logger root = Logger.getRootLogger();
    BasicConfigurator.configure();
    try {
        int port = Integer.parseInt(portStr);
        cat.info("Creating socket appender (" + host + "," + port + ").");
        s = new SocketAppender(host, port);
        s.setName("S");
        root.addAppender(s);
    } catch (java.lang.NumberFormatException e) {
        e.printStackTrace();
        usage("Could not interpret port number [" + portStr + "].");
    } catch (Exception e) {
        System.err.println("Could not start!");
        e.printStackTrace();
        System.exit(1);
    }
}
Example 28
Project: eXist-1.4.x-master  File: RequestDecoder.java View source code
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    byte b;
    while (true) {
        //TODO: limit length to avoid "OutOfMemory"
        if (length == null) {
            if (in.remaining() > 0) {
                b = in.get();
                if (b == (byte) 0) {
                    try {
                        length = Integer.valueOf(sLength);
                    } catch (java.lang.NumberFormatException e) {
                        length = null;
                        sLength = "";
                    }
                    continue;
                }
                sLength += (char) b;
            } else {
                return false;
            }
        } else if (in.remaining() >= length) {
            ResponseImpl response = new ResponseImpl(session, in.getSlice(length).asInputStream());
            if (response.isValid())
                response.getDebugger().addResponse(response);
            length = null;
            sLength = "";
            return true;
        } else {
            return false;
        }
    }
}
Example 29
Project: exist-master  File: RequestDecoder.java View source code
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    byte b;
    while (true) {
        //TODO: limit length to avoid "OutOfMemory"
        if (length == null) {
            if (in.remaining() > 0) {
                b = in.get();
                if (b == (byte) 0) {
                    try {
                        length = Integer.valueOf(sLength);
                    } catch (java.lang.NumberFormatException e) {
                        length = null;
                        sLength = "";
                    }
                    continue;
                }
                sLength += (char) b;
            } else {
                return false;
            }
        } else if (in.remaining() >= length) {
            ResponseImpl response = new ResponseImpl(session, in.getSlice(length).asInputStream());
            if (response.isValid())
                response.getDebugger().addResponse(response);
            length = null;
            sLength = "";
            return true;
        } else {
            return false;
        }
    }
}
Example 30
Project: jPOS-master  File: SMExceptionTest.java View source code
@Test
public void testConstructor() throws Throwable {
    Exception e = new NumberFormatException("testSMExceptionParam1");
    SMException sMException = new SMException(e);
    assertEquals("sMException.getMessage()", "java.lang.NumberFormatException: testSMExceptionParam1", sMException.getMessage());
    assertNull("sMException.nested", sMException.nested);
    assertSame("sMException.getNested()", e, sMException.getNested());
}
Example 31
Project: logback-master  File: SocketMin.java View source code
static void init(String host, String portStr) {
    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    BasicConfigurator bc = new BasicConfigurator();
    bc.setContext(root.getLoggerContext());
    bc.configure(root.getLoggerContext());
    try {
        int port = Integer.parseInt(portStr);
        logger.info("Creating socket appender (" + host + "," + port + ").");
        s = new SocketAppender();
        s.setRemoteHost(host);
        s.setPort(port);
        s.setName("S");
        root.addAppender(s);
    } catch (java.lang.NumberFormatException e) {
        e.printStackTrace();
        usage("Could not interpret port number [" + portStr + "].");
    } catch (Exception e) {
        System.err.println("Could not start!");
        e.printStackTrace();
        System.exit(1);
    }
}
Example 32
Project: many-ql-master  File: NumberPrimitive.java View source code
@Override
public void drawQuestion(VBox questionArea, QLGUI qlGui) {
    TextField textField = new TextField();
    textField.getStyleClass().add("question");
    textField.setMaxWidth(100);
    if (value != null)
        textField.setText(value.toString());
    else if (negative)
        textField.setText("-");
    if (qlGui.getFocusUuid() == uuid)
        qlGui.setFocusedNode(textField);
    textField.positionCaret(textField.getLength());
    // Disable any input other than numbers
    textField.textProperty().addListener(( observable,  oldValue,  newValue) -> {
        if (newValue.matches("-?[0-9]*")) {
            if (newValue.length() == 0) {
                value = null;
                negative = false;
            } else if (newValue.equals("-")) {
                value = null;
                negative = true;
            } else {
                // Catch integer overflow
                try {
                    value = Integer.parseInt(newValue);
                } catch (java.lang.NumberFormatException ex) {
                    if (negative)
                        value = Integer.MIN_VALUE;
                    else
                        value = Integer.MAX_VALUE;
                }
            }
        }
        qlGui.renderWithFocus(uuid);
    });
    questionArea.getChildren().add(textField);
}
Example 33
Project: mobicents-master  File: DTMFUtils.java View source code
public static boolean updateBoothNumber(SipSession session, String signal) {
    int cause = -1;
    try {
        cause = Integer.parseInt(signal);
    } catch (java.lang.NumberFormatException e) {
        logger.info("Booth Number is = " + (String) session.getAttribute("boothNumber"));
        return true;
    }
    synchronized (session) {
        String boothNumber = (String) session.getAttribute("boothNumber");
        if (boothNumber == null) {
            boothNumber = "";
        }
        switch(cause) {
            case 0:
                boothNumber = boothNumber + "0";
                break;
            case 1:
                boothNumber = boothNumber + "1";
                break;
            case 2:
                boothNumber = boothNumber + "2";
                break;
            case 3:
                boothNumber = boothNumber + "3";
                break;
            case 4:
                boothNumber = boothNumber + "4";
                break;
            case 5:
                boothNumber = boothNumber + "5";
                break;
            case 6:
                boothNumber = boothNumber + "6";
                break;
            case 7:
                boothNumber = boothNumber + "7";
                break;
            case 8:
                boothNumber = boothNumber + "8";
                break;
            case 9:
                boothNumber = boothNumber + "9";
                break;
            default:
                break;
        }
        session.setAttribute("boothNumber", boothNumber);
    }
    return false;
}
Example 34
Project: SyncNBT-master  File: SyncNBT.java View source code
/**
   * This method listens for commands typed by the player.
   * /itemsync status
   * /itemsync mode [int]
   */
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (cmd.getName().equalsIgnoreCase("itemsync")) {
        if (args.length > 1 && args[0].equalsIgnoreCase("mode")) {
            try {
                db.setSetting(sender.getName(), new Integer(args[1]));
                return true;
            } catch (java.lang.NumberFormatException e) {
                sender.sendMessage("A number, the 2nd should be a parameter");
            }
        } else if (args.length > 0 && args[0].equalsIgnoreCase("status")) {
            int setting = db.getSetting(sender.getName());
            sender.sendMessage("The current itemsync mode is: " + setting);
            return true;
        }
    }
    return false;
}
Example 35
Project: XSLT-master  File: RequestDecoder.java View source code
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    byte b;
    while (true) {
        //TODO: limit length to avoid "OutOfMemory"
        if (length == null) {
            if (in.remaining() > 0) {
                b = in.get();
                if (b == (byte) 0) {
                    try {
                        length = Integer.valueOf(sLength);
                    } catch (java.lang.NumberFormatException e) {
                        length = null;
                        sLength = "";
                    }
                    continue;
                }
                sLength += (char) b;
            } else {
                return false;
            }
        } else if (in.remaining() >= length) {
            ResponseImpl response = new ResponseImpl(session, in.getSlice(length).asInputStream());
            if (response.isValid())
                response.getDebugger().addResponse(response);
            length = null;
            sLength = "";
            return true;
        } else {
            return false;
        }
    }
}
Example 36
Project: zhong-master  File: Utils.java View source code
public static long sizeFromStr(String sizeStr) {
    if (TextUtils.isEmpty(sizeStr)) {
        return 0;
    } else {
        if (sizeStr.endsWith("K") || sizeStr.endsWith("k")) {
            return (long) (1024 * Float.valueOf(sizeStr.substring(0, sizeStr.length() - 1)));
        } else if (sizeStr.endsWith("M") || sizeStr.endsWith("m")) {
            return (long) (1024 * 1024 * Float.valueOf(sizeStr.substring(0, sizeStr.length() - 1)));
        } else {
            try {
                return Long.valueOf(sizeStr);
            } catch (java.lang.NumberFormatException e) {
                e.printStackTrace();
                return 0;
            }
        }
    }
}
Example 37
Project: extdirectspring-master  File: ExceptionHandlingConfigInXmlTest.java View source code
@Test
public void testExceptionInMapping() throws Exception {
    String edRequest = ControllerUtil.createEdsRequest("remoteProviderSimple", "method4b", 2, new Object[] { 3, "xxx", "string.param" });
    MvcResult result = ControllerUtil.performRouterRequest(this.mockMvc, edRequest);
    List<ExtDirectResponse> responses = ControllerUtil.readDirectResponses(result.getResponse().getContentAsByteArray());
    assertThat(responses).hasSize(1);
    ExtDirectResponse resp = responses.get(0);
    assertThat(resp.getAction()).isEqualTo("remoteProviderSimple");
    assertThat(resp.getMethod()).isEqualTo("method4b");
    assertThat(resp.getType()).isEqualTo("exception");
    assertThat(resp.getTid()).isEqualTo(2);
    assertThat(resp.getMessage()).isEqualTo("there is something wrong");
    assertThat(resp.getResult()).isNull();
    assertThat(resp.getWhere()).startsWith("java.lang.NumberFormatException: For input string: \"xxx\"");
}
Example 38
Project: hudson_plugins-master  File: PerfPublisherPublisher.java View source code
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
    PrintStream logger = listener.getLogger();
    /**
		 * Compute metrics parametring
		 */
    Map<String, String> list_metrics = new HashMap<String, String>();
    //Format : name=xmlfield;
    if (metrics != null && metrics.length() > 0) {
        List<String> tmps = Arrays.asList(this.metrics.split(";"));
        for (String tmp : tmps) {
            List<String> f = Arrays.asList(tmp.split("="));
            if (f.size() == 2 && f.get(0).trim().length() > 0 && f.get(1).length() > 0) {
                list_metrics.put(f.get(0).trim(), f.get(1).trim());
            }
        }
    }
    /**
		 * Compute the HealthDescription
		 */
    HealthDescriptor hl = new HealthDescriptor();
    try {
        hl.setMaxHealth(Integer.parseInt(unhealthy));
    } catch (java.lang.NumberFormatException e) {
        hl.setMaxHealth(0);
    }
    try {
        hl.setMinHealth(Integer.parseInt(healthy));
    } catch (java.lang.NumberFormatException e) {
        hl.setMinHealth(0);
    }
    try {
        hl.setUnstableHealth(Integer.parseInt(threshold));
    } catch (java.lang.NumberFormatException e) {
        hl.setUnstableHealth(0);
    }
    /**
		 * Define if we must parse multiple file by searching for , in the name
		 * var
		 */
    String[] files = name.split(",");
    if (files.length > 1) {
        logger.println("[CapsAnalysis] Multiple reports detected.");
    }
    ArrayList<String> filesToParse = new ArrayList<String>();
    for (int i = 0; i < files.length; i++) {
        FileSet fileSet = new FileSet();
        File workspace = new File(build.getWorkspace().toURI());
        fileSet.setDir(workspace);
        fileSet.setIncludes(files[i].trim());
        Project antProject = new Project();
        fileSet.setProject(antProject);
        String[] tmp_files = fileSet.getDirectoryScanner(antProject).getIncludedFiles();
        for (int j = 0; j < tmp_files.length; j++) {
            if (build.getProject().getWorkspace().child(tmp_files[j]).exists()) {
                filesToParse.add(tmp_files[j]);
            } else {
                logger.println("[CapsAnalysis] Impossible to analyse report " + tmp_files[j] + " file not found!");
                build.setResult(Result.UNSTABLE);
            }
        }
    }
    try {
        build.addAction(new PerfPublisherBuildAction(build, filesToParse, logger, hl, list_metrics));
    } catch (PerfPublisherParseException gpe) {
        logger.println("[CapsAnalysis] generating reports analysis failed!");
        build.setResult(Result.UNSTABLE);
    }
    return true;
}
Example 39
Project: jeql-master  File: Dbf.java View source code
/**
     * Parses the record stored in the StringBuffer rec into a vector of
     * objects
     * @param StringBuffer rec - the record to be parsed.
     */
public Vector ParseRecord(StringBuffer rec) {
    Vector record = new Vector(numfields);
    String t;
    Integer I = new Integer(0);
    Float F = new Float(0.0);
    t = rec.toString();
    for (int i = 0; i < numfields; i++) {
        if (DEBUG)
            System.out.println(DBC + "type " + fielddef[i].fieldtype);
        if (DEBUG)
            System.out.println(DBC + "start " + fielddef[i].fieldstart);
        if (DEBUG)
            System.out.println(DBC + "len " + fielddef[i].fieldlen);
        if (DEBUG)
            System.out.println(DBC + "" + t.substring(fielddef[i].fieldstart, fielddef[i].fieldstart + fielddef[i].fieldlen));
        switch(fielddef[i].fieldtype) {
            case 'C':
                record.addElement(t.substring(fielddef[i].fieldstart, fielddef[i].fieldstart + fielddef[i].fieldlen));
                break;
            case 'N':
            case 'F':
                if (fielddef[i].fieldnumdec == 0)
                    try {
                        record.addElement(I.decode(t.substring(fielddef[i].fieldstart, fielddef[i].fieldstart + fielddef[i].fieldlen)));
                    } catch (java.lang.NumberFormatException e) {
                        record.addElement(new Integer(0));
                    }
                else
                    try {
                        record.addElement(F.valueOf(t.substring(fielddef[i].fieldstart, fielddef[i].fieldstart + fielddef[i].fieldlen)));
                    } catch (java.lang.NumberFormatException e) {
                        record.addElement(new Float(0.0));
                    }
                break;
            default:
                if (DEBUG)
                    System.out.println(DBC + "Oh - don't know how to parse " + fielddef[i].fieldtype);
        }
    }
    return record;
}
Example 40
Project: activemq-artemis-master  File: MessagePropertyConversionTest.java View source code
/**
    * if a property is set as a <code>java.lang.String</code>,
    * to get it as a <code>double</code> throws a <code>java.lang.NuberFormatException</code>
    * if the <code>String</code> is not a correct representation for a <code>double</code>
    * (e.g. <code>"not a number"</code>).
    */
@Test
public void testString2Double_2() {
    try {
        Message message = senderSession.createMessage();
        message.setStringProperty("pi", "not_a_number");
        message.getDoubleProperty("pi");
        Assert.fail("sec. 3.5.4 The String to numeric conversions must throw the java.lang.NumberFormatException " + " if the numeric's valueOf() method does not accept the String value as a valid representation.\n");
    } catch (java.lang.NumberFormatException e) {
    } catch (JMSException e) {
        fail(e);
    }
}
Example 41
Project: JavaFastPFOR-master  File: BenchmarkCSV.java View source code
private static ArrayList<int[]> loadIntegers(final String filename, final Format f) throws IOException {
    int misparsed = 0;
    if (f == Format.ONEARRAYPERLINE) {
        ArrayList<int[]> answer = new ArrayList<int[]>();
        BufferedReader br = new BufferedReader(new FileReader(filename));
        String s;
        while ((s = br.readLine()) != null) {
            // that's
            String[] numbers = s.split("[,;;]");
            // slow
            int[] a = new int[numbers.length];
            for (int k = 0; k < numbers.length; ++k) {
                try {
                    a[k] = Integer.parseInt(numbers[k].trim());
                } catch (java.lang.NumberFormatException nfe) {
                    if (misparsed == 0)
                        System.err.println(nfe);
                    ++misparsed;
                }
            }
            answer.add(a);
        }
        if (misparsed > 0)
            System.out.println("Failed to parse " + misparsed + " entries");
        br.close();
        return answer;
    } else if (f == Format.ONEARRAYPERFILE) {
        ArrayList<Integer> answer = new ArrayList<Integer>();
        BufferedReader br = new BufferedReader(new FileReader(filename));
        String s;
        while ((s = br.readLine()) != null) {
            // that's
            String[] numbers = s.split("[,;;]");
            // slow
            for (int k = 0; k < numbers.length; ++k) {
                try {
                    answer.add(Integer.parseInt(numbers[k].trim()));
                } catch (java.lang.NumberFormatException nfe) {
                    if (misparsed == 0)
                        System.err.println(nfe);
                    ++misparsed;
                }
            }
        }
        int[] actualanswer = new int[answer.size()];
        for (int i = 0; i < answer.size(); ++i) actualanswer[i] = answer.get(i);
        ArrayList<int[]> wrap = new ArrayList<int[]>();
        wrap.add(actualanswer);
        if (misparsed > 0)
            System.out.println("Failed to parse " + misparsed + " entries");
        br.close();
        return wrap;
    } else {
        ArrayList<Integer> answer = new ArrayList<Integer>();
        BufferedReader br = new BufferedReader(new FileReader(filename));
        String s;
        while ((s = br.readLine()) != null) {
            try {
                answer.add(Integer.parseInt(s.trim()));
            } catch (java.lang.NumberFormatException nfe) {
                if (misparsed == 0)
                    System.err.println(nfe);
                ++misparsed;
            }
        }
        int[] actualanswer = new int[answer.size()];
        for (int i = 0; i < answer.size(); ++i) actualanswer[i] = answer.get(i);
        ArrayList<int[]> wrap = new ArrayList<int[]>();
        wrap.add(actualanswer);
        if (misparsed > 0)
            System.out.println("Failed to parse " + misparsed + " entries");
        br.close();
        return wrap;
    }
}
Example 42
Project: JCGO-master  File: JdbcOdbcObject.java View source code
//--------------------------------------------------------------------
// hexPairToInt
// Converts a 2 character hexadecimal pair into an integer (the
// first 2 characters of the string are used)
//--------------------------------------------------------------------
public static int hexPairToInt(String inString) throws java.lang.NumberFormatException {
    String digits = "0123456789ABCDEF";
    String s = inString.toUpperCase();
    int n = 0;
    int thisDigit = 0;
    int sLen = s.length();
    if (sLen > 2) {
        sLen = 2;
    }
    for (int i = 0; i < sLen; i++) {
        thisDigit = digits.indexOf(s.substring(i, i + 1));
        // Invalid hex character
        if (thisDigit < 0) {
            throw new java.lang.NumberFormatException();
        }
        if (i == 0) {
            thisDigit *= 0x10;
        }
        n += thisDigit;
    }
    return n;
}
Example 43
Project: agile4techos-master  File: Sort.java View source code
public static void main(String[] args) {
    if (args.length != 2) {
        usage("Incorrect number of parameters.");
    }
    int arraySize = -1;
    try {
        arraySize = Integer.valueOf(args[1]).intValue();
        if (arraySize <= 0)
            usage("Negative array size.");
    } catch (java.lang.NumberFormatException e) {
        usage("Could not number format [" + args[1] + "].");
    }
    PropertyConfigurator.configure(args[0]);
    int[] intArray = new int[arraySize];
    logger.info("Populating an array of " + arraySize + " elements in" + " reverse order.");
    for (int i = arraySize - 1; i >= 0; i--) {
        intArray[i] = arraySize - i - 1;
    }
    SortAlgo sa1 = new SortAlgo(intArray);
    sa1.bubbleSort();
    sa1.dump();
    // We intentionally initilize sa2 with null.
    SortAlgo sa2 = new SortAlgo(null);
    logger.info("The next log statement should be an error message.");
    sa2.dump();
    logger.info("Exiting main method.");
}
Example 44
Project: codjo-standalone-common-master  File: NumberFieldImport.java View source code
/**
     * Traduction du champ en objet Integer ou Float.
     *
     * @param field Champ à traduire.
     *
     * @return Le champ en format SQL.
     *
     * @throws BadFormatException Mauvais format de nombre
     */
@Override
public Object translateField(String field) throws BadFormatException {
    if (field == null) {
        return null;
    }
    field = StringUtil.removeAllCharOccurrence(field, ' ');
    if ("".equals(field)) {
        return null;
    }
    try {
        if (isInteger) {
            return new Integer(field);
        } else {
            return parseDecimal(field);
        }
    } catch (java.lang.NumberFormatException ex) {
        throw new BadFormatException(this, ex.getMessage());
    }
}
Example 45
Project: CS_Coursework-master  File: SimpleSocketServer.java View source code
static void init(String portStr, String configFile) {
    try {
        port = Integer.parseInt(portStr);
    } catch (java.lang.NumberFormatException e) {
        e.printStackTrace();
        usage("Could not interpret port number [" + portStr + "].");
    }
    if (configFile.endsWith(".xml")) {
        DOMConfigurator.configure(configFile);
    } else {
        PropertyConfigurator.configure(configFile);
    }
}
Example 46
Project: develtests-master  File: SimpleSocketServer.java View source code
static void init(String portStr, String configFile) {
    try {
        port = Integer.parseInt(portStr);
    } catch (java.lang.NumberFormatException e) {
        e.printStackTrace();
        usage("Could not interpret port number [" + portStr + "].");
    }
    if (configFile.endsWith(".xml")) {
        DOMConfigurator.configure(configFile);
    } else {
        PropertyConfigurator.configure(configFile);
    }
}
Example 47
Project: elastic-job-master  File: RestfulServerTest.java View source code
@Test
public void assertCallFailure() throws Exception {
    ContentExchange actual = sentRequest("{\"string\":\"test\",\"integer\":\"invalid_number\"}");
    Assert.assertThat(actual.getResponseStatus(), Is.is(500));
    Assert.assertThat(actual.getResponseContent(), StringStartsWith.startsWith("java.lang.NumberFormatException"));
    Mockito.verify(caller).call("test");
}
Example 48
Project: fasthat-master  File: Reader.java View source code
/**
     * Read a snapshot from a file.
     *
     * @param heapFile The name of a file containing a heap dump
     * @param callStack If true, read the call stack of allocaation sites
     */
public static Snapshot readFile(LoadProgress loadProgress, String heapFile, boolean callStack, int debugLevel) throws IOException {
    int dumpNumber = 1;
    int pos = heapFile.lastIndexOf('#');
    if (pos > -1) {
        String num = heapFile.substring(pos + 1, heapFile.length());
        try {
            dumpNumber = Integer.parseInt(num, 10);
        } catch (java.lang.NumberFormatException ex) {
            String msg = "In file name \"" + heapFile + "\", a dump number was " + "expected after the :, but \"" + num + "\" was found instead.";
            System.err.println(msg);
            throw new IOException(msg);
        }
        heapFile = heapFile.substring(0, pos);
    }
    try (PositionDataInputStream in = new PositionDataInputStream(new BufferedInputStream(new FileInputStream(heapFile)))) {
        loadProgress.startLoadingStream(heapFile, in);
        int i = in.readInt();
        if (i == HprofReader.MAGIC_NUMBER) {
            Reader r = new HprofReader(heapFile, in, dumpNumber, callStack, debugLevel);
            return r.read();
        } else {
            throw new IOException("Unrecognized magic number: " + i);
        }
    } finally {
        loadProgress.end();
    }
}
Example 49
Project: ikvm-openjdk-master  File: Reader.java View source code
/**
     * Read a snapshot from a file.
     *
     * @param heapFile The name of a file containing a heap dump
     * @param callStack If true, read the call stack of allocaation sites
     */
public static Snapshot readFile(String heapFile, boolean callStack, int debugLevel) throws IOException {
    int dumpNumber = 1;
    int pos = heapFile.lastIndexOf('#');
    if (pos > -1) {
        String num = heapFile.substring(pos + 1, heapFile.length());
        try {
            dumpNumber = Integer.parseInt(num, 10);
        } catch (java.lang.NumberFormatException ex) {
            String msg = "In file name \"" + heapFile + "\", a dump number was " + "expected after the :, but \"" + num + "\" was found instead.";
            System.err.println(msg);
            throw new IOException(msg);
        }
        heapFile = heapFile.substring(0, pos);
    }
    PositionDataInputStream in = new PositionDataInputStream(new BufferedInputStream(new FileInputStream(heapFile)));
    try {
        int i = in.readInt();
        if (i == HprofReader.MAGIC_NUMBER) {
            Reader r = new HprofReader(heapFile, in, dumpNumber, callStack, debugLevel);
            return r.read();
        } else {
            throw new IOException("Unrecognized magic number: " + i);
        }
    } finally {
        in.close();
    }
}
Example 50
Project: jdk7u-jdk-master  File: Reader.java View source code
/**
     * Read a snapshot from a file.
     *
     * @param heapFile The name of a file containing a heap dump
     * @param callStack If true, read the call stack of allocaation sites
     */
public static Snapshot readFile(String heapFile, boolean callStack, int debugLevel) throws IOException {
    int dumpNumber = 1;
    int pos = heapFile.lastIndexOf('#');
    if (pos > -1) {
        String num = heapFile.substring(pos + 1, heapFile.length());
        try {
            dumpNumber = Integer.parseInt(num, 10);
        } catch (java.lang.NumberFormatException ex) {
            String msg = "In file name \"" + heapFile + "\", a dump number was " + "expected after the :, but \"" + num + "\" was found instead.";
            System.err.println(msg);
            throw new IOException(msg);
        }
        heapFile = heapFile.substring(0, pos);
    }
    PositionDataInputStream in = new PositionDataInputStream(new BufferedInputStream(new FileInputStream(heapFile)));
    try {
        int i = in.readInt();
        if (i == HprofReader.MAGIC_NUMBER) {
            Reader r = new HprofReader(heapFile, in, dumpNumber, callStack, debugLevel);
            return r.read();
        } else {
            throw new IOException("Unrecognized magic number: " + i);
        }
    } finally {
        in.close();
    }
}
Example 51
Project: log4j-concurrent-master  File: SimpleSocketServer.java View source code
static void init(String portStr, String configFile) {
    try {
        port = Integer.parseInt(portStr);
    } catch (java.lang.NumberFormatException e) {
        e.printStackTrace();
        usage("Could not interpret port number [" + portStr + "].");
    }
    if (configFile.endsWith(".xml")) {
        DOMConfigurator.configure(configFile);
    } else {
        PropertyConfigurator.configure(configFile);
    }
}
Example 52
Project: log4j-master  File: SocketMin.java View source code
static void init(String host, String portStr) {
    Logger root = Logger.getRootLogger();
    BasicConfigurator.configure();
    try {
        int port = Integer.parseInt(portStr);
        logger.info("Creating socket appender (" + host + "," + port + ").");
        s = new SocketAppender(host, port);
        s.setName("S");
        root.addAppender(s);
    } catch (java.lang.NumberFormatException e) {
        e.printStackTrace();
        usage("Could not interpret port number [" + portStr + "].");
    } catch (Exception e) {
        System.err.println("Could not start!");
        e.printStackTrace();
        System.exit(1);
    }
}
Example 53
Project: logback-android-master  File: SocketMin.java View source code
static void init(String host, String portStr) {
    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    BasicConfigurator.configure(root.getLoggerContext());
    try {
        int port = Integer.parseInt(portStr);
        logger.info("Creating socket appender (" + host + "," + port + ").");
        s = new SocketAppender();
        s.setRemoteHost(host);
        s.setPort(port);
        s.setName("S");
        root.addAppender(s);
    } catch (java.lang.NumberFormatException e) {
        e.printStackTrace();
        usage("Could not interpret port number [" + portStr + "].");
    } catch (Exception e) {
        System.err.println("Could not start!");
        e.printStackTrace();
        System.exit(1);
    }
}
Example 54
Project: ManagedRuntimeInitiative-master  File: Reader.java View source code
/**
     * Read a snapshot from a file.
     *
     * @param heapFile The name of a file containing a heap dump
     * @param callStack If true, read the call stack of allocaation sites
     */
public static Snapshot readFile(String heapFile, boolean callStack, int debugLevel) throws IOException {
    int dumpNumber = 1;
    int pos = heapFile.lastIndexOf('#');
    if (pos > -1) {
        String num = heapFile.substring(pos + 1, heapFile.length());
        try {
            dumpNumber = Integer.parseInt(num, 10);
        } catch (java.lang.NumberFormatException ex) {
            String msg = "In file name \"" + heapFile + "\", a dump number was " + "expected after the :, but \"" + num + "\" was found instead.";
            System.err.println(msg);
            throw new IOException(msg);
        }
        heapFile = heapFile.substring(0, pos);
    }
    PositionDataInputStream in = new PositionDataInputStream(new BufferedInputStream(new FileInputStream(heapFile)));
    try {
        int i = in.readInt();
        if (i == HprofReader.MAGIC_NUMBER) {
            Reader r = new HprofReader(heapFile, in, dumpNumber, callStack, debugLevel);
            return r.read();
        } else {
            throw new IOException("Unrecognized magic number: " + i);
        }
    } finally {
        in.close();
    }
}
Example 55
Project: mut4j-master  File: SimpleSocketServer.java View source code
static void init(String portStr, String configFile) {
    try {
        port = Integer.parseInt(portStr);
    } catch (java.lang.NumberFormatException e) {
        e.printStackTrace();
        usage("Could not interpret port number [" + portStr + "].");
    }
    if (configFile.endsWith(".xml")) {
        DOMConfigurator.configure(configFile);
    } else {
        PropertyConfigurator.configure(configFile);
    }
}
Example 56
Project: openjdk-master  File: Reader.java View source code
/**
     * Read a snapshot from a file.
     *
     * @param heapFile The name of a file containing a heap dump
     * @param callStack If true, read the call stack of allocaation sites
     */
public static Snapshot readFile(String heapFile, boolean callStack, int debugLevel) throws IOException {
    int dumpNumber = 1;
    int pos = heapFile.lastIndexOf('#');
    if (pos > -1) {
        String num = heapFile.substring(pos + 1, heapFile.length());
        try {
            dumpNumber = Integer.parseInt(num, 10);
        } catch (java.lang.NumberFormatException ex) {
            String msg = "In file name \"" + heapFile + "\", a dump number was " + "expected after the :, but \"" + num + "\" was found instead.";
            System.err.println(msg);
            throw new IOException(msg);
        }
        heapFile = heapFile.substring(0, pos);
    }
    try (PositionDataInputStream in = new PositionDataInputStream(new BufferedInputStream(new FileInputStream(heapFile)))) {
        int i = in.readInt();
        if (i == HprofReader.MAGIC_NUMBER) {
            Reader r = new HprofReader(heapFile, in, dumpNumber, callStack, debugLevel);
            return r.read();
        } else {
            throw new IOException("Unrecognized magic number: " + i);
        }
    }
}
Example 57
Project: openjdk8-jdk-master  File: Reader.java View source code
/**
     * Read a snapshot from a file.
     *
     * @param heapFile The name of a file containing a heap dump
     * @param callStack If true, read the call stack of allocaation sites
     */
public static Snapshot readFile(String heapFile, boolean callStack, int debugLevel) throws IOException {
    int dumpNumber = 1;
    int pos = heapFile.lastIndexOf('#');
    if (pos > -1) {
        String num = heapFile.substring(pos + 1, heapFile.length());
        try {
            dumpNumber = Integer.parseInt(num, 10);
        } catch (java.lang.NumberFormatException ex) {
            String msg = "In file name \"" + heapFile + "\", a dump number was " + "expected after the :, but \"" + num + "\" was found instead.";
            System.err.println(msg);
            throw new IOException(msg);
        }
        heapFile = heapFile.substring(0, pos);
    }
    PositionDataInputStream in = new PositionDataInputStream(new BufferedInputStream(new FileInputStream(heapFile)));
    try {
        int i = in.readInt();
        if (i == HprofReader.MAGIC_NUMBER) {
            Reader r = new HprofReader(heapFile, in, dumpNumber, callStack, debugLevel);
            return r.read();
        } else {
            throw new IOException("Unrecognized magic number: " + i);
        }
    } finally {
        in.close();
    }
}
Example 58
Project: opentrader.github.com-master  File: SimpleSocketServer.java View source code
static void init(String portStr, String configFile) {
    try {
        port = Integer.parseInt(portStr);
    } catch (java.lang.NumberFormatException e) {
        e.printStackTrace();
        usage("Could not interpret port number [" + portStr + "].");
    }
    if (configFile.endsWith(".xml")) {
        DOMConfigurator.configure(configFile);
    } else {
        PropertyConfigurator.configure(configFile);
    }
}
Example 59
Project: Peid-Utilities-master  File: SimpleSocketServer.java View source code
static void init(String portStr, String configFile) {
    try {
        port = Integer.parseInt(portStr);
    } catch (java.lang.NumberFormatException e) {
        e.printStackTrace();
        usage("Could not interpret port number [" + portStr + "].");
    }
    if (configFile.endsWith(".xml")) {
        DOMConfigurator.configure(configFile);
    } else {
        PropertyConfigurator.configure(configFile);
    }
}
Example 60
Project: perftrace-master  File: SimpleSocketServer.java View source code
static void init(String portStr, String configFile) {
    try {
        port = Integer.parseInt(portStr);
    } catch (java.lang.NumberFormatException e) {
        e.printStackTrace();
        usage("Could not interpret port number [" + portStr + "].");
    }
    if (configFile.endsWith(".xml")) {
        DOMConfigurator.configure(configFile);
    } else {
        PropertyConfigurator.configure(configFile);
    }
}
Example 61
Project: sandbox-master  File: HeightmapFileReader.java View source code
public static float[][] readValues(java.io.InputStream in, String delimiter) throws java.io.IOException, java.lang.NumberFormatException {
    String thisLine;
    java.io.BufferedInputStream s = new java.io.BufferedInputStream(in);
    java.io.BufferedReader myInput = new java.io.BufferedReader(new java.io.InputStreamReader(s, Charsets.UTF_8));
    int index = 0;
    float min = 0;
    float max = 0;
    float[][] theMap = new float[512][512];
    while ((thisLine = myInput.readLine()) != null) {
        // scan it line by line
        java.util.StringTokenizer st = new java.util.StringTokenizer(thisLine, delimiter);
        float a = Float.valueOf(st.nextToken());
        theMap[index / 512][index % 512] = a;
        index++;
        min = a < min ? a : min;
        max = a > max ? a : max;
        if (index / 512 > 511) {
            break;
        }
    }
    //        System.out.println("max " + max);
    return (theMap);
}
Example 62
Project: Terasology-master  File: HeightmapFileReader.java View source code
public static float[][] readValues(java.io.InputStream in, String delimiter) throws java.io.IOException, java.lang.NumberFormatException {
    String thisLine;
    java.io.BufferedInputStream s = new java.io.BufferedInputStream(in);
    java.io.BufferedReader myInput = new java.io.BufferedReader(new java.io.InputStreamReader(s, Charsets.UTF_8));
    int index = 0;
    float min = 0;
    float max = 0;
    float[][] theMap = new float[512][512];
    while ((thisLine = myInput.readLine()) != null) {
        // scan it line by line
        java.util.StringTokenizer st = new java.util.StringTokenizer(thisLine, delimiter);
        float a = Float.valueOf(st.nextToken());
        theMap[index / 512][index % 512] = a;
        index++;
        min = a < min ? a : min;
        max = a > max ? a : max;
        if (index / 512 > 511) {
            break;
        }
    }
    //        System.out.println("max " + max);
    return (theMap);
}
Example 63
Project: WLPass-master  File: SimpleSocketServer.java View source code
static void init(String portStr, String configFile) {
    try {
        port = Integer.parseInt(portStr);
    } catch (java.lang.NumberFormatException e) {
        e.printStackTrace();
        usage("Could not interpret port number [" + portStr + "].");
    }
    if (configFile.endsWith(".xml")) {
        DOMConfigurator.configure(configFile);
    } else {
        PropertyConfigurator.configure(configFile);
    }
}
Example 64
Project: wpi-suite-master  File: UserDeserializer.java View source code
@Override
public User deserialize(JsonElement userElement, Type userType, JsonDeserializationContext context) throws JsonParseException {
    JsonObject deflated = userElement.getAsJsonObject();
    if (!deflated.has("username")) {
        throw new JsonParseException("The serialized User did not contain the required username field.");
    }
    // for all other attributes: instantiate as null, fill in if given.
    int idNum = 0;
    String username = deflated.get("username").getAsString();
    String name = null;
    String password = null;
    if (deflated.has("idNum") && !deflated.get("idNum").getAsString().equals("")) {
        try {
            idNum = deflated.get("idNum").getAsInt();
        } catch (java.lang.NumberFormatException e) {
            logger.log(Level.FINER, "User transmitted with String in iDnum field");
        }
    }
    if (deflated.has("password") && !deflated.get("password").getAsString().equals("")) {
        password = deflated.get("password").getAsString();
    }
    if (deflated.has("name") && !deflated.get("name").getAsString().equals("")) {
        name = deflated.get("name").getAsString();
    }
    User inflated = new User(name, username, password, idNum);
    if (deflated.has("role") && !deflated.get("role").getAsString().equals("")) {
        Role r = Role.valueOf(deflated.get("role").getAsString());
        inflated.setRole(r);
    }
    return inflated;
}
Example 65
Project: wpi-suite-tng-master  File: UserDeserializer.java View source code
@Override
public User deserialize(JsonElement userElement, Type userType, JsonDeserializationContext context) throws JsonParseException {
    JsonObject deflated = userElement.getAsJsonObject();
    if (!deflated.has("username")) {
        throw new JsonParseException("The serialized User did not contain the required username field.");
    }
    // for all other attributes: instantiate as null, fill in if given.
    int idNum = 0;
    String username = deflated.get("username").getAsString();
    String name = null;
    String password = null;
    if (deflated.has("idNum") && !deflated.get("idNum").getAsString().equals("")) {
        try {
            idNum = deflated.get("idNum").getAsInt();
        } catch (java.lang.NumberFormatException e) {
            logger.log(Level.FINER, "User transmitted with String in iDnum field");
        }
    }
    if (deflated.has("password") && !deflated.get("password").getAsString().equals("")) {
        password = deflated.get("password").getAsString();
    }
    if (deflated.has("name") && !deflated.get("name").getAsString().equals("")) {
        name = deflated.get("name").getAsString();
    }
    User inflated = new User(name, username, password, idNum);
    if (deflated.has("role") && !deflated.get("role").getAsString().equals("")) {
        Role r = Role.valueOf(deflated.get("role").getAsString());
        inflated.setRole(r);
    }
    return inflated;
}
Example 66
Project: zk-master  File: B0004.java View source code
public void validate(ValidationContext ctx) {
    if (!ctx.isValid())
        return;
    Property p = ctx.getProperty();
    Object val = p.getValue();
    try {
        if (val != null && Integer.parseInt(val.toString()) > 20) {
            setLastMessage2(null);
        } else {
            ctx.setInvalid();
            setLastMessage2("value 2 have to large than 20");
        }
    } catch (java.lang.NumberFormatException x) {
        ctx.setInvalid();
        setLastMessage2("value 2 is not valid " + x.getMessage());
    }
    ctx.getBindContext().getBinder().notifyChange(B0004.this, "lastMessage2");
}
Example 67
Project: beboj-master  File: User.java View source code
public static void loadRelicensingInformation(boolean clean) {
//        relicensingUsers = new HashSet<Long>();
//        nonRelicensingUsers = new HashSet<Long>();
//        try {
//            MirroredInputStream stream = new MirroredInputStream(
//                 Main.pref.get("url.licensechange",
//                    "http://planet.openstreetmap.org/users_agreed/users_agreed.txt"),
//                 clean ? 1 : 7200);
//            try {
//                InputStreamReader r;
//                r = new InputStreamReader(stream);
//                BufferedReader reader = new BufferedReader(r);
//                String line;
//                while ((line = reader.readLine()) != null) {
//                    if (line.startsWith("#")) continue;
//                    try {
//                        Long id = new Long(Long.parseLong(line.trim()));
//                        relicensingUsers.add(id);
//                    } catch (java.lang.NumberFormatException ex) {
//                    }
//                }
//            }
//            finally {
//                stream.close();
//            }
//        } catch (IOException ex) {
//        }
//
//        try {
//            MirroredInputStream stream = new MirroredInputStream(
//                Main.pref.get("url.licensechange_reject",
//                    "http://planet.openstreetmap.org/users_agreed/users_disagreed.txt"),
//                clean ? 1 : 7200);
//            try {
//                InputStreamReader r;
//                r = new InputStreamReader(stream);
//                BufferedReader reader = new BufferedReader(r);
//                String line;
//                while ((line = reader.readLine()) != null) {
//                    if (line.startsWith("#")) continue;
//                    try {
//                        Long id = new Long(Long.parseLong(line.trim()));
//                        nonRelicensingUsers.add(id);
//                    } catch (java.lang.NumberFormatException ex) {
//                    }
//                }
//            }
//            finally {
//                stream.close();
//            }
//        } catch (IOException ex) {
//        }
}
Example 68
Project: jetty.project-master  File: ErrorPageTest.java View source code
@Test
public void testGlobalErrorException() throws Exception {
    try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class)) {
        String response = _connector.getResponse("GET /fail/global?code=NAN HTTP/1.0\r\n\r\n");
        assertThat(response, Matchers.containsString("HTTP/1.1 500 Server Error"));
        assertThat(response, Matchers.containsString("ERROR_PAGE: /GlobalErrorPage"));
        assertThat(response, Matchers.containsString("ERROR_CODE: 500"));
        assertThat(response, Matchers.containsString("ERROR_EXCEPTION: java.lang.NumberFormatException: For input string: \"NAN\""));
        assertThat(response, Matchers.containsString("ERROR_EXCEPTION_TYPE: class java.lang.NumberFormatException"));
        assertThat(response, Matchers.containsString("ERROR_SERVLET: org.eclipse.jetty.servlet.ErrorPageTest$FailServlet-"));
        assertThat(response, Matchers.containsString("ERROR_REQUEST_URI: /fail/global"));
    }
}
Example 69
Project: MavenOneCMDB-master  File: AppletLaunch.java View source code
public static double getVerNum(String version) {
    double retval = 0;
    double mask = 1;
    double maskVal = 0.01;
    int dotPos = version.indexOf(".");
    while (dotPos > -1) {
        String dotPart = version.substring(0, dotPos);
        version = version.substring(dotPos + 1);
        try {
            retval += (mask * (Double.valueOf(dotPart)).doubleValue());
        } catch (java.lang.NumberFormatException e) {
        }
        dotPos = version.indexOf(".");
        mask = mask * maskVal;
    }
    try {
        retval += (mask * (Double.valueOf(version)).doubleValue());
    } catch (java.lang.NumberFormatException e) {
    }
    return retval;
}
Example 70
Project: QuakeInjector-master  File: PackageDatabaseParser.java View source code
/**
	 * Parse a single Package/file entry
	 */
private Package parsePackage(Element file, Map<Package, List<String>> reqResolve) {
    String id = file.getAttribute("id");
    Rating rating;
    {
        String ratingString = file.getAttribute("rating");
        int ratingNumber = 0;
        if (!ratingString.equals("")) {
            try {
                ratingNumber = Integer.parseInt(ratingString);
                if (ratingNumber < 0 || ratingNumber > 5) {
                    System.out.println("Rating of " + id + " is broken");
                    ratingNumber = 0;
                }
            } catch (java.lang.NumberFormatException e) {
                System.out.println("Rating of " + id + " is broken");
            }
        }
        rating = ratingTable[ratingNumber];
    }
    String title = XmlUtils.getFirstElement(file, "title").getTextContent().trim();
    String author = XmlUtils.getFirstElement(file, "author").getTextContent().trim();
    int size;
    try {
        size = Integer.parseInt(XmlUtils.getFirstElement(file, "size").getTextContent().trim());
    } catch (java.lang.NumberFormatException e) {
        System.out.println("XML Parsing Error: malformed <size> tag on record \"" + id + "\"");
        size = 0;
    }
    String date = XmlUtils.getFirstElement(file, "date").getTextContent().trim();
    String description = XmlUtils.getTextForNode(XmlUtils.getFirstElement(file, "description")).trim();
    String relativeBaseDir = null;
    String cmdline = null;
    ArrayList<String> startmaps = new ArrayList<String>();
    ArrayList<String> requirements = new ArrayList<String>();
    // parse techinfo stuff
    Element techinfo = XmlUtils.getFirstElement(file, "techinfo");
    if (techinfo != null) {
        for (Node node : XmlUtils.iterate(techinfo.getChildNodes())) {
            if (!XmlUtils.isElement(node)) {
                continue;
            }
            Element info = (Element) node;
            if (info.getTagName().equals("zipbasedir")) {
                relativeBaseDir = info.getTextContent();
            } else if (info.getTagName().equals("commandline")) {
                cmdline = info.getTextContent();
            } else if (info.getTagName().equals("startmap")) {
                startmaps.add(info.getTextContent());
            } else if (info.getTagName().equals("requirements")) {
                for (Node reqFile : XmlUtils.iterate(info.getChildNodes())) {
                    if (XmlUtils.isElement(reqFile)) {
                        String r = ((Element) reqFile).getAttribute("id");
                        requirements.add(r);
                    }
                }
            }
        }
    }
    //if there's no startmap tag, use the id
    if (startmaps.isEmpty()) {
        startmaps.add(id);
    }
    Package result = new Package(id, author, title, size, PackageDatabaseParser.parseDate(date), false, rating, description, relativeBaseDir, cmdline, startmaps, null);
    reqResolve.put(result, requirements);
    return result;
}
Example 71
Project: openjump-core-rels-master  File: Dbf.java View source code
/**
     * Parses the record stored in the StringBuffer rec into a vector of
     * objects
     * @param rec the record to be parsed.
     */
public Vector ParseRecord(StringBuffer rec) {
    Vector record = new Vector(numfields);
    String t;
    Integer I = new Integer(0);
    Float F = new Float(0.0);
    t = rec.toString();
    for (int i = 0; i < numfields; i++) {
        if (DEBUG)
            System.out.println(DBC + "type " + fielddef[i].fieldtype);
        if (DEBUG)
            System.out.println(DBC + "start " + fielddef[i].fieldstart);
        if (DEBUG)
            System.out.println(DBC + "len " + fielddef[i].fieldlen);
        if (DEBUG)
            System.out.println(DBC + "" + t.substring(fielddef[i].fieldstart, fielddef[i].fieldstart + fielddef[i].fieldlen));
        switch(fielddef[i].fieldtype) {
            case 'C':
                record.addElement(t.substring(fielddef[i].fieldstart, fielddef[i].fieldstart + fielddef[i].fieldlen));
                break;
            case 'N':
            case 'F':
                if (fielddef[i].fieldnumdec == 0)
                    try {
                        record.addElement(I.decode(t.substring(fielddef[i].fieldstart, fielddef[i].fieldstart + fielddef[i].fieldlen)));
                    } catch (java.lang.NumberFormatException e) {
                        record.addElement(new Integer(0));
                    }
                else
                    try {
                        record.addElement(F.valueOf(t.substring(fielddef[i].fieldstart, fielddef[i].fieldstart + fielddef[i].fieldlen)));
                    } catch (java.lang.NumberFormatException e) {
                        record.addElement(new Float(0.0));
                    }
                break;
            default:
                if (DEBUG)
                    System.out.println(DBC + "Oh - don't know how to parse " + fielddef[i].fieldtype);
        }
    }
    return record;
}
Example 72
Project: Fido-master  File: DialogAttachImage.java View source code
/** Calculate the relations between size and resolution of the image.
        @param useSize if true, calculate resolution from size.
            if false, calculate size from resolution.
    */
private void calculateSizeAndResolution(int useSize) {
    if (isCalculating || img == null)
        return;
    isCalculating = true;
    // Conversion between inches and mm.
    final double oneinch = 25.4;
    switch(useSize) {
        case USE_RESOLUTION:
            try {
                double res = getResolution();
                double w = img.getWidth() / res * oneinch;
                double h = img.getHeight() / res * oneinch;
                xsize.setText(Globals.roundTo(w, 3));
                ysize.setText(Globals.roundTo(h, 3));
            } catch (java.lang.NumberFormatException E) {
                isCalculating = false;
                return;
            }
            break;
        case USE_SIZE_X:
            try {
                double sizex = getSizeX();
                double res = img.getWidth() / sizex * oneinch;
                setResolution(res);
                double h = img.getHeight() / res * oneinch;
                ysize.setText(Globals.roundTo(h, 3));
            } catch (java.lang.NumberFormatException E) {
                isCalculating = false;
                return;
            }
            break;
        case USE_SIZE_Y:
            try {
                double sizey = getSizeY();
                double res = img.getHeight() / sizey * oneinch;
                setResolution(res);
                double w = img.getWidth() / res * oneinch;
                xsize.setText(Globals.roundTo(w, 3));
            } catch (java.lang.NumberFormatException E) {
                isCalculating = false;
                return;
            }
            break;
    }
    isCalculating = false;
}
Example 73
Project: FidoCadJ-master  File: DialogAttachImage.java View source code
/** Calculate the relations between size and resolution of the image.
        @param useSize if true, calculate resolution from size.
            if false, calculate size from resolution.
    */
private void calculateSizeAndResolution(int useSize) {
    if (isCalculating || img == null)
        return;
    isCalculating = true;
    // Conversion between inches and mm.
    final double oneinch = 25.4;
    switch(useSize) {
        case USE_RESOLUTION:
            try {
                double res = getResolution();
                double w = img.getWidth() / res * oneinch;
                double h = img.getHeight() / res * oneinch;
                xsize.setText(Globals.roundTo(w, 3));
                ysize.setText(Globals.roundTo(h, 3));
            } catch (java.lang.NumberFormatException E) {
                isCalculating = false;
                return;
            }
            break;
        case USE_SIZE_X:
            try {
                double sizex = getSizeX();
                double res = img.getWidth() / sizex * oneinch;
                setResolution(res);
                double h = img.getHeight() / res * oneinch;
                ysize.setText(Globals.roundTo(h, 3));
            } catch (java.lang.NumberFormatException E) {
                isCalculating = false;
                return;
            }
            break;
        case USE_SIZE_Y:
            try {
                double sizey = getSizeY();
                double res = img.getHeight() / sizey * oneinch;
                setResolution(res);
                double w = img.getWidth() / res * oneinch;
                xsize.setText(Globals.roundTo(w, 3));
            } catch (java.lang.NumberFormatException E) {
                isCalculating = false;
                return;
            }
            break;
    }
    isCalculating = false;
}
Example 74
Project: cambodia-master  File: ParaFromFile.java View source code
public int GetPara(String processName) {
    ConfigFile cf = new ConfigFile(fileName);
    String srcTable = cf.getValue("SRC_TABLE");
    if (srcTable == null || "".equals(srcTable.trim())) {
        LoggerHelper.error(this.getClass(), "SRC_TABLE that define in " + fileName + " is error!");
        return -1;
    }
    schePara.setSrcTable(srcTable.trim());
    String srcTableBak = cf.getValue("SRC_TABLE_BAK");
    if (srcTableBak == null || "".equals(srcTableBak.trim())) {
        LoggerHelper.error(this.getClass(), "SRC_TABLE_BAK that define in " + fileName + " is error!");
        return -1;
    }
    schePara.setSrcTableBak(srcTableBak.trim());
    String dstTable = cf.getValue("DST_TABLE");
    if (dstTable == null || "".equals(dstTable.trim())) {
        LoggerHelper.error(this.getClass(), "DST_TABLE that define in " + fileName + " is error!");
        return -1;
    }
    schePara.setDstTable(dstTable.trim());
    String dstTableBak = cf.getValue("DST_TABLE_BAK");
    if (dstTableBak == null || "".equals(dstTableBak.trim())) {
        LoggerHelper.error(this.getClass(), "DST_TABLE_BAK that define in " + fileName + " is error!");
        return -1;
    }
    schePara.setDstTableBak(dstTableBak.trim());
    String seqDstTransnum = cf.getValue("SEQ_DST_TRANSNUM");
    if (seqDstTransnum == null || "".equals(seqDstTransnum.trim())) {
        LoggerHelper.error(this.getClass(), "SEQ_DST_TRANSNUM that define in " + fileName + " is error !");
        return -1;
    }
    schePara.setSeqDstTransnum(seqDstTransnum.trim());
    //Ö¸¶¨ÓÅÏȼ¶²»ÆôÓÃÖ¸ÁîÓÅ»¯
    String order_notsupport = cf.getValue("ORDER_NOTSUPPORT");
    if (order_notsupport != null && !"".equals(order_notsupport.trim())) {
        schePara.setOrder_notsupport(Integer.parseInt(order_notsupport.trim()));
    }
    //»Øд´¦ÀíËÙ¶È
    String writebak = cf.getValue("WRITEBAK_SPEED");
    if (writebak != null && !"".equals(writebak.trim())) {
        int speed = Integer.parseInt(writebak.trim());
        if (speed >= 0)
            CaConstants.movecaouttohis_speed = speed;
    }
    //³ÌÐò¿ÕÏеȴý»òÕßCAÓµ¶ÂµÈ´ý
    String free = cf.getValue("FREE_TIME");
    if (free != null && !"".equals(free.trim())) {
        int speed = Integer.parseInt(free.trim());
        if (speed > 0)
            CaConstants.free_sleep_time = speed;
    }
    String sCount = cf.getValue("ORDER_COUNT");
    int iCount = 0;
    try {
        iCount = Integer.parseInt(sCount);
    } catch (java.lang.NumberFormatException e) {
        e.printStackTrace();
        iCount = 0;
    }
    if (iCount <= 0) {
        LoggerHelper.error(this.getClass(), "ORDER_COUNT that define in " + fileName + " is error!");
        return -1;
    }
    schePara.setOrderCount(iCount);
    for (int i = 1; i <= iCount; i++) {
        String orderN = cf.getValue("ORDER" + i);
        if (orderN == null || "".equals(orderN.trim())) {
            LoggerHelper.error(this.getClass(), "ORDER" + i + "that defined in " + fileName + " is error!");
            return -1;
        }
        schePara.getMapOrder().put("ORDER" + i, orderN.trim());
    }
    // name, castype,  casSQL, pools, addmode, cancelmode
    for (int i = 1; ; i++) {
        String ca = cf.getValue("CA" + i);
        if (ca == null || "".equals(ca.trim())) {
            break;
        }
        String[] cas = ca.split(",");
        if (cas.length != 6) {
            LoggerHelper.error(this.getClass(), "CA" + i + "that defined in " + fileName + " is error!");
            return -1;
        }
        CASPrivatePara caspp = new CASPrivatePara();
        caspp.setName(cas[0].trim());
        caspp.setCasType(cas[1].trim());
        caspp.setCasSQL(cas[2].trim());
        caspp.setPool(Integer.parseInt(cas[3].trim()));
        caspp.setAddMode(cas[4].trim());
        caspp.setCancelMode(cas[5].trim());
        schePara.getMapCAS().put(cas[0].trim(), caspp);
    }
    String OSD_CONTENT_CHENK = cf.getValue("OSD_CONTENT_CHENK");
    if (OSD_CONTENT_CHENK != null && !"".equals(OSD_CONTENT_CHENK.trim())) {
        schePara.setOsd_content_check(Boolean.parseBoolean(OSD_CONTENT_CHENK.trim()));
    }
    String OSD_BASE_REFRESH_TIME = cf.getValue("OSD_BASE_REFRESH_TIME");
    if (OSD_BASE_REFRESH_TIME != null && !"".equals(OSD_BASE_REFRESH_TIME.trim())) {
        int refresh_time = Integer.parseInt(OSD_BASE_REFRESH_TIME.trim());
        if (refresh_time > 0) {
            schePara.setOsd_base_refresh_time(refresh_time);
        }
    }
    return 1;
}
Example 75
Project: com.idega.builder-master  File: IBSavePageWindow.java View source code
public void main(IWContext iwc) throws Exception {
    IWResourceBundle iwrb = getBundle(iwc).getResourceBundle(iwc);
    Form form = new Form();
    setTitle(iwrb.getLocalizedString("create_new_page", "Create a new page"));
    add(form);
    Table tab = new Table(2, 5);
    form.add(tab);
    TextInput inputName = new TextInput(PAGE_NAME_PARAMETER);
    tab.add(iwrb.getLocalizedString("page_name", "Page name"), 1, 1);
    tab.add(inputName, 2, 1);
    DropdownMenu mnu = new DropdownMenu(PAGE_TYPE);
    mnu.addMenuElement("1", "Page");
    mnu.addMenuElement("2", "Template");
    tab.add(new Text("Select page type : "), 1, 2);
    tab.add(mnu, 2, 2);
    mnu.setToSubmit();
    String type = iwc.getParameter(PAGE_TYPE);
    tab.add(iwrb.getLocalizedString("parent_page", "Create page under:"), 1, 3);
    if (type != null) {
        if (type.equals("2")) {
            tab.add(getTemplateChooser(PAGE_CHOOSER_NAME), 2, 3);
        } else {
            tab.add(getPageChooser(PAGE_CHOOSER_NAME), 2, 3);
        }
    } else {
        tab.add(getPageChooser(PAGE_CHOOSER_NAME), 2, 3);
    }
    tab.add(iwrb.getLocalizedString("using_template", "Using template:"), 1, 4);
    tab.add(getTemplateChooser(TEMPLATE_CHOOSER_NAME), 2, 4);
    SubmitButton button = new SubmitButton("subbi", iwrb.getLocalizedString("save", "Save"));
    tab.add(button, 2, 5);
    String submit = iwc.getParameter("subbi");
    if (submit != null) {
        String pageId = iwc.getParameter(PAGE_CHOOSER_NAME);
        String name = iwc.getParameter(PAGE_NAME_PARAMETER);
        type = iwc.getParameter(PAGE_TYPE);
        String templateId = iwc.getParameter(TEMPLATE_CHOOSER_NAME);
        if (pageId != null) {
            ICPage ibPage = ((com.idega.core.builder.data.ICPageHome) com.idega.data.IDOLookup.getHomeLegacy(ICPage.class)).createLegacy();
            if (name == null) {
                name = "Untitled";
            }
            ibPage.setName(name);
            ICFile file = ((com.idega.core.file.data.ICFileHome) com.idega.data.IDOLookup.getHome(ICFile.class)).create();
            ibPage.setFile(file);
            if (type.equals("1")) {
                ibPage.setType(ICPageBMPBean.PAGE);
            } else if (type.equals("2")) {
                ibPage.setType(ICPageBMPBean.TEMPLATE);
            } else {
                ibPage.setType(ICPageBMPBean.PAGE);
            }
            int tid = -1;
            try {
                tid = Integer.parseInt(templateId);
                ibPage.setTemplateId(tid);
            } catch (java.lang.NumberFormatException e) {
            }
            ibPage.store();
            ICPage ibPageParent = ((com.idega.core.builder.data.ICPageHome) com.idega.data.IDOLookup.getHomeLegacy(ICPage.class)).findByPrimaryKeyLegacy(Integer.parseInt(pageId));
            ibPageParent.addChild(ibPage);
            BuilderLogic.getInstance().setCurrentIBPage(iwc, ibPage.getPrimaryKey().toString());
            setParentToReload();
            close();
        }
    } else {
        String name = iwc.getParameter(PAGE_NAME_PARAMETER);
        type = iwc.getParameter(PAGE_TYPE);
        if (name != null) {
            inputName.setValue(name);
        }
        if (type != null) {
            mnu.setSelectedElement(type);
        }
        /*      System.out.println("id = " + templateId);

      System.out.println("name = " + templateName);*/
        java.util.Enumeration e = iwc.getParameterNames();
        while (e.hasMoreElements()) {
            String param = (String) e.nextElement();
            String value = iwc.getParameter(param);
            System.out.println(param + " = " + value);
        }
    }
}
Example 76
Project: fenixedu-ist-teacher-service-master  File: ManageDegreeTeachingServicesDispatchAction.java View source code
public ActionForward showTeachingServiceDetails(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, FenixServiceException {
    Professorship professorship = getDomainObject(request, "professorshipID");
    if (professorship == null || professorship.getTeacher() == null || !canManageTeacherCredits(professorship)) {
        return mapping.findForward("teacher-not-found");
    }
    DegreeTeachingServiceBean degreeTeachingServiceBean = new DegreeTeachingServiceBean(professorship);
    request.setAttribute("degreeTeachingServiceBean", degreeTeachingServiceBean);
    return mapping.findForward("show-teaching-service-percentages");
}
Example 77
Project: Grindstone-master  File: VODConfiguration.java View source code
private void setUpExceptionMappings() {
    mapType("java.lang.Throwable", "System.Exception");
    mapProperty("java.lang.Throwable.getMessage", "Message");
    mapProperty("java.lang.Throwable.getCause", "InnerException");
    mapType("java.lang.Error", "System.Exception");
    mapType("java.lang.OutOfMemoryError", "System.OutOfMemoryException");
    mapType("java.lang.Exception", "System.Exception");
    mapType("java.lang.RuntimeException", "System.Exception");
    mapType("java.lang.ClassCastException", "System.InvalidCastException");
    mapType("java.lang.NullPointerException", "System.ArgumentNullException");
    mapType("java.lang.IllegalArgumentException", "System.ArgumentException");
    mapType("java.lang.IllegalStateException", "System.InvalidOperationException");
    //mapType("java.lang.InterruptedException", "System.Exception");
    mapType("java.lang.IndexOutOfBoundsException", "System.IndexOutOfRangeException");
    mapType("java.lang.UnsupportedOperationException", "System.NotSupportedException");
    mapType("java.lang.ArrayIndexOutOfBoundsException", "System.IndexOutOfRangeException");
    mapType("java.lang.NoSuchMethodError", "System.MissingMethodException");
    mapType("java.io.IOException", "System.IO.IOException");
    mapType("java.net.SocketException", "System.Net.Sockets.SocketException");
    mapType("java.lang.SecurityException", "System.Security.SecurityException");
    //in .NET: ArgumentNullException, FormatException, or OverflowException: common base class is System.SystemException
    mapType("java.lang.NumberFormatException", "System.SystemException");
    mapType("java.lang.NoSuchFieldException", "System.MissingFieldException");
    mapType("java.rmi.NoSuchObjectException", "System.InvalidOperationException");
    mapType("java.util.NoSuchElementException", "System.InvalidOperationException");
    mapType("java.lang.NoSuchMethodException", "System.MissingMethodException");
    mapType("java.lang.reflect.InvocationTargetException", "System.Reflection.TargetInvocationException");
    mapType("java.lang.IllegalAccessException", "System.MethodAccessException");
    mapType("java.io.FileNotFoundException", "System.IO.FileNotFoundException");
    mapType("java.io.StreamCorruptedException", "System.IO.IOException");
    mapType("java.io.UTFDataFormatException", "System.IO.IOException");
    mapType("java.io.InvalidObjectException", "System.Runtime.Serialization.InvalidDataContractException");
    mapType("java.util.ConcurrentModificationException", "System.InvalidOperationException");
    //I've tried interfaces and abstract classes with System.Activator.CreateInstance,
    //and both attempts yield 'MissingMethodException' and not 'MemberAccessException'
    mapType("java.lang.InstantiationException", "System.MissingMethodException");
}
Example 78
Project: java-docs-samples-master  File: BookstoreServer.java View source code
public static void main(String[] args) throws Exception {
    Options options = createOptions();
    CommandLineParser parser = new DefaultParser();
    CommandLine line;
    try {
        line = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Invalid command line: " + e.getMessage());
        printUsage(options);
        return;
    }
    int port = DEFAULT_PORT;
    if (line.hasOption("port")) {
        String portOption = line.getOptionValue("port");
        try {
            port = Integer.parseInt(portOption);
        } catch (java.lang.NumberFormatException e) {
            System.err.println("Invalid port number: " + portOption);
            printUsage(options);
            return;
        }
    }
    final BookstoreData data = initializeBookstoreData();
    final BookstoreServer server = new BookstoreServer();
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            try {
                System.out.println("Shutting down");
                server.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    server.start(port, data);
    System.out.format("Bookstore service listening on %d\n", port);
    server.blockUntilShutdown();
}
Example 79
Project: java2haxe-master  File: VODConfiguration.java View source code
private void setUpExceptionMappings() {
    mapType("java.lang.Throwable", "System.Exception");
    mapProperty("java.lang.Throwable.getMessage", "Message");
    mapProperty("java.lang.Throwable.getCause", "InnerException");
    mapType("java.lang.Error", "System.Exception");
    mapType("java.lang.OutOfMemoryError", "System.OutOfMemoryException");
    mapType("java.lang.Exception", "System.Exception");
    mapType("java.lang.RuntimeException", "System.Exception");
    mapType("java.lang.ClassCastException", "System.InvalidCastException");
    mapType("java.lang.NullPointerException", "System.ArgumentNullException");
    mapType("java.lang.IllegalArgumentException", "System.ArgumentException");
    mapType("java.lang.IllegalStateException", "System.InvalidOperationException");
    //mapType("java.lang.InterruptedException", "System.Exception");
    mapType("java.lang.IndexOutOfBoundsException", "System.IndexOutOfRangeException");
    mapType("java.lang.UnsupportedOperationException", "System.NotSupportedException");
    mapType("java.lang.ArrayIndexOutOfBoundsException", "System.IndexOutOfRangeException");
    mapType("java.lang.NoSuchMethodError", "System.MissingMethodException");
    mapType("java.io.IOException", "System.IO.IOException");
    mapType("java.net.SocketException", "System.Net.Sockets.SocketException");
    mapType("java.lang.SecurityException", "System.Security.SecurityException");
    //in .NET: ArgumentNullException, FormatException, or OverflowException: common base class is System.SystemException
    mapType("java.lang.NumberFormatException", "System.SystemException");
    mapType("java.lang.NoSuchFieldException", "System.MissingFieldException");
    mapType("java.rmi.NoSuchObjectException", "System.InvalidOperationException");
    mapType("java.util.NoSuchElementException", "System.InvalidOperationException");
    mapType("java.lang.NoSuchMethodException", "System.MissingMethodException");
    mapType("java.lang.reflect.InvocationTargetException", "System.Reflection.TargetInvocationException");
    mapType("java.lang.IllegalAccessException", "System.MethodAccessException");
    mapType("java.io.FileNotFoundException", "System.IO.FileNotFoundException");
    mapType("java.io.StreamCorruptedException", "System.IO.IOException");
    mapType("java.io.UTFDataFormatException", "System.IO.IOException");
    mapType("java.io.InvalidObjectException", "System.Runtime.Serialization.InvalidDataContractException");
    mapType("java.util.ConcurrentModificationException", "System.InvalidOperationException");
    //I've tried interfaces and abstract classes with System.Activator.CreateInstance,
    //and both attempts yield 'MissingMethodException' and not 'MemberAccessException'
    mapType("java.lang.InstantiationException", "System.MissingMethodException");
}
Example 80
Project: junit5-master  File: AssertionsAssertThrowsTests.java View source code
@Test
void assertThrowsWithExecutableThatThrowsAnUnexpectedException() {
    try {
        assertThrows(IllegalStateException.class, () -> {
            throw new NumberFormatException();
        });
        expectAssertionFailedError();
    } catch (AssertionFailedError ex) {
        assertMessageContains(ex, "Unexpected exception type thrown");
        assertMessageContains(ex, "expected: <java.lang.IllegalStateException>");
        assertMessageContains(ex, "but was: <java.lang.NumberFormatException>");
    }
}
Example 81
Project: netphony-topology-master  File: TMManagementSession.java View source code
public void run() {
    log.info("Starting Management session for TM");
    boolean running = true;
    try {
        out = new PrintStream(socket.getOutputStream());
    } catch (IOException e) {
        log.warning("Management session cancelled: " + e.getMessage());
        return;
    }
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        while (running) {
            if (!started) {
                out.print("\n");
                out.print("   T               ,\r\n");
                out.print("   O               |'.             ,\r\n");
                out.print("   P              |  '-._        / )\r\n");
                out.print("   O             .'  .._  ',     /_'-,\r\n");
                out.print("                '   /  _'.'_\\   /._)')\r\n");
                out.print("   M           :   /  '_' '_'  /  _.'\r\n");
                out.print("   O           |E |   |Q| |Q| /   /\r\n");
                out.print("   D          .'  _\\  '-' '-'    /\r\n");
                out.print("   U        .'--.(S     ,__` )  /\r\n");
                out.print("   L              '-.     _.'  /\r\n");
                out.print("   E            __.--'----(   /\r\n");
                out.print("            _.-'     :   __\\ /\r\n");
                out.print("           (      __.' :'  :Y\r\n");
                out.print("            '.   '._,  :   :|\r\n");
                out.print("              '.     ) :.__:|\r\n");
                out.print("                \\    \\______/\r\n");
                out.print("                 '._L/_H____]\r\n");
                out.print("                  /_        /\r\n");
                out.print("                 /  '-.__.-')\r\n");
                out.print("                :      /   /\r\n");
                out.print("                :     /   /\r\n");
                out.print("              ,/_____/----;\r\n");
                out.print("              '._____)----'\r\n");
                out.print("              /     /   /\r\n");
                out.print("             /     /   /\r\n");
                out.print("           .'     /    \\\r\n");
                out.print("          (______(-.____)\r\n");
                out.print("***********************************************\n");
                started = true;
            }
            out.print("Available commands:\r\n\n");
            out.print("\t1) showTED\r\n");
            out.print("\t2) showPlugins\r\n");
            out.print("\t3) help\r\n");
            out.print("\tENTER) quit\r\n");
            out.print("TM:>");
            String command = null;
            try {
                command = br.readLine();
            } catch (IOException ioe) {
                log.warning("IO error trying to read your command");
                return;
            }
            if (command == null) {
                continue;
            }
            if (command.equals("quit") || command.equals("")) {
                log.info("Ending Management Session");
                out.println("bye!");
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }
            if (command.equals("showTED") || command.equals("1")) {
                out.print(tedb.printTopology() + "\n");
            } else if (command.equals("showPlguins") || command.equals("2")) {
                int i = 1;
                for (TMPlugin p : this.pluginsList) {
                    out.print(i + ") " + p.getPluginName());
                    if (p.isRunning())
                        out.print(" [Running]\n");
                    else
                        out.print(" [Stop]\n");
                    i++;
                }
                out.print("ENTER) back\n\nTM:>");
                String command2;
                try {
                    command2 = br.readLine();
                } catch (IOException ioe) {
                    log.warning("IO error trying to read your command");
                    return;
                }
                if (command2 == null) {
                    continue;
                }
                try {
                    int option = Integer.parseInt(command2);
                    out.print(this.pluginsList.get(option - 1).displayInfo() + "\n\n");
                } catch (java.lang.NumberFormatException e) {
                    continue;
                }
            } else if (command.equals("help") || command.equals("3")) {
                out.print("Available commands:\r\n\n");
                out.print("\t1) showTED\r\n");
                out.print("\t2) help\r\n");
                out.print("\tENTER) quit\r\n");
            } else {
                out.print("invalid command\n");
                out.print("\n");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }
}
Example 82
Project: platform2-master  File: CampusApplicationFormHelper.java View source code
/**
	 * 
	 */
public static void saveCampusInformation(IWContext iwc) {
    int studyBeginMon = 0;
    int studyBeginYr = 0;
    int studyEndMo = 0;
    int studyEndYr = 0;
    int spouseStudyBeginMo = 0;
    int spouseStudyBeginYr = 0;
    int spouseStudyEndMo = 0;
    int spouseStudyEndYr = 0;
    int currentResidence = 0;
    int spouseOccupation = 0;
    int schoolID = 0;
    String faculty = iwc.getParameter("faculty");
    String school = iwc.getParameter("school");
    String studyTrack = iwc.getParameter("studyTrack");
    // String resInfo = iwc.getParameter("resInfo");
    String spouseName = iwc.getParameter("spouseName");
    String spouseSSN = iwc.getParameter("spouseSSN");
    String spouseSchool = iwc.getParameter("spouseSchool");
    String spouseStudyTrack = iwc.getParameter("spouseStudyTrack");
    String studyBegin = iwc.getParameter("studyBegin");
    String studyEnd = iwc.getParameter("studyEnd");
    String spouseStudyBegin = iwc.getParameter("spouseStudyBegin");
    String spouseStudyEnd = iwc.getParameter("spouseStudyEnd");
    // String children = iwc.getParameter("children");
    String wantHousingFrom = iwc.getParameter("wantHousingFrom");
    String waitingList = iwc.getParameter("waitingList");
    String furniture = iwc.getParameter("furniture");
    String contact = iwc.getParameter("contact");
    String email = iwc.getParameter("email");
    String info = iwc.getParameter("extra_info");
    CampusApplication application = null;
    Applicant spouse = null;
    try {
        application = ((CampusApplicationHome) IDOLookup.getHome(CampusApplication.class)).create();
        spouse = ((ApplicantHome) IDOLookup.getHome(Applicant.class)).create();
    } catch (IDOLookupException e1) {
        e1.printStackTrace();
    } catch (CreateException e1) {
        e1.printStackTrace();
    }
    Vector childs = new Vector();
    try {
        currentResidence = Integer.parseInt(iwc.getParameter("currentResidence"));
    } catch (java.lang.NumberFormatException e) {
    }
    try {
        spouseOccupation = Integer.parseInt(iwc.getParameter("spouseOccupation"));
    } catch (java.lang.NumberFormatException e) {
    }
    try {
        schoolID = new Integer(school).intValue();
    } catch (NumberFormatException e) {
    }
    if (studyBegin != null) {
        try {
            IWTimestamp stamp = new IWTimestamp(studyBegin);
            studyBeginMon = stamp.getMonth();
            studyBeginYr = stamp.getYear();
        } catch (Exception ex) {
        }
    }
    if (studyEnd != null) {
        try {
            IWTimestamp stamp = new IWTimestamp(studyEnd);
            studyEndMo = stamp.getMonth();
            studyEndYr = stamp.getYear();
        } catch (Exception ex) {
        }
    }
    if (spouseStudyBegin != null) {
        try {
            IWTimestamp stamp = new IWTimestamp(spouseStudyBegin);
            spouseStudyBeginMo = stamp.getMonth();
            spouseStudyBeginYr = stamp.getYear();
        } catch (Exception ex) {
        }
    }
    if (spouseStudyEnd != null) {
        try {
            IWTimestamp stamp = new IWTimestamp(spouseStudyEnd);
            spouseStudyEndMo = stamp.getMonth();
            spouseStudyEndYr = stamp.getYear();
        } catch (Exception ex) {
        }
    }
    application.setCurrentResidenceId(currentResidence);
    application.setSpouseOccupationId(spouseOccupation);
    application.setStudyBeginMonth(studyBeginMon);
    application.setStudyBeginYear(studyBeginYr);
    application.setStudyEndMonth(studyEndMo);
    application.setStudyEndYear(studyEndYr);
    if (faculty != null) {
        application.setFaculty(faculty);
    }
    if (school != null) {
        application.setSchoolID(schoolID);
    }
    application.setStudyTrack(studyTrack);
    application.setSpouseName(spouseName);
    application.setSpouseSSN(spouseSSN);
    application.setSpouseSchool(spouseSchool);
    application.setSpouseStudyTrack(spouseStudyTrack);
    application.setSpouseStudyBeginMonth(spouseStudyBeginMo);
    application.setSpouseStudyBeginYear(spouseStudyBeginYr);
    application.setSpouseStudyEndMonth(spouseStudyEndMo);
    application.setSpouseStudyEndYear(spouseStudyEndYr);
    IWTimestamp t = new IWTimestamp(wantHousingFrom);
    System.out.println("want housing from = " + t.toString());
    application.setHousingFrom(t.getDate());
    if (waitingList == null)
        application.setOnWaitinglist(false);
    else
        application.setOnWaitinglist(true);
    if (furniture == null)
        application.setWantFurniture(false);
    else
        application.setWantFurniture(true);
    application.setContactPhone(contact);
    application.setOtherInfo(info);
    application.setEmail(email);
    // spouse part
    if (spouseName.length() > 0) {
        spouse.setFullName(spouseName);
        spouse.setSSN(spouseSSN);
        spouse.setStatus("P");
        iwc.setSessionAttribute("spouse", spouse);
    }
    // Children part
    if (iwc.isParameterSet("children_count")) {
        int count = Integer.parseInt(iwc.getParameter("children_count"));
        String name, birth;
        for (int i = 0; i < count; i++) {
            try {
                Applicant child = ((ApplicantHome) IDOLookup.getHome(Applicant.class)).create();
                name = iwc.getParameter("childname" + i);
                birth = iwc.getParameter("childbirth" + i);
                if (name.length() > 0) {
                    child.setFullName(name);
                    child.setSSN(birth);
                    child.setStatus("C");
                    childs.add(child);
                }
            } catch (IDOLookupException e2) {
                e2.printStackTrace();
            } catch (CreateException e2) {
                e2.printStackTrace();
            }
        }
        iwc.setSessionAttribute("childs", childs);
    }
    iwc.setSessionAttribute("campusapplication", application);
}
Example 83
Project: sharp-master  File: VODConfiguration.java View source code
private void setUpExceptionMappings() {
    mapType("java.lang.Throwable", "System.Exception");
    mapProperty("java.lang.Throwable.getMessage", "Message");
    mapProperty("java.lang.Throwable.getCause", "InnerException");
    mapType("java.lang.Error", "System.Exception");
    mapType("java.lang.OutOfMemoryError", "System.OutOfMemoryException");
    mapType("java.lang.Exception", "System.Exception");
    mapType("java.lang.RuntimeException", "System.Exception");
    mapType("java.lang.ClassCastException", "System.InvalidCastException");
    mapType("java.lang.NullPointerException", "System.ArgumentNullException");
    mapType("java.lang.IllegalArgumentException", "System.ArgumentException");
    mapType("java.lang.IllegalStateException", "System.InvalidOperationException");
    //mapType("java.lang.InterruptedException", "System.Exception");
    mapType("java.lang.IndexOutOfBoundsException", "System.IndexOutOfRangeException");
    mapType("java.lang.UnsupportedOperationException", "System.NotSupportedException");
    mapType("java.lang.ArrayIndexOutOfBoundsException", "System.IndexOutOfRangeException");
    mapType("java.lang.NoSuchMethodError", "System.MissingMethodException");
    mapType("java.io.IOException", "System.IO.IOException");
    mapType("java.net.SocketException", "System.Net.Sockets.SocketException");
    mapType("java.lang.SecurityException", "System.Security.SecurityException");
    //in .NET: ArgumentNullException, FormatException, or OverflowException: common base class is System.SystemException
    mapType("java.lang.NumberFormatException", "System.SystemException");
    mapType("java.lang.NoSuchFieldException", "System.MissingFieldException");
    mapType("java.rmi.NoSuchObjectException", "System.InvalidOperationException");
    mapType("java.util.NoSuchElementException", "System.InvalidOperationException");
    mapType("java.lang.NoSuchMethodException", "System.MissingMethodException");
    mapType("java.lang.reflect.InvocationTargetException", "System.Reflection.TargetInvocationException");
    mapType("java.lang.IllegalAccessException", "System.MethodAccessException");
    mapType("java.io.FileNotFoundException", "System.IO.FileNotFoundException");
    mapType("java.io.StreamCorruptedException", "System.IO.IOException");
    mapType("java.io.UTFDataFormatException", "System.IO.IOException");
    mapType("java.io.InvalidObjectException", "System.Runtime.Serialization.InvalidDataContractException");
    mapType("java.util.ConcurrentModificationException", "System.InvalidOperationException");
    //I've tried interfaces and abstract classes with System.Activator.CreateInstance,
    //and both attempts yield 'MissingMethodException' and not 'MemberAccessException'
    mapType("java.lang.InstantiationException", "System.MissingMethodException");
}
Example 84
Project: sharpen-master  File: VODConfiguration.java View source code
private void setUpExceptionMappings() {
    mapType("java.lang.Throwable", "System.Exception");
    mapProperty("java.lang.Throwable.getMessage", "Message");
    mapProperty("java.lang.Throwable.getCause", "InnerException");
    mapType("java.lang.Error", "System.Exception");
    mapType("java.lang.OutOfMemoryError", "System.OutOfMemoryException");
    mapType("java.lang.Exception", "System.Exception");
    mapType("java.lang.RuntimeException", "System.Exception");
    mapType("java.lang.ClassCastException", "System.InvalidCastException");
    mapType("java.lang.NullPointerException", "System.ArgumentNullException");
    mapType("java.lang.IllegalArgumentException", "System.ArgumentException");
    mapType("java.lang.IllegalStateException", "System.InvalidOperationException");
    //mapType("java.lang.InterruptedException", "System.Exception");
    mapType("java.lang.IndexOutOfBoundsException", "System.IndexOutOfRangeException");
    mapType("java.lang.UnsupportedOperationException", "System.NotSupportedException");
    mapType("java.lang.ArrayIndexOutOfBoundsException", "System.IndexOutOfRangeException");
    mapType("java.lang.NoSuchMethodError", "System.MissingMethodException");
    mapType("java.io.IOException", "System.IO.IOException");
    mapType("java.net.SocketException", "System.Net.Sockets.SocketException");
    mapType("java.lang.SecurityException", "System.Security.SecurityException");
    //in .NET: ArgumentNullException, FormatException, or OverflowException: common base class is System.SystemException
    mapType("java.lang.NumberFormatException", "System.SystemException");
    mapType("java.lang.NoSuchFieldException", "System.MissingFieldException");
    mapType("java.rmi.NoSuchObjectException", "System.InvalidOperationException");
    mapType("java.util.NoSuchElementException", "System.InvalidOperationException");
    mapType("java.lang.NoSuchMethodException", "System.MissingMethodException");
    mapType("java.lang.reflect.InvocationTargetException", "System.Reflection.TargetInvocationException");
    mapType("java.lang.IllegalAccessException", "System.MethodAccessException");
    mapType("java.io.FileNotFoundException", "System.IO.FileNotFoundException");
    mapType("java.io.StreamCorruptedException", "System.IO.IOException");
    mapType("java.io.UTFDataFormatException", "System.IO.IOException");
    mapType("java.io.InvalidObjectException", "System.Runtime.Serialization.InvalidDataContractException");
    mapType("java.util.ConcurrentModificationException", "System.InvalidOperationException");
    //I've tried interfaces and abstract classes with System.Activator.CreateInstance,
    //and both attempts yield 'MissingMethodException' and not 'MemberAccessException'
    mapType("java.lang.InstantiationException", "System.MissingMethodException");
}
Example 85
Project: sharpen_imazen-master  File: VODConfiguration.java View source code
private void setUpExceptionMappings() {
    mapType("java.lang.Throwable", "System.Exception");
    mapProperty("java.lang.Throwable.getMessage", "Message");
    mapProperty("java.lang.Throwable.getCause", "InnerException");
    mapType("java.lang.Error", "System.Exception");
    mapType("java.lang.OutOfMemoryError", "System.OutOfMemoryException");
    mapType("java.lang.Exception", "System.Exception");
    mapType("java.lang.RuntimeException", "System.Exception");
    mapType("java.lang.ClassCastException", "System.InvalidCastException");
    mapType("java.lang.NullPointerException", "System.ArgumentNullException");
    mapType("java.lang.IllegalArgumentException", "System.ArgumentException");
    mapType("java.lang.IllegalStateException", "System.InvalidOperationException");
    //mapType("java.lang.InterruptedException", "System.Exception");
    mapType("java.lang.IndexOutOfBoundsException", "System.IndexOutOfRangeException");
    mapType("java.lang.UnsupportedOperationException", "System.NotSupportedException");
    mapType("java.lang.ArrayIndexOutOfBoundsException", "System.IndexOutOfRangeException");
    mapType("java.lang.NoSuchMethodError", "System.MissingMethodException");
    mapType("java.io.IOException", "System.IO.IOException");
    mapType("java.net.SocketException", "System.Net.Sockets.SocketException");
    mapType("java.lang.SecurityException", "System.Security.SecurityException");
    //in .NET: ArgumentNullException, FormatException, or OverflowException: common base class is System.SystemException
    mapType("java.lang.NumberFormatException", "System.SystemException");
    mapType("java.lang.NoSuchFieldException", "System.MissingFieldException");
    mapType("java.rmi.NoSuchObjectException", "System.InvalidOperationException");
    mapType("java.util.NoSuchElementException", "System.InvalidOperationException");
    mapType("java.lang.NoSuchMethodException", "System.MissingMethodException");
    mapType("java.lang.reflect.InvocationTargetException", "System.Reflection.TargetInvocationException");
    mapType("java.lang.IllegalAccessException", "System.MethodAccessException");
    mapType("java.io.FileNotFoundException", "System.IO.FileNotFoundException");
    mapType("java.io.StreamCorruptedException", "System.IO.IOException");
    mapType("java.io.UTFDataFormatException", "System.IO.IOException");
    mapType("java.io.InvalidObjectException", "System.Runtime.Serialization.InvalidDataContractException");
    mapType("java.util.ConcurrentModificationException", "System.InvalidOperationException");
    //I've tried interfaces and abstract classes with System.Activator.CreateInstance,
    //and both attempts yield 'MissingMethodException' and not 'MemberAccessException'
    mapType("java.lang.InstantiationException", "System.MissingMethodException");
}
Example 86
Project: skandroid-core-master  File: FormattedValues.java View source code
/**
   * Get a formatted latency value
   *
   * @param pValue
   * @return
   */
public static Pair<String, String> sGetFormattedLatencyValue(String pValue) {
    // pValue = "失敗"; // "Failed" - for testing against invalid strings.
    String values[] = pValue.split(" ");
    String unit = "";
    if (values.length > 1) {
        unit = values[1];
    }
    try {
        if (unit.equals("s")) {
            return new Pair<>(new DecimalFormat("0.0").format(1000 * Float.valueOf(values[0])), unit);
        } else {
            //DecimalFormat useFormat = new DecimalFormat("000");
            DecimalFormat useFormat = new DecimalFormat("0");
            useFormat.setMaximumFractionDigits(0);
            return new Pair<>(useFormat.format(Math.round(Float.valueOf(values[0]))), unit);
        }
    } catch (java.lang.NumberFormatException e) {
        Log.d("SKCommon", "Warning: Value is not a number" + pValue);
        SKPorting.sAssert(FormattedValues.class, false);
        return new Pair<>("0", "");
    }
}
Example 87
Project: sonar-java-master  File: CatchUsesExceptionWithContextCheck.java View source code
private void h() {
    try {
    /* ... */
    } catch (// Compliant
    Exception // Compliant
    e) {
        throw Throwables.propagate(e);
    } catch (// Compliant - propagation
    RuntimeException // Compliant - propagation
    e) {
        throw e;
    } catch (// Noncompliant
    Exception // Noncompliant
    e) {
        throw new RuntimeException("context");
    }
    try {
    /* ... */
    } catch (// Compliant
    Exception // Compliant
    e) {
        throw new RuntimeException("context", e);
    }
    try {
    } catch (// Compliant
    Exception // Compliant
    e) {
        throw e;
    } finally {
    }
    try {
    } catch (// Noncompliant
    Exception // Noncompliant
    e) {
        int a;
    } catch (// Noncompliant
    Throwable // Noncompliant
    e) {
    }
    try {
    } catch (// Compliant
    IOException // Compliant
    e) {
        throw Throwables.propagate(e);
    }
    try {
    } catch (// Compliant
    IOException // Compliant
    e) {
        throw new RuntimeException(e);
    } catch (// Noncompliant
    Exception // Noncompliant
    e) {
        throw new RuntimeException(e.getMessage());
    } catch (// Compliant
    Exception // Compliant
    e) {
        throw Throwables.propagate(e);
    }
    try {
    } catch (// Compliant
    Exception // Compliant
    e) {
        throw e;
    } catch (Exception ex) {
        throw new XNIException(ex);
    }
    try {
    } catch (// Compliant
    NumberFormatException // Compliant
    e) {
        return 0;
    } catch (// Compliant
    InterruptedException // Compliant
    e) {
    } catch (// Compliant
    ParseException // Compliant
    e) {
    } catch (// Compliant
    MalformedURLException // Compliant
    e) {
    } catch (// Compliant
    java.time.format.DateTimeParseException // Compliant
    e) {
    }
    try {
    } catch (// Compliant
    Exception // Compliant
    e) {
        foo(someContextVariable, e);
    } catch (// Compliant
    Exception // Compliant
    e) {
        throw (Exception) new Foo("bar").initCause(e);
    } catch (// Compliant
    Exception // Compliant
    e) {
        foo(null, e).bar();
    } catch (// Compliant
    Exception // Compliant
    e) {
        throw foo(e).bar();
    } catch (// Noncompliant
    Exception // Noncompliant
    e) {
        throw e.getCause();
    } catch (// Compliant
    Exception // Compliant
    e) {
        throw (Exception) e;
    } catch (// Compliant
    Exception // Compliant
    e) {
        throw (e);
    } catch (// Noncompliant
    Exception // Noncompliant
    e) {
        throw (e).getClause();
    } catch (// Compliant
    Exception // Compliant
    e) {
        Exception e2 = e;
        throw e2;
    } catch (// Compliant
    Exception // Compliant
    e) {
        Exception foo = new RuntimeException(e);
    } catch (Exception e) {
        Exception foo = (e);
    } catch (// Compliant
    Exception // Compliant
    e) {
        Exception foo;
        foo = e;
    } catch (// Compliant
    java.lang.NumberFormatException // Compliant
    e) {
    } catch (// Compliant
    java.net.MalformedURLException // Compliant
    e) {
    } catch (// Compliant
    java.time.format.DateTimeParseException // Compliant
    e) {
    } catch (// Compliant
    java.text.ParseException // Compliant
    e) {
    } catch (// Noncompliant
    java.text.foo // Noncompliant
    e) {
    } catch (// Noncompliant [[sc=14;ec=39]]
    java.foo.ParseException // Noncompliant [[sc=14;ec=39]]
    e) {
    } catch (// Noncompliant
    foo.text.ParseException // Noncompliant
    e) {
    } catch (// Noncompliant
    text.ParseException // Noncompliant
    e) {
    } catch (// Noncompliant
    foo.java.text.ParseException // Noncompliant
    e) {
    } catch (// Compliant
    Exception // Compliant
    e) {
        Exception foo = false ? e : null;
    } catch (// Compliant
    Exception // Compliant
    e) {
        Exception foo = false ? null : e;
    } catch (// Compliant
    Exception // Compliant
    e) {
        Exception e2;
        foo = (e2 = e) ? null : null;
    } catch (// Compliant
    Exception // Compliant
    e) {
        throw wrapHttpException ? handleHttpException(e) : null;
    } catch (// Compliant
    Exception // Compliant
    e) {
        throw wrapHttpException ? null : e;
    } catch (// Noncompliant
    Exception // Noncompliant
    e) {
        try {
        } catch (Exception f) {
            System.out.println("", e.getCause());
        }
    }
}
Example 88
Project: tool.lars-master  File: Version4Digit.java View source code
@Override
public int compareTo(Version4Digit that) {
    if (equals(that)) {
        return 0;
    }
    if (this.getMajor() > that.getMajor()) {
        return 1;
    } else if (that.getMajor() > this.getMajor()) {
        return -1;
    }
    if (this.getMinor() > that.getMinor()) {
        return 1;
    } else if (that.getMinor() > this.getMinor()) {
        return -1;
    }
    if (this.getMicro() > that.getMicro()) {
        return 1;
    } else if (that.getMicro() > this.getMicro()) {
        return -1;
    }
    // now the tricky bit
    try {
        if (this.getiQualifier() > that.getiQualifier()) {
            return 1;
        } else if (that.getiQualifier() > this.getiQualifier()) {
            return -1;
        }
    } catch (NumberFormatException e) {
        return this.qualifier.compareTo(that.qualifier);
    }
    // equals
    return 0;
}
Example 89
Project: VisAD-master  File: DArraySelector.java View source code
public void focusLost(FocusEvent evt) {
    JTextField tf = (JTextField) evt.getComponent();
    int value;
    try {
        value = new Integer(tf.getText()).intValue();
    } catch (java.lang.NumberFormatException exc) {
        value = -1;
    }
    boolean retVal = false;
    if (value > upper) {
        tf.setText(String.valueOf(upper));
    } else if (value < lower) {
        tf.setText(String.valueOf(lower));
    }
    fireActionEvent();
}
Example 90
Project: voltdb-master  File: PipeToFile.java View source code
@Override
public void run() {
    assert (m_writer != null);
    assert (m_input != null);
    boolean initLocationFound = false;
    while (m_eof.get() != true) {
        try {
            String data = m_input.readLine();
            if (data == null) {
                m_eof.set(true);
                continue;
            }
            // let the optional watcher take a peak
            if (m_watcher != null) {
                m_watcher.handleLine(data);
            }
            // look for the non-exec site id
            if (data.contains(m_hostID)) {
                // INITIALIZING INITIATOR ID: 1, SITEID: 0
                String[] split = data.split(" ");
                synchronized (this) {
                    try {
                        m_hostId = Long.valueOf(split[split.length - 1].split(":")[0]).intValue();
                    } catch (java.lang.NumberFormatException e) {
                        System.err.println("Had a number format exception processing line: '" + data + "'");
                        throw e;
                    }
                }
            }
            // look for a sequence of letters matching the server ready token.
            if (!m_witnessedReady.get() && data.contains(m_token)) {
                synchronized (this) {
                    m_witnessedReady.set(true);
                    this.notifyAll();
                }
            }
            // look for a sequence of letters matching the server ready token.
            if (!initLocationFound && data.contains(m_initToken)) {
                initLocationFound = true;
                m_initTime = System.currentTimeMillis();
            }
            m_writer.write(data + "\n");
            m_writer.flush();
        } catch (IOException ex) {
            m_eof.set(true);
        }
    }
    synchronized (this) {
        notifyAll();
    }
    try {
        m_writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 91
Project: Wink-master  File: JAXRSExceptionsSubresourcesTest.java View source code
/**
     * Test the positive workflow where a comment with a message and author is
     * successfully posted to the Guestbook.
     * 
     * @throws Exception
     */
public void testRuntimeException() throws Exception {
    HttpClient client = new HttpClient();
    DeleteMethod deleteMethod = new DeleteMethod(getBaseURI() + "/commentdata/afdsfsdf");
    try {
        client.executeMethod(deleteMethod);
        assertEquals(Status.INTERNAL_SERVER_ERROR.getStatusCode(), deleteMethod.getStatusCode());
    // assertLogContainsException("java.lang.NumberFormatException: For input string: \"afdsfsdf\"");
    } finally {
        deleteMethod.releaseConnection();
    }
}
Example 92
Project: hapi-fhir-master  File: DefaultThymeleafNarrativeGeneratorDstu2Test.java View source code
@Test
public void testGenerateOperationOutcome() {
    //@formatter:off
    String parse = "<OperationOutcome xmlns=\"http://hl7.org/fhir\">\n" + "   <issue>\n" + "      <severity value=\"error\"/>\n" + "      <diagnostics value=\"ca.uhn.fhir.rest.server.exceptions.InternalErrorException: Failed to call access method

ca.uhn.fhir.rest.server.exceptions.InternalErrorException: Failed to call access method
	at ca.uhn.fhir.rest.method.BaseMethodBinding.invokeServerMethod(BaseMethodBinding.java:199)
	at ca.uhn.fhir.rest.method.HistoryMethodBinding.invokeServer(HistoryMethodBinding.java:162)
	at ca.uhn.fhir.rest.method.BaseResourceReturningMethodBinding.invokeServer(BaseResourceReturningMethodBinding.java:228)
	at ca.uhn.fhir.rest.method.HistoryMethodBinding.invokeServer(HistoryMethodBinding.java:1)
	at ca.uhn.fhir.rest.server.RestfulServer.handleRequest(RestfulServer.java:534)
	at ca.uhn.fhir.rest.server.RestfulServer.doGet(RestfulServer.java:141)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
	at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
	at org.ebaysf.web.cors.CORSFilter.handleNonCORS(CORSFilter.java:437)
	at org.ebaysf.web.cors.CORSFilter.doFilter(CORSFilter.java:172)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
	at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
	at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
	at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
	at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
	at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
	at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
	at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
	at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
	at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
	at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
	at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.reflect.InvocationTargetException
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:601)
	at ca.uhn.fhir.rest.method.BaseMethodBinding.invokeServerMethod(BaseMethodBinding.java:194)
	... 40 more
Caused by: java.lang.NumberFormatException: For input string: "3cb9a027-9e02-488d-8d01-952553d6be4e"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Long.parseLong(Long.java:441)
	at java.lang.Long.parseLong(Long.java:483)
	at ca.uhn.fhir.model.primitive.IdDt.getIdPartAsLong(IdDt.java:194)
	at ca.uhn.fhir.jpa.provider.JpaResourceProvider.getHistoryForResourceInstance(JpaResourceProvider.java:81)
	... 45 more
\"/>\n" + "   </issue>\n" + "   <issue>\n" + "      <severity value=\"warning\"/>\n" + "      <diagnostics value=\"YThis is a warning\"/>\n" + "   </issue>\n" + "</OperationOutcome>";
    //@formatter:on
    OperationOutcome oo = ourCtx.newXmlParser().parseResource(OperationOutcome.class, parse);
    // String output = gen.generateTitle(oo);
    // ourLog.info(output);
    // assertEquals("Operation Outcome (2 issues)", output);
    NarrativeDt narrative = new NarrativeDt();
    myGen.generateNarrative(ourCtx, oo, narrative);
    String output = narrative.getDiv().getValueAsString();
    ourLog.info(output);
    assertThat(output, containsString("<td><pre>YThis is a warning</pre></td>"));
}
Example 93
Project: hipergate-master  File: ProductList.java View source code
public String render(RenderRequest req, String sEncoding) throws PortletException, IOException, IllegalStateException {
    DBBind dbb;
    DBSubset dbs, img;
    JDCConnection con = null;
    ByteArrayInputStream oInStream;
    ByteArrayOutputStream oOutStream;
    String sOutput, sCategoryId, sTemplatePath, sLimit, sOffset, sWrkArGet, sWorkAreaId, sImagePath;
    int iOffset = 0, iLimit = 2147483647, iProdCount = 0, iImgCount = 0;
    if (DebugFile.trace) {
        DebugFile.writeln("Begin ProductList.render()");
        DebugFile.incIdent();
    }
    sOffset = req.getParameter("offset");
    sLimit = req.getParameter("limit");
    sCategoryId = (String) req.getAttribute("category");
    sTemplatePath = (String) req.getAttribute("template");
    sWorkAreaId = req.getProperty("workarea");
    sWrkArGet = req.getProperty("workareasget");
    if (DebugFile.trace) {
        DebugFile.writeln("template=" + sTemplatePath);
        DebugFile.writeln("category=" + sCategoryId);
        DebugFile.writeln("workarea=" + sWorkAreaId);
        DebugFile.writeln("workareasget=" + sWrkArGet);
    }
    try {
        if (null != sOffset)
            iOffset = Integer.parseInt(sOffset);
    } catch (java.lang.NumberFormatException nfe) {
        if (DebugFile.trace)
            DebugFile.decIdent();
        throw new PortletException("NumberFormatException parameter offset is not a valid integer value", nfe);
    }
    try {
        if (null != sLimit)
            iLimit = Integer.parseInt(sLimit);
    } catch (java.lang.NumberFormatException nfe) {
        if (DebugFile.trace)
            DebugFile.decIdent();
        throw new PortletException("NumberFormatException parameter limit is not a valid integer value", nfe);
    }
    try {
        dbb = (DBBind) getPortletContext().getAttribute("GlobalDBBind");
        dbs = new DBSubset(DB.k_products + " p," + DB.k_x_cat_objs + " x", "p." + DB.gu_product + ",p." + DB.nm_product + ",p." + DB.de_product + ",p." + DB.pr_list + ",p." + DB.pr_sale + ",p." + DB.id_currency + ",p." + DB.pct_tax_rate + ",p." + DB.is_tax_included + ",p." + DB.dt_start + ",p." + DB.dt_end + ",p." + DB.tag_product + ",p." + DB.id_ref, "p." + DB.gu_product + "=x." + DB.gu_object + " AND x." + DB.id_class + "=15 AND x." + DB.gu_category + "=? ORDER BY x." + DB.od_position, 20);
        con = dbb.getConnection("ProductList");
        if (null != sLimit)
            dbs.setMaxRows(iLimit);
        if (sOffset == null)
            iProdCount = dbs.load(con, new Object[] { sCategoryId });
        else
            iProdCount = dbs.load(con, new Object[] { sCategoryId }, iOffset);
    } catch (SQLException sqle) {
        if (DebugFile.trace)
            DebugFile.writeln("SQLException " + sqle.getMessage());
        if (con != null) {
            try {
                if (!con.isClosed())
                    con.close("ProductList");
            } catch (SQLException ignore) {
            }
        }
        if (DebugFile.trace)
            DebugFile.decIdent();
        throw new PortletException("SQLException " + sqle.getMessage(), sqle);
    }
    if (DebugFile.trace)
        DebugFile.writeln(String.valueOf(iProdCount) + " products found");
    StringBuffer oXML = new StringBuffer(8192);
    oXML.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-stylesheet type=\"text/xsl\"?>\n<products count=\"" + String.valueOf(iProdCount) + "\">\n");
    Product oCurrentProd = new Product();
    for (int c = 0; c < iProdCount; c++) {
        oXML.append("  <product>");
        oXML.append("<gu_product>" + dbs.getString(0, c) + "</gu_product><nm_product>" + dbs.getString(1, c) + "</nm_product><tr_product><![CDATA[" + dbs.getStringNull(2, c, "") + "]]></tr_product><de_product><![CDATA[" + dbs.getStringNull(3, c, "") + "]]></de_product>");
        oCurrentProd.replace(DB.gu_product, dbs.getString(0, c));
        oXML.append("<images>");
        try {
            img = oCurrentProd.getImages(con);
            iImgCount = img.getRowCount();
            for (int i = 0; i < iImgCount; i++) {
                oXML.append("<image tp=\"" + img.getString(DB.tp_image, i) + "\"><gu_image>" + img.getString(DB.gu_image, i) + "</gu_image>");
                sImagePath = img.getString(DB.path_image, i);
                oXML.append("<src_image><![CDATA[" + sWrkArGet + "/" + sWorkAreaId + "/apps/Shop/" + sImagePath.substring(sImagePath.indexOf(sWorkAreaId) + 43) + "]]></src_image>");
                oXML.append("<nm_image><![CDATA[" + img.getStringNull(DB.nm_image, i, "") + "]]></nm_image>");
                if (img.isNull(DB.dm_width, i))
                    oXML.append("<dm_width></dm_width>");
                else
                    oXML.append("<dm_width>" + img.get(DB.dm_width, i).toString() + "</dm_width>");
                if (img.isNull(DB.dm_height, i))
                    oXML.append("<dm_height></dm_height>");
                else
                    oXML.append("<dm_height>" + img.get(DB.dm_height, i).toString() + "</dm_height>");
                oXML.append("<tl_image>" + img.getStringNull(DB.tl_image, i, "") + "</tl_image></image>");
            }
        // next (i)
        } catch (SQLException sqle) {
        } catch (NullPointerException npe) {
        }
        oXML.append("</images></product>\n");
    }
    try {
        con.close("ProductList");
        con = null;
    } catch (SQLException sqle) {
        if (DebugFile.trace)
            DebugFile.writeln("SQLException " + sqle.getMessage());
    }
    oXML.append("</categories>");
    try {
        if (DebugFile.trace)
            DebugFile.writeln("new ByteArrayInputStream(" + String.valueOf(oXML.length()) + ")");
        oInStream = new ByteArrayInputStream(oXML.toString().getBytes("UTF-8"));
        oOutStream = new ByteArrayOutputStream(40000);
        Properties oProps = new Properties();
        Enumeration oKeys = req.getPropertyNames();
        while (oKeys.hasMoreElements()) {
            String sKey = (String) oKeys.nextElement();
            oProps.setProperty(sKey, req.getProperty(sKey));
        }
        // wend
        StylesheetCache.transform(sTemplatePath, oInStream, oOutStream, oProps);
        sOutput = oOutStream.toString("UTF-8");
        oOutStream.close();
        oInStream.close();
        oInStream = null;
    } catch (TransformerConfigurationException tce) {
        if (DebugFile.trace) {
            DebugFile.writeln("TransformerConfigurationException " + tce.getMessageAndLocation());
            try {
                DebugFile.write("--------------------------------------------------------------------------------\n");
                DebugFile.write(FileSystem.readfile(sTemplatePath));
                DebugFile.write("\n--------------------------------------------------------------------------------\n");
                DebugFile.write(oXML.toString());
                DebugFile.write("\n--------------------------------------------------------------------------------\n");
            } catch (java.io.IOException ignore) {
            } catch (com.enterprisedt.net.ftp.FTPException ignore) {
            }
            DebugFile.decIdent();
        }
        throw new PortletException("TransformerConfigurationException " + tce.getMessage(), tce);
    } catch (TransformerException tex) {
        if (DebugFile.trace) {
            DebugFile.writeln("TransformerException " + tex.getMessageAndLocation());
            try {
                DebugFile.write("--------------------------------------------------------------------------------\n");
                DebugFile.write(FileSystem.readfile(sTemplatePath));
                DebugFile.write("\n--------------------------------------------------------------------------------\n");
                DebugFile.write(oXML.toString());
                DebugFile.write("\n--------------------------------------------------------------------------------\n");
            } catch (java.io.IOException ignore) {
            } catch (com.enterprisedt.net.ftp.FTPException ignore) {
            }
            DebugFile.decIdent();
        }
        throw new PortletException("TransformerException " + tex.getMessage(), tex);
    }
    if (DebugFile.trace) {
        DebugFile.decIdent();
        DebugFile.writeln("End ProductList.render()");
    }
    return sOutput;
}
Example 94
Project: Keel3.0-master  File: Genesis.java View source code
/**
     * <p>
     * Transforms the dataset into a double matrix
     * </p>
     * @param array Output matrix
     * @param dataset Input dataset
     */
public static void DatasetToArray(double array[][], OpenDataset dataset) {
    String line;
    int pos1, pos2 = 0, group;
    // For all the patterns
    for (int i = 0; i < dataset.getndatos(); i++) {
        line = dataset.getDatosAt(i);
        pos1 = 1;
        int offset = 0;
        for (int j = 0; j < dataset.getnentradas(); j++) {
            pos2 = line.indexOf(",", pos1);
            if (dataset.getTiposAt(j) == 0) {
                Vector values = dataset.getRangosVar(j);
                String cats[] = new String[values.size()];
                for (int k = 0; k < values.size(); k++) {
                    cats[k] = values.elementAt(k).toString();
                }
                for (int k = 0; k < values.size(); k++) {
                    if (line.substring(pos1, pos2).compareToIgnoreCase(cats[k]) == 0) {
                        array[i][offset + k] = 1.0;
                    } else {
                        array[i][offset + k] = 0.0;
                    }
                }
                offset += values.size();
            } else {
                try {
                    array[i][offset] = Double.parseDouble(line.substring(pos1, pos2));
                } catch (java.lang.NumberFormatException NumberFormatException) {
                    array[i][offset] = 0.0;
                } catch (java.lang.ArrayIndexOutOfBoundsException e) {
                    e.printStackTrace();
                    System.exit(-1);
                }
                offset++;
            }
            pos1 = pos2 + 1;
        }
        // Take the output classes without spaces and convert them to binary outputs.
        pos1 = line.indexOf(",", pos2);
        //pos2 = line.indexOf("]" pos1);
        String category = line.substring(pos1 + 1, line.length());
        if (dataset.getTiposAt(dataset.getnentradas()) != 0) {
            pos1 = 0;
            for (int k = 0; k < dataset.getnsalidas() - 1; k++) {
                pos2 = category.indexOf(",", pos1);
                array[i][offset + k] = Double.parseDouble(category.substring(pos1, pos2));
                pos1 = pos2 + 1;
            }
            try {
                array[i][offset + dataset.getnsalidas() - 1] = Double.parseDouble(category.substring(pos1));
            } catch (java.lang.NumberFormatException e) {
                e.printStackTrace();
                System.exit(-1);
            }
        } else {
            Vector out_values = dataset.getRangosVar(dataset.getnentradas());
            String cats[] = new String[out_values.size()];
            for (int k = 0; k < out_values.size(); k++) {
                cats[k] = out_values.elementAt(k).toString();
            }
            for (int j = 0; j < out_values.size(); j++) {
                if (category.compareToIgnoreCase(cats[j]) == 0) {
                    array[i][offset + j] = 1.0;
                } else {
                    array[i][offset + j] = 0.0;
                }
            }
        }
    }
}
Example 95
Project: data-quality-master  File: SurvivorshipUtilsTest.java View source code
@Override
protected void outputRow(Object[] row) {
    row2Struct outStuct_tMatchGroup_1 = new row2Struct();
    if (0 < row.length) {
        try {
            outStuct_tMatchGroup_1.id = Integer.valueOf((String) row[0]);
        } catch (java.lang.NumberFormatException e) {
            outStuct_tMatchGroup_1.id = row[0] == null ? null : 0;
        }
    }
    if (1 < row.length) {
        outStuct_tMatchGroup_1.name = row[1] == null ? null : String.valueOf(row[1]);
    }
    if (2 < row.length) {
        try {
            outStuct_tMatchGroup_1.provinceID = Integer.valueOf((String) row[2]);
        } catch (java.lang.NumberFormatException e) {
            outStuct_tMatchGroup_1.provinceID = row[2] == null ? null : 0;
        }
    }
    if (3 < row.length) {
        outStuct_tMatchGroup_1.GID = row[3] == null ? null : String.valueOf(row[3]);
    }
    if (4 < row.length) {
        try {
            outStuct_tMatchGroup_1.GRP_SIZE = Integer.valueOf((String) row[4]);
        } catch (java.lang.NumberFormatException e) {
            outStuct_tMatchGroup_1.GRP_SIZE = row[4] == null ? null : 0;
        }
    }
    if (5 < row.length) {
        outStuct_tMatchGroup_1.MASTER = row[5] == null ? null : Boolean.valueOf((String) row[5]);
    }
    if (6 < row.length) {
        try {
            outStuct_tMatchGroup_1.SCORE = Double.valueOf((String) row[6]);
        } catch (java.lang.NumberFormatException e) {
            outStuct_tMatchGroup_1.SCORE = 0.0;
        }
    }
    if (7 < row.length) {
        try {
            outStuct_tMatchGroup_1.GRP_QUALITY = Double.valueOf((String) row[7]);
        } catch (java.lang.NumberFormatException e) {
            outStuct_tMatchGroup_1.GRP_QUALITY = 0.0;
        }
    }
    if (8 < row.length) {
        outStuct_tMatchGroup_1.MATCHING_DISTANCES = row[8] == null ? null : String.valueOf(row[8]);
    }
}
Example 96
Project: CodenameOne-master  File: Integer.java View source code
/**
     * Parses the string argument as a signed integer in the radix specified by the second argument. The characters in the string must all be digits of the specified radix (as determined by whether
     * returns a nonnegative value), except that the first character may be an ASCII minus sign '-' ('
     * u002d') to indicate a negative value. The resulting integer value is returned.
     * An exception of type NumberFormatException is thrown if any of the following situations occurs: The first argument is null or is a string of length zero. The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX. Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('u002d') provided that the string is longer than length 1. The integer value represented by the string is not a value of type int.
     * Examples:
     * parseInt("0", 10) returns 0 parseInt("473", 10) returns 473 parseInt("-0", 10) returns 0 parseInt("-FF", 16) returns -255 parseInt("1100110", 2) returns 102 parseInt("2147483647", 10) returns 2147483647 parseInt("-2147483648", 10) returns -2147483648 parseInt("2147483648", 10) throws a NumberFormatException parseInt("99", 8) throws a NumberFormatException parseInt("Kona", 10) throws a NumberFormatException parseInt("Kona", 27) returns 411787
     */
public static int parseInt(String string, int radix) throws NumberFormatException {
    if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
        throw new NumberFormatException("Invalid radix: " + radix);
    }
    if (string == null) {
        throw invalidInt(string);
    }
    int length = string.length(), i = 0;
    if (length == 0) {
        throw invalidInt(string);
    }
    boolean negative = string.charAt(i) == '-';
    if (negative && ++i == length) {
        throw invalidInt(string);
    }
    return parse(string, i, radix, negative);
}
Example 97
Project: concretesplitviewer-master  File: OSVReader.java View source code
/**
     * Parse OSV-file as 'Version 1'
     * @param groups Strings that produced by splitting file with '#'
     * @return true if successful, false if any kind of error found
     */
private boolean isVersionOne(File file, String[] groups) throws NotRightFormatException {
    if (groups.length <= 0) {
        System.err.println("Please check are there records in file. May be it is empty.");
        return false;
    }
    String[] headerLines = groups[0].split("\n");
    if (headerLines.length <= 0) {
        System.out.println("It is not 'Version 1' OSV-file. No header lines.");
        return false;
    }
    Pattern p = Pattern.compile(".*Version[ \\t]+(1)\\s*");
    Matcher m = p.matcher(headerLines[0]);
    if (!m.matches()) {
        System.out.println("It is not 'Version 1' OSV-file. First line not contain 'Version 1'.");
        return false;
    }
    System.out.println("It seems 'Version 1' OSV-file.");
    if (headerLines.length < 5) {
        System.err.println("Bad 'Version 1' file format: header contains less than 5 lines.");
        return false;
    }
    /*
         * Parse header lines and find interesting descriptors
         */
    int nameStart = 0, nameEnd = 0, resultStart = 0, resultEnd = 0, splitStart = 0;
    boolean namePresented = false, resultPresented = false, splitPresented = false;
    Pattern pName = Pattern.compile(".*@NAME(.+),(.+)\\s*");
    Pattern pResult = Pattern.compile(".*@RESULT(.+),(.+)\\s*");
    Pattern pSplits = Pattern.compile(".*@SPLITS[ \\t]+(\\d+)\\s*");
    for (int i = 1; i < headerLines.length; i++) {
        Matcher mName = pName.matcher(headerLines[i]);
        if (mName.matches()) {
            nameStart = Integer.parseInt(mName.group(1).trim());
            nameEnd = Integer.parseInt(mName.group(2).trim());
            nameEnd = nameEnd + nameStart - 1;
            namePresented = true;
            continue;
        }
        Matcher mResult = pResult.matcher(headerLines[i]);
        if (mResult.matches()) {
            resultStart = Integer.parseInt(mResult.group(1).trim());
            resultEnd = Integer.parseInt(mResult.group(2).trim());
            resultEnd = resultEnd + resultStart - 1;
            resultPresented = true;
            continue;
        }
        Matcher mSplits = pSplits.matcher(headerLines[i]);
        if (mSplits.matches()) {
            splitStart = Integer.parseInt(mSplits.group(1));
            splitPresented = true;
            continue;
        }
    // Here is line that doesn't match NAME, nor RESULT, nor SPLITS.
    // May be it is event description.
    // So it should be used as Title for main window.
    }
    // Check if all interesting descriptors presented
    if (!namePresented) {
        System.err.println("Bad 'Version 1' file format: @NAME is not presented.");
        return false;
    }
    if (!resultPresented) {
        System.err.println("Bad 'Version 1' file format: @RESULT is not presented.");
        return false;
    }
    if (!splitPresented) {
        System.err.println("Bad 'Version 1' file format: @SPLITS is not presented.");
        return false;
    }
    eventDescription = headerLines[4].trim();
    // All interesting descriptors presented.
    // Parse.
    groupsNames = new ArrayList<String>();
    LinkedList<Group> allGroupsTemp = new LinkedList<Group>();
    try {
        for (int i = 1; i < groups.length; i++) {
            allGroupsTemp.add(new Group());
            // Split all group lines
            String[] groupLines = groups[i].split("\\n");
            // Parse first line in group: find name, number of points and distance
            String groupName = "";
            int groupPoints = 0;
            int groupDistance = 0;
            Pattern pGroup = Pattern.compile("[ \\t]*([^\\s]+)[ \\t]*,[ \\t]*(\\d+).*,[ \\t]*(\\d+)\\.(\\d+).*\\s*");
            Matcher mGroup = pGroup.matcher(groupLines[0]);
            if (!mGroup.matches()) {
                System.err.println("Bad 'Version 1' file format. Bad group description line: '" + groupLines[0] + "'");
                return false;
            } else {
            }
            groupName = mGroup.group(1);
            groupPoints = Integer.parseInt(mGroup.group(2));
            groupDistance = 1000 * Integer.parseInt(mGroup.group(3)) + Integer.parseInt(mGroup.group(4));
            Distance d = new Distance(groupName, groupDistance, groupPoints + 1);
            // Find equal distance in other groups and store this fact
            Iterator<Group> it = allGroupsTemp.iterator();
            while (it.hasNext()) {
                Distance dTmp = it.next().getDistance();
                if (dTmp == null)
                    break;
                if (dTmp.equals(d)) {
                    dTmp.setName(dTmp.getName() + " " + d.getName());
                    d = dTmp;
                    break;
                }
            }
            groupsNames.add(groupName);
            allGroupsTemp.getLast().setDistance(d);
            allGroupsTemp.getLast().setName(groupName);
            if (DEBUG)
                System.out.println(groupName);
            // Parse each line in the group
            for (int j = 1; j < groupLines.length; j++) {
                String athleteName = "";
                String athleteResult = "";
                Time[] athleteSplits = new Time[groupPoints + 1];
                if (groupLines[j].length() < nameEnd) {
                    System.err.println("Bad 'Version 1' file format. Length of line: '" + groupLines[j] + "' is not enough for @NAME.");
                    return false;
                } else {
                    athleteName = groupLines[j].substring(nameStart - 1, nameEnd);
                }
                if (groupLines[j].length() < resultEnd) {
                    System.err.println("Bad 'Version 1' file format. Length of line: '" + groupLines[j] + "' is not enough for @RESULT.");
                    return false;
                } else {
                    athleteResult = groupLines[j].substring(resultStart - 1, resultEnd);
                }
                if (groupLines[j].length() < splitStart) {
                    System.err.println("Bad 'Version 1' file format. Length of line: '" + groupLines[j] + "' is not enough for @SPLITS.");
                    return false;
                } else {
                    if (DEBUG)
                        System.out.println(groupLines[j]);
                    String[] theSplits = groupLines[j].substring(splitStart - 1).trim().split("\\s+");
                    for (int k = 0; k < groupPoints + 1; k++) {
                        try {
                            athleteSplits[k] = new Time(theSplits[k], 2);
                        } catch (java.lang.NumberFormatException e) {
                            athleteSplits[k] = new Time(0, 2);
                        } catch (java.lang.ArrayIndexOutOfBoundsException e) {
                            athleteSplits[k] = new Time(0, 2);
                        }
                    }
                }
                String[] athleteNames = athleteName.split("[ \\t]+");
                Athlete a = new Athlete((athleteNames.length > 0 ? (athleteNames[0].trim()) : ""), (athleteNames.length > 1 ? (athleteNames[1].trim()) : ""), athleteSplits, allGroupsTemp.getLast(), 1900, athleteResult);
            }
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        return false;
    } catch (NumberFormatException nfe) {
        throw new NotRightFormatException(file, "OSV version 1", "bad number format: " + nfe.getMessage());
    }
    Iterator<Group> it = allGroupsTemp.iterator();
    while (it.hasNext()) {
        Distance d = it.next().getDistance();
        if (d.getLengthOfDist(1) < 0) {
            d.setLengthsOfDists(Tools.calculatLengthsOfLaps(d.getGroups()));
        }
    }
    allGroups = new ArrayList<Group>(allGroupsTemp);
    return true;
}
Example 98
Project: gsn-master  File: CSVHandler.java View source code
public TreeMap<String, Serializable> convertTo(String[] formats, String[] fields, String nullValues[], String[] values, char separator) {
    TreeMap<String, Serializable> streamElement = new TreeMap<String, Serializable>(new CaseInsensitiveComparator());
    for (String field : fields) streamElement.put(field, null);
    HashMap<String, String> timeStampFormats = new HashMap<String, String>();
    for (int i = 0; i < Math.min(fields.length, values.length); i++) {
        if (isNull(nullValues, values[i])) {
            continue;
        } else if (formats[i].equalsIgnoreCase("numeric")) {
            try {
                streamElement.put(fields[i], Double.parseDouble(values[i]));
            } catch (java.lang.NumberFormatException e) {
                logger.error("Parsing to Numeric failed: Value to parse=" + values[i] + " in" + getDataFile());
                throw e;
            }
        } else if (formats[i].equalsIgnoreCase("string")) {
            streamElement.put(fields[i], values[i]);
        } else if (formats[i].equalsIgnoreCase("bigint")) {
            try {
                streamElement.put(fields[i], Long.parseLong(values[i]));
            } catch (java.lang.NumberFormatException e) {
                logger.error("Parsing to BigInt failed: Value to parse=" + values[i] + " in" + getDataFile());
                throw e;
            }
        } else if (isTimeStampFormat(formats[i])) {
            String value = "";
            String format = "";
            if (streamElement.get(fields[i]) != null) {
                value = (String) streamElement.get(fields[i]);
                format = timeStampFormats.get(fields[i]);
                value += separator;
                format += separator;
            }
            if (isTimeStampLeftPaddedFormat(formats[i]))
                values[i] = StringUtils.leftPad(values[i], getTimeStampFormat(formats[i]).length(), '0');
            value += values[i];
            format += getTimeStampFormat(formats[i]);
            streamElement.put(fields[i], value);
            timeStampFormats.put(fields[i], format);
        }
    }
    for (String timeField : timeStampFormats.keySet()) {
        String timeFormat = timeStampFormats.get(timeField);
        String timeValue = (String) streamElement.get(timeField);
        try {
            DateTime x = DateTimeFormat.forPattern(timeFormat).withZone(getTimeZone()).parseDateTime(timeValue);
            streamElement.put(timeField, x.getMillis());
        } catch (IllegalArgumentException e) {
            logger.error("Parsing error: TimeFormat=" + timeFormat + " , TimeValue=" + timeValue + " in" + getDataFile());
            logger.error(e.getMessage(), e);
            throw e;
        }
    }
    return streamElement;
}
Example 99
Project: hadoop-20-master  File: ControlGroup.java View source code
public long getRSSMemoryUsage() {
    String[] kvPairs = this.getListParameter(MEM_STAT);
    if (kvPairs == null) {
        return 0;
    }
    for (String kvPair : kvPairs) {
        String[] kv = kvPair.split("\\s+");
        long ret;
        if (kv.length >= 2 && kv[0].trim().compareToIgnoreCase(MEM_RSS_IN_BYTES) == 0) {
            try {
                ret = Long.parseLong(kv[1].trim());
            } catch (NumberFormatException ne) {
                LOG.debug("Error reading parameter " + kv[1] + ": \"java.lang.NumberFormatException: " + ne.getMessage() + "\"");
                ret = 0;
            }
            return ret;
        }
    }
    return 0;
}
Example 100
Project: tajo-master  File: QueryExecutorServlet.java View source code
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String action = request.getParameter("action");
    Map<String, Object> returnValue = new HashMap<>();
    try {
        if (tajoClient == null) {
            errorResponse(response, "TajoClient not initialized");
            return;
        }
        if (action == null || action.trim().isEmpty()) {
            errorResponse(response, "no action parameter.");
            return;
        }
        if ("runQuery".equals(action)) {
            String prevQueryRunnerId = request.getParameter("prevQueryId");
            if (prevQueryRunnerId != null) {
                synchronized (queryRunners) {
                    QueryRunner runner = queryRunners.remove(prevQueryRunnerId);
                    if (runner != null)
                        runner.setStop();
                }
            }
            // if TajoMaster memory usage is over 50%, the request will be canceled
            float allowedMemoryRatio = 0.5f;
            long maxMemory = Runtime.getRuntime().maxMemory();
            long usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            if (usedMemory > maxMemory * allowedMemoryRatio) {
                errorResponse(response, "Allowed memory size of " + (maxMemory * allowedMemoryRatio) / (1024 * 1024) + " MB exhausted");
                return;
            }
            String query = request.getParameter("query");
            if (query == null || query.trim().isEmpty()) {
                errorResponse(response, "No query parameter");
                return;
            }
            String queryRunnerId = null;
            while (true) {
                synchronized (queryRunners) {
                    queryRunnerId = "" + System.currentTimeMillis();
                    if (!queryRunners.containsKey(queryRunnerId)) {
                        break;
                    }
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
            String database = request.getParameter("database");
            QueryRunner queryRunner = new QueryRunner(queryRunnerId, query, database);
            try {
                queryRunner.sizeLimit = Integer.parseInt(request.getParameter("limitSize"));
            } catch (java.lang.NumberFormatException nfe) {
                queryRunner.sizeLimit = 1048576;
            }
            try {
                queryRunner.rowLimit = Integer.parseInt(request.getParameter("limitRow"));
            } catch (java.lang.NumberFormatException nfe) {
                queryRunner.rowLimit = 3000000;
            }
            synchronized (queryRunners) {
                queryRunners.put(queryRunnerId, queryRunner);
            }
            queryRunnerExecutor.submit(queryRunner);
            returnValue.put("queryRunnerId", queryRunnerId);
        } else if ("getQueryProgress".equals(action)) {
            synchronized (queryRunners) {
                String queryRunnerId = request.getParameter("queryRunnerId");
                QueryRunner queryRunner = queryRunners.get(queryRunnerId);
                if (queryRunner == null) {
                    errorResponse(response, "No query info:" + queryRunnerId);
                    return;
                }
                if (queryRunner.error != null) {
                    errorResponse(response, queryRunner.error);
                    return;
                }
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                returnValue.put("progress", queryRunner.progress);
                returnValue.put("startTime", df.format(queryRunner.startTime));
                returnValue.put("finishTime", queryRunner.finishTime == 0 ? "-" : df.format(queryRunner.startTime));
                returnValue.put("runningTime", JSPUtil.getElapsedTime(queryRunner.startTime, queryRunner.finishTime));
            }
        } else if ("getQueryResult".equals(action)) {
            synchronized (queryRunners) {
                String queryRunnerId = request.getParameter("queryRunnerId");
                QueryRunner queryRunner = queryRunners.get(queryRunnerId);
                if (queryRunner == null) {
                    errorResponse(response, "No query info:" + queryRunnerId);
                    return;
                }
                if (queryRunner.error != null) {
                    errorResponse(response, queryRunner.error);
                    return;
                }
                returnValue.put("resultSize", queryRunner.resultRows);
                returnValue.put("resultData", queryRunner.queryResult);
                returnValue.put("resultColumns", queryRunner.columnNames);
                returnValue.put("runningTime", JSPUtil.getElapsedTime(queryRunner.startTime, queryRunner.finishTime));
            }
        } else if ("clearAllQueryRunner".equals(action)) {
            synchronized (queryRunners) {
                for (QueryRunner eachQueryRunner : queryRunners.values()) {
                    eachQueryRunner.setStop();
                }
                queryRunners.clear();
            }
        } else if ("killQuery".equals(action)) {
            String queryId = request.getParameter("queryId");
            if (queryId == null || queryId.trim().isEmpty()) {
                errorResponse(response, "No queryId parameter");
                return;
            }
            QueryStatus status = tajoClient.killQuery(TajoIdUtils.parseQueryId(queryId));
            if (status.getState() == TajoProtos.QueryState.QUERY_KILLED) {
                returnValue.put("successMessage", queryId + " is killed successfully.");
            } else if (status.getState() == TajoProtos.QueryState.QUERY_KILL_WAIT) {
                returnValue.put("successMessage", queryId + " will be finished after a while.");
            } else {
                errorResponse(response, "ERROR:" + status.getErrorMessage());
                return;
            }
        }
        returnValue.put("success", "true");
        writeHttpResponse(response, returnValue);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        errorResponse(response, e);
    }
}
Example 101
Project: xresloader-master  File: ExcelEngine.java View source code
/**
     * �元格数�转�(Integer)
     *
     * @param row    行
     * @param col    列�
     * @param evalor 公�管�器
     * @return
     */
public static DataContainer<Long> cell2i(Row row, IdentifyDescriptor col, FormulaEvaluator evalor) throws ConvException {
    DataContainer<Long> ret = new DataContainer<Long>();
    ret.setDefault(0L);
    if (null == row)
        return ret;
    Cell c = row.getCell(col.index);
    if (null == c)
        return ret;
    CellValue cv = null;
    if (CellType.FORMULA == c.getCellTypeEnum()) {
        if (null != evalor)
            cv = evalor.evaluate(c);
        else
            return ret;
    }
    CellType type = (null == cv) ? c.getCellTypeEnum() : cv.getCellTypeEnum();
    switch(type) {
        case BLANK:
            return ret;
        case BOOLEAN:
            if (null != col.verify_engine) {
                return ret.set(Long.valueOf(col.verify_engine.get(c.getBooleanCellValue() ? 1 : 0)));
            } else {
                return ret.set(c.getBooleanCellValue() ? 1L : 0L);
            }
        case ERROR:
            return ret;
        case FORMULA:
            return ret;
        case NUMERIC:
            {
                long val = 0;
                if (DateUtil.isCellDateFormatted(c)) {
                    val = dateToUnixTimestamp(c.getDateCellValue());
                } else {
                    val = Math.round(c.getNumericCellValue());
                }
                if (null != col.verify_engine) {
                    return ret.set(Long.valueOf(col.verify_engine.get((int) val)));
                } else {
                    return ret.set(val);
                }
            }
        case STRING:
            {
                String val = c.getStringCellValue().trim();
                if (val.isEmpty()) {
                    return ret;
                }
                try {
                    if (null != col.verify_engine) {
                        return ret.set(Long.valueOf(col.verify_engine.get(tryMacro(val))));
                    } else {
                        return ret.set(Math.round(Double.valueOf(tryMacro(val))));
                    }
                } catch (java.lang.NumberFormatException e) {
                    throw new ConvException(String.format("%s can not be converted to a integer", val));
                }
            }
        default:
            return ret;
    }
}