List of usage examples for java.lang Character valueOf
@HotSpotIntrinsicCandidate public static Character valueOf(char c)
From source file:org.apache.fop.fonts.SingleByteFont.java
/** * Returns an array with the widths for an additional encoding. * @param index the index of the additional encoding * @return the width array/*www . j a va 2 s . c o m*/ */ public int[] getAdditionalWidths(int index) { SimpleSingleByteEncoding enc = getAdditionalEncoding(index); int[] arr = new int[enc.getLastChar() - enc.getFirstChar() + 1]; for (int i = 0, c = arr.length; i < c; i++) { NamedCharacter nc = enc.getCharacterForIndex(enc.getFirstChar() + i); UnencodedCharacter uc = this.unencodedCharacters.get(Character.valueOf(nc.getSingleUnicodeValue())); arr[i] = uc.getWidth(); } return arr; }
From source file:org.unitime.timetable.backup.SessionRestore.java
public void create(TableData.Table table) throws InstantiationException, IllegalAccessException, DocumentException { ClassMetadata metadata = iHibSessionFactory.getClassMetadata(table.getName()); if (metadata == null) return;/*from w w w . j av a 2 s.com*/ PersistentClass mapping = _RootDAO.getConfiguration().getClassMapping(table.getName()); Map<String, Integer> lengths = new HashMap<String, Integer>(); for (String property : metadata.getPropertyNames()) { if ("org.unitime.timetable.model.CurriculumClassification.students" .equals(metadata.getEntityName() + "." + property)) continue; Type type = metadata.getPropertyType(property); if (type instanceof StringType) for (Iterator<?> i = mapping.getProperty(property).getColumnIterator(); i.hasNext();) { Object o = i.next(); if (o instanceof Column) { Column column = (Column) o; lengths.put(property, column.getLength()); } break; } } iProgress.setPhase(metadata.getEntityName().substring(metadata.getEntityName().lastIndexOf('.') + 1) + " [" + table.getRecordCount() + "]", table.getRecordCount()); for (TableData.Record record : table.getRecordList()) { iProgress.incProgress(); Object object = metadata.getMappedClass().newInstance(); for (String property : metadata.getPropertyNames()) { TableData.Element element = null; for (TableData.Element e : record.getElementList()) if (e.getName().equals(property)) { element = e; break; } if (element == null) continue; Object value = null; Type type = metadata.getPropertyType(property); if (type instanceof PrimitiveType) { if (type instanceof BooleanType) { value = new Boolean("true".equals(element.getValue(0))); } else if (type instanceof ByteType) { value = Byte.valueOf(element.getValue(0)); } else if (type instanceof CharacterType) { value = Character.valueOf(element.getValue(0).charAt(0)); } else if (type instanceof DoubleType) { value = Double.valueOf(element.getValue(0)); } else if (type instanceof FloatType) { value = Float.valueOf(element.getValue(0)); } else if (type instanceof IntegerType) { value = Integer.valueOf(element.getValue(0)); } else if (type instanceof LongType) { value = Long.valueOf(element.getValue(0)); } else if (type instanceof ShortType) { value = Short.valueOf(element.getValue(0)); } } else if (type instanceof DateType) { try { value = new SimpleDateFormat("dd MMMM yyyy", Localization.getJavaLocale()) .parse(element.getValue(0)); } catch (ParseException e) { value = new DateType().fromStringValue(element.getValue(0)); } } else if (type instanceof TimestampType) { value = new TimestampType().fromStringValue(element.getValue(0)); } else if (type instanceof StringType) { value = element.getValue(0); Integer len = lengths.get(property); if (len != null && value.toString().length() > len) { message("Value is too long, truncated (property " + metadata.getEntityName() + "." + property + ", length " + len + ")", record.getId()); value = value.toString().substring(0, len); } } else if (type instanceof BinaryType) { value = element.getValueBytes(0).toByteArray(); } else if (type instanceof CustomType && type.getReturnedClass().equals(Document.class)) { value = new SAXReader().read(new StringReader(element.getValue(0))); } else if (type instanceof EntityType) { } else if (type instanceof CollectionType) { } else { message("Unknown type " + type.getClass().getName() + " (property " + metadata.getEntityName() + "." + property + ", class " + type.getReturnedClass() + ")", record.getId()); } if (value != null) metadata.setPropertyValue(object, property, value); } add(new Entity(metadata, record, object, record.getId())); } }
From source file:edu.buffalo.cse.pigout.Main.java
static int run(String args[], PigProgressNotificationListener listener) { int rc = 1;/*from w w w .j a va 2 s. c om*/ boolean verbose = false; boolean pigoutCalled = false; String logFileName = null; try { Configuration conf = new Configuration(false); GenericOptionsParser parser = new GenericOptionsParser(conf, args); conf = parser.getConfiguration(); // create and update properties from configurations Properties properties = new Properties(); PropertiesUtil.loadDefaultProperties(properties); PropertiesUtil.loadPropertiesFromFile(properties, "./conf/pigout.properties"); properties.putAll(ConfigurationUtil.toProperties(conf)); for (String key : properties.stringPropertyNames()) { log.debug(key + " = " + properties.getProperty(key)); } if (listener == null) { listener = makeListener(properties); } String[] pigArgs = parser.getRemainingArgs(); boolean userSpecifiedLog = false; boolean checkScriptOnly = false; BufferedReader pin = null; boolean debug = false; boolean dryrun = false; boolean embedded = false; List<String> params = new ArrayList<String>(); List<String> paramFiles = new ArrayList<String>(); HashSet<String> disabledOptimizerRules = new HashSet<String>(); CmdLineParser opts = new CmdLineParser(pigArgs); opts.registerOpt('4', "log4jconf", CmdLineParser.ValueExpected.REQUIRED); opts.registerOpt('b', "brief", CmdLineParser.ValueExpected.NOT_ACCEPTED); opts.registerOpt('c', "check", CmdLineParser.ValueExpected.NOT_ACCEPTED); opts.registerOpt('d', "debug", CmdLineParser.ValueExpected.REQUIRED); opts.registerOpt('e', "execute", CmdLineParser.ValueExpected.NOT_ACCEPTED); opts.registerOpt('f', "file", CmdLineParser.ValueExpected.REQUIRED); opts.registerOpt('g', "embedded", CmdLineParser.ValueExpected.REQUIRED); opts.registerOpt('h', "help", CmdLineParser.ValueExpected.OPTIONAL); opts.registerOpt('i', "version", CmdLineParser.ValueExpected.OPTIONAL); opts.registerOpt('l', "logfile", CmdLineParser.ValueExpected.REQUIRED); opts.registerOpt('m', "param_file", CmdLineParser.ValueExpected.OPTIONAL); opts.registerOpt('p', "param", CmdLineParser.ValueExpected.OPTIONAL); opts.registerOpt('r', "dryrun", CmdLineParser.ValueExpected.NOT_ACCEPTED); opts.registerOpt('t', "optimizer_off", CmdLineParser.ValueExpected.REQUIRED); opts.registerOpt('v', "verbose", CmdLineParser.ValueExpected.NOT_ACCEPTED); opts.registerOpt('w', "warning", CmdLineParser.ValueExpected.NOT_ACCEPTED); opts.registerOpt('x', "exectype", CmdLineParser.ValueExpected.REQUIRED); opts.registerOpt('F', "stop_on_failure", CmdLineParser.ValueExpected.NOT_ACCEPTED); opts.registerOpt('M', "no_multiquery", CmdLineParser.ValueExpected.NOT_ACCEPTED); opts.registerOpt('P', "propertyFile", CmdLineParser.ValueExpected.REQUIRED); ExecMode mode = ExecMode.UNKNOWN; String file = null; String engine = null; ExecType execType = ExecType.LOCAL; // set up client side system properties in UDF context UDFContext.getUDFContext().setClientSystemProps(properties); char opt; //properties.setProperty("opt.multiquery",""+true); while ((opt = opts.getNextOpt()) != CmdLineParser.EndOfOpts) { switch (opt) { case '4': String log4jconf = opts.getValStr(); if (log4jconf != null) { properties.setProperty(LOG4J_CONF, log4jconf); } break; case 'b': properties.setProperty(BRIEF, "true"); break; case 'c': checkScriptOnly = true; break; case 'd': String logLevel = opts.getValStr(); if (logLevel != null) { properties.setProperty(DEBUG, logLevel); } debug = true; break; case 'e': mode = ExecMode.STRING; break; case 'f': mode = ExecMode.FILE; file = opts.getValStr(); break; case 'g': embedded = true; engine = opts.getValStr(); break; case 'F': properties.setProperty("stop.on.failure", "" + true); break; case 'h': String topic = opts.getValStr(); if (topic != null) { System.out.println("Topic based help is not provided yet."); usage(); } else usage(); return ReturnCode.SUCCESS; case 'i': System.out.println(getVersionString()); return ReturnCode.SUCCESS; case 'l': //call to method that validates the path to the log file //and sets up the file to store the client side log file String logFileParameter = opts.getValStr(); if (logFileParameter != null && logFileParameter.length() > 0) { logFileName = validateLogFile(logFileParameter, null); } else { logFileName = validateLogFile(logFileName, null); } userSpecifiedLog = true; properties.setProperty("pig.logfile", (logFileName == null ? "" : logFileName)); break; case 'm': //adds a parameter file paramFiles.add(opts.getValStr()); break; case 'M': // turns off multiquery optimization properties.setProperty("opt.multiquery", "" + false); break; case 'p': //adds a parameter params.add(opts.getValStr()); break; case 'r': // currently only used for parameter substitution // will be extended in the future dryrun = true; break; case 't': //disables a opt rule disabledOptimizerRules.add(opts.getValStr()); break; case 'v': properties.setProperty(VERBOSE, "" + true); verbose = true; break; case 'w': properties.setProperty("aggregate.warning", "" + false); break; case 'x': //sets execution type: try { execType = ExecType.fromString(opts.getValStr()); } catch (IOException e) { throw new RuntimeException("ERROR: Unrecognized exectype.", e); } break; case 'P': { InputStream inputStream = null; try { FileLocalizer.FetchFileRet localFileRet = FileLocalizer.fetchFile(properties, opts.getValStr()); inputStream = new BufferedInputStream(new FileInputStream(localFileRet.file)); properties.load(inputStream); } catch (IOException e) { throw new RuntimeException("Unable to parse properties file '" + opts.getValStr() + "'"); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } break; default: { Character cc = Character.valueOf(opt); throw new AssertionError("Unhandled option " + cc.toString()); } } } // create the context with the parameter PigContext pigContext = new PigContext(execType, properties); // create the static script state object String commandLine = LoadFunc.join((AbstractList<String>) Arrays.asList(args), " "); ScriptState scriptState = ScriptState.start(commandLine, pigContext); if (listener != null) { scriptState.registerListener(listener); } pigContext.getProperties().setProperty("pig.cmd.args", commandLine); if (logFileName == null && !userSpecifiedLog) { logFileName = validateLogFile(properties.getProperty("pig.logfile"), null); } pigContext.getProperties().setProperty("pig.logfile", (logFileName == null ? "" : logFileName)); // configure logging configureLog4J(properties, pigContext); log.info(getVersionString().replace("\n", "")); if (logFileName != null) { log.info("Logging error messages to: " + logFileName); } if (!Boolean.valueOf(properties.getProperty(PROP_FILT_SIMPL_OPT, "false"))) { //turn off if the user has not explicitly turned on this optimization disabledOptimizerRules.add("FilterLogicExpressionSimplifier"); } pigContext.getProperties().setProperty("pig.optimizer.rules", ObjectSerializer.serialize(disabledOptimizerRules)); PigContext.setClassLoader(pigContext.createCl(null)); // construct the parameter substitution preprocessor PigOutSh pigOutSh = null; BufferedReader in; String substFile = null; paramFiles = fetchRemoteParamFiles(paramFiles, properties); pigContext.setParams(params); pigContext.setParamFiles(paramFiles); switch (mode) { case FILE: { String remainders[] = opts.getRemainingArgs(); if (remainders != null) { pigContext.getProperties().setProperty(PigContext.PIG_CMD_ARGS_REMAINDERS, ObjectSerializer.serialize(remainders)); } FileLocalizer.FetchFileRet localFileRet = FileLocalizer.fetchFile(properties, file); if (localFileRet.didFetch) { properties.setProperty("pig.jars.relative.to.dfs", "true"); } scriptState.setFileName(file); if (embedded) { return runEmbeddedScript(pigContext, localFileRet.file.getPath(), engine); } else { SupportedScriptLang type = determineScriptType(localFileRet.file.getPath()); log.debug("File: " + localFileRet.file.getPath() + " Script type: " + type); if (type != null) { return runEmbeddedScript(pigContext, localFileRet.file.getPath(), type.name().toLowerCase()); } } //Reader is created by first loading "pigout.load.default.statements" or .pigoutbootup file if available in = new BufferedReader(new InputStreamReader( Utils.getCompositeStream(new FileInputStream(localFileRet.file), properties))); //run parameter substitution preprocessor first substFile = file + ".substituted"; pin = runParamPreprocessor(pigContext, in, substFile, debug || dryrun || checkScriptOnly); if (dryrun) { if (dryrun(substFile, pigContext)) { log.info("Dry run completed. Substituted pig script is at " + substFile + ". Expanded pig script is at " + file + ".expanded"); } else { log.info("Dry run completed. Substituted pig script is at " + substFile); } return ReturnCode.SUCCESS; } logFileName = validateLogFile(logFileName, file); pigContext.getProperties().setProperty("pig.logfile", (logFileName == null ? "" : logFileName)); // Set job name based on name of the script pigContext.getProperties().setProperty(PigContext.JOB_NAME, "PigOut_" + new File(file).getName()); if (!debug) { new File(substFile).deleteOnExit(); } scriptState.setScript(new File(file)); // From now on, PigOut starts... // Create a shell interface to PigOutServer pigOutSh = new PigOutSh(pin, pigContext); pigoutCalled = true; if (checkScriptOnly) { // -c option //Check syntax pigOutSh.checkScript(substFile); System.err.println(file + " syntax OK"); return ReturnCode.SUCCESS; } // parseAndBuild() will parse, and then generate a script log.info("PigOut is parsing and analyzing the script..."); pigOutSh.parseAndBuild(); log.debug("PigOut is partitioning the plan..."); pigOutSh.partition(); return ReturnCode.SUCCESS; } case STRING: { log.error("Please use FILE mode."); return -1; } default: break; } } catch (ParseException e) { usage(); rc = ReturnCode.PARSE_EXCEPTION; PigStatsUtil.setErrorMessage(e.getMessage()); PigStatsUtil.setErrorThrowable(e); } catch (org.apache.pig.tools.parameters.ParseException e) { // usage(); rc = ReturnCode.PARSE_EXCEPTION; PigStatsUtil.setErrorMessage(e.getMessage()); PigStatsUtil.setErrorThrowable(e); } catch (IOException e) { if (e instanceof PigException) { PigException pe = (PigException) e; rc = (pe.retriable()) ? ReturnCode.RETRIABLE_EXCEPTION : ReturnCode.PIG_EXCEPTION; PigStatsUtil.setErrorMessage(pe.getMessage()); PigStatsUtil.setErrorCode(pe.getErrorCode()); } else { rc = ReturnCode.IO_EXCEPTION; PigStatsUtil.setErrorMessage(e.getMessage()); } PigStatsUtil.setErrorThrowable(e); if (!pigoutCalled) { LogUtils.writeLog(e, logFileName, log, verbose, "Error before Pig is launched"); } } catch (Throwable e) { rc = ReturnCode.THROWABLE_EXCEPTION; PigStatsUtil.setErrorMessage(e.getMessage()); PigStatsUtil.setErrorThrowable(e); e.printStackTrace(); if (!pigoutCalled) { LogUtils.writeLog(e, logFileName, log, verbose, "Error before Pig is launched"); } } finally { // clear temp files FileLocalizer.deleteTempFiles(); PerformanceTimerFactory.getPerfTimerFactory().dumpTimers(); } return rc; }
From source file:org.apache.openjpa.jdbc.schema.Column.java
/** * Return the default value set for this column, if any. If only a default * string has been set, attempts to convert it to the right type based * on the Java type set for this column. */// w ww. j a v a 2s. com public Object getDefault() { if (_default != null) return _default; if (_defaultStr == null) return null; switch (_javaType) { case JavaTypes.BOOLEAN: case JavaTypes.BOOLEAN_OBJ: _default = ("true".equals(_defaultStr)) ? Boolean.TRUE : Boolean.FALSE; break; case JavaTypes.BYTE: case JavaTypes.BYTE_OBJ: _default = new Byte(_defaultStr); break; case JavaTypes.CHAR: case JavaTypes.CHAR_OBJ: _default = Character.valueOf(_defaultStr.charAt(0)); break; case JavaTypes.DOUBLE: case JavaTypes.DOUBLE_OBJ: _default = new Double(_defaultStr); break; case JavaTypes.FLOAT: case JavaTypes.FLOAT_OBJ: _default = new Float(_defaultStr); break; case JavaTypes.INT: case JavaTypes.INT_OBJ: _default = Integer.parseInt(_defaultStr); break; case JavaTypes.LONG: case JavaTypes.LONG_OBJ: _default = Long.parseLong(_defaultStr); break; case JavaTypes.NUMBER: case JavaTypes.BIGDECIMAL: _default = new BigDecimal(_defaultStr); break; case JavaTypes.SHORT: case JavaTypes.SHORT_OBJ: _default = new Short(_defaultStr); break; case JavaTypes.DATE: _default = new java.util.Date(_defaultStr); break; case JavaTypes.BIGINTEGER: _default = new BigInteger(_defaultStr); break; case JavaSQLTypes.SQL_DATE: _default = Date.valueOf(_defaultStr); break; case JavaSQLTypes.TIMESTAMP: _default = Timestamp.valueOf(_defaultStr); break; case JavaSQLTypes.TIME: _default = Time.valueOf(_defaultStr); break; default: _default = _defaultStr; } return _default; }
From source file:stg.utils.RandomStringGenerator.java
/** * Generates the random string as per the format. * /*from ww w .jav a2 s.c o m*/ * @return String */ public String generate() { CharacterIterator iter = new StringCharacterIterator(format); char c = iter.first(); StringBuilder sb = new StringBuilder(); List<Character> tempLowerCaseCharsList = cloneList(lowerCaseCharsList); List<Character> tempUpperCaseCharsList = cloneList(upperCaseCharsList); List<Character> tempNumericCharsList = cloneList(numericCharsList); List<Character> tempSpecialCharsList = cloneList(specialCharsList); boolean constantStarted = false; while (c != CharacterIterator.DONE) { switch (c) { case ESCAPE: c = iter.next(); if (c == CharacterIterator.DONE) { throw new IllegalArgumentException( "Invalid format, escape character found without any associated character that was to be escaped."); } sb.append(c); break; case LOWER_CASE: if (!constantStarted) { switch (option) { case NON_UNIQUE: sb.append(RandomStringUtils.random(1, toCharArray(lowerCaseCharsList))); break; case UNIQUE_CASE_SENSITIVE: sb.append(generateUniqueCharacter(c, tempLowerCaseCharsList)); break; default: String str = generateUniqueCharacter(c, tempLowerCaseCharsList); sb.append(str); if (!tempUpperCaseCharsList.contains(Character.valueOf(str.toUpperCase().charAt(0)))) { System.out.println(tempLowerCaseCharsList + " \t " + str); } if (!tempUpperCaseCharsList.remove(Character.valueOf(str.toUpperCase().charAt(0)))) { //remove it from the upper case char set. System.out.println("Problem unable to remove " + tempUpperCaseCharsList + "\t" + str); } break; } } else { sb.append(c); } break; case UPPER_CASE: if (!constantStarted) { switch (option) { case NON_UNIQUE: sb.append(RandomStringUtils.random(1, toCharArray(upperCaseCharsList))); break; case UNIQUE_CASE_SENSITIVE: sb.append(generateUniqueCharacter(c, tempUpperCaseCharsList)); break; default: String str = generateUniqueCharacter(c, tempUpperCaseCharsList); sb.append(str); if (!tempLowerCaseCharsList.contains(Character.valueOf(str.toLowerCase().charAt(0)))) { System.out.println(tempLowerCaseCharsList + " \t " + str); } if (!tempLowerCaseCharsList.remove(Character.valueOf(str.toLowerCase().charAt(0)))) { System.out.println("Problem unable to remove " + tempLowerCaseCharsList + "\t" + str); } break; } } else { sb.append(c); } break; case NUMBER: if (!constantStarted) { switch (option) { case NON_UNIQUE: sb.append(RandomStringUtils.random(1, toCharArray(numericCharsList))); break; default: sb.append(generateUniqueCharacter(c, tempNumericCharsList)); break; } } else { sb.append(c); } break; case SPECIAL: if (!constantStarted) { switch (option) { case NON_UNIQUE: sb.append(RandomStringUtils.random(1, toCharArray(specialCharsList))); break; default: sb.append(generateUniqueCharacter(c, tempSpecialCharsList)); break; } } else { sb.append(c); } break; case START_CONSTANT: if (constantStarted) { throw new IllegalArgumentException("Special { character found without an escape character"); } if (!constantStarted) constantStarted = true; break; case END_CONSTANT: if (!constantStarted) throw new IllegalArgumentException("Special } character found without an escape character"); if (constantStarted) constantStarted = false; break; default: sb.append(c); } c = iter.next(); } return sb.toString(); }
From source file:org.pdfsam.console.business.pdf.handlers.SplitCmdExecutor.java
/** * Execute the split of a pdf document when split type is S_BLEVEL * /*from w w w.ja va2 s .c o m*/ * @param inputCommand * @param bookmarksTable * bookmarks table. It's populated only when splitting by bookmarks. If null or empty it's ignored * @throws Exception */ private void executeSplit(SplitParsedCommand inputCommand, Hashtable bookmarksTable) throws Exception { pdfReader = PdfUtility.readerFor(inputCommand.getInputFile()); pdfReader.removeUnusedObjects(); pdfReader.consolidateNamedDestinations(); int n = pdfReader.getNumberOfPages(); BookmarksProcessor bookmarkProcessor = new BookmarksProcessor(SimpleBookmark.getBookmark(pdfReader), n); int fileNum = 0; LOG.info("Found " + n + " pages in input pdf document."); Integer[] limits = inputCommand.getSplitPageNumbers(); // limits list validation end clean TreeSet limitsList = validateSplitLimits(limits, n); if (limitsList.isEmpty()) { throw new SplitException(SplitException.ERR_NO_PAGE_LIMITS); } // HERE I'M SURE I'VE A LIMIT LIST WITH VALUES, I CAN START BOOKMARKS int currentPage; Document currentDocument = new Document(pdfReader.getPageSizeWithRotation(1)); int relativeCurrentPage = 0; int endPage = n; int startPage = 1; PdfImportedPage importedPage; File tmpFile = null; File outFile = null; Iterator itr = limitsList.iterator(); if (itr.hasNext()) { endPage = ((Integer) itr.next()).intValue(); } for (currentPage = 1; currentPage <= n; currentPage++) { relativeCurrentPage++; // check if i've to read one more page or to open a new doc if (relativeCurrentPage == 1) { LOG.debug("Creating a new document."); fileNum++; tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile()); String bookmark = null; if (bookmarksTable != null && bookmarksTable.size() > 0) { bookmark = (String) bookmarksTable.get(new Integer(currentPage)); } FileNameRequest request = new FileNameRequest(currentPage, fileNum, bookmark); outFile = new File(inputCommand.getOutputFile(), prefixParser.generateFileName(request)); startPage = currentPage; currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage)); pdfWriter = new PdfSmartCopy(currentDocument, new FileOutputStream(tmpFile)); // set creator currentDocument.addCreator(ConsoleServicesFacade.CREATOR); setCompressionSettingOnWriter(inputCommand, pdfWriter); setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion())); currentDocument.open(); } importedPage = pdfWriter.getImportedPage(pdfReader, currentPage); pdfWriter.addPage(importedPage); // if it's time to close the document if (currentPage == endPage) { LOG.info("Temporary document " + tmpFile.getName() + " done, now adding bookmarks..."); // manage bookmarks List bookmarks = bookmarkProcessor.processBookmarks(startPage, endPage); if (bookmarks != null) { pdfWriter.setOutlines(bookmarks); } relativeCurrentPage = 0; currentDocument.close(); FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite()); LOG.debug("File " + outFile.getCanonicalPath() + " created."); endPage = (itr.hasNext()) ? ((Integer) itr.next()).intValue() : n; } setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n); } pdfReader.close(); LOG.info("Split " + inputCommand.getSplitType() + " done."); }
From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.java
/** * Gracefully convert given Object to given class given the precondition * that both are primitives or one of the classes associated with * primitives. eg. If val is of type Double and cls is of type int, return * Integer type with appropriate value truncation so that it can be assigned * to field with field.set()./*from w w w . j av a2 s .c om*/ * * @param cls * @param val * @return * @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException */ private static Object convertToPrimitiveFieldObj(Object val, Class<?> cls) { Class<?> valClass = val.getClass(); Object result = null; try { Method getter = null; if (cls.isAssignableFrom(Byte.class) || cls.isAssignableFrom(Byte.TYPE)) { getter = valClass.getMethod("byteValue"); } else if (cls.isAssignableFrom(Short.class) || cls.isAssignableFrom(Short.TYPE)) { getter = valClass.getMethod("shortValue"); } else if (cls.isAssignableFrom(Integer.class) || cls.isAssignableFrom(Integer.TYPE)) { getter = valClass.getMethod("intValue"); } else if (cls.isAssignableFrom(Long.class) || cls.isAssignableFrom(Long.TYPE)) { getter = valClass.getMethod("longValue"); } else if (cls.isAssignableFrom(Float.class) || cls.isAssignableFrom(Float.TYPE)) { getter = valClass.getMethod("floatValue"); } else if (cls.isAssignableFrom(Double.class) || cls.isAssignableFrom(Double.TYPE)) { getter = valClass.getMethod("doubleValue"); } else if (cls.isAssignableFrom(Boolean.class) || cls.isAssignableFrom(Boolean.TYPE)) { if (val instanceof Boolean) { result = val; } else { throw new TypeMismatchException(cls, val.getClass()); } } else if (cls.isAssignableFrom(Character.class) || cls.isAssignableFrom(Character.TYPE)) { if (val instanceof String && ((String) val).length() == 1) { char c = ((String) val).charAt(0); result = Character.valueOf(c); } else if (val instanceof String) { throw new TypeMismatchException( "Expected Character, " + "but received String with length other than 1."); } else { throw new TypeMismatchException( String.format("Expected Character, accept String, but got %s.", val.getClass())); } } if (getter != null) { result = getter.invoke(val); } } catch (NoSuchMethodException e) { throw new TypeMismatchException(String.format("Cannot convert %s to %s.", val.getClass(), cls)); } catch (SecurityException e) { throw new TypeMismatchException(String.format("Cannot convert %s to %s.", val.getClass(), cls)); } catch (IllegalAccessException e) { throw new TypeMismatchException(String.format("Cannot convert %s to %s.", val.getClass(), cls)); } catch (InvocationTargetException e) { throw new TypeMismatchException(String.format("Cannot convert %s to %s.", val.getClass(), cls)); } return result; }
From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private static <T> T produceBean(Class<T> clazz, ControlParam countrolParam, Stack<Class> parseClassList) { try {//from w ww.j a va2s .c o m T item = clazz.newInstance(); for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(clazz)) { Method writeMethod = pd.getWriteMethod(); if (writeMethod == null || pd.getReadMethod() == null || // countrolParam.getExcludeFieldList() != null && countrolParam.getExcludeFieldList().contains(pd.getName())// ) {// continue; } Class fieldClazz = pd.getPropertyType(); Long numIndex = countrolParam.getNumIndex(); // int enumIndex = countrolParam.getEnumIndex(); Random random = countrolParam.getRandom(); long strIndex = countrolParam.getStrIndex(); int charIndex = countrolParam.getCharIndex(); Calendar time = countrolParam.getTime(); if (TypeUtil.isBaseType(fieldClazz)) { if (TypeUtil.isNumberType(fieldClazz)) { if (fieldClazz == Byte.class) { writeMethod.invoke(item, Byte.valueOf((byte) (numIndex & 0x7F))); } else if (fieldClazz == Short.class) { writeMethod.invoke(item, Short.valueOf((short) (numIndex & 0x7FFF))); } else if (fieldClazz == Integer.class) { writeMethod.invoke(item, Integer.valueOf((int) (numIndex & 0x7FFFFFFF))); } else if (fieldClazz == Long.class) { writeMethod.invoke(item, Long.valueOf((long) numIndex)); } else if (fieldClazz == Float.class) { writeMethod.invoke(item, Float.valueOf((float) numIndex)); } else if (fieldClazz == Double.class) { writeMethod.invoke(item, Double.valueOf((double) numIndex)); } else if (fieldClazz == byte.class) {// writeMethod.invoke(item, (byte) (numIndex & 0x7F)); } else if (fieldClazz == short.class) { writeMethod.invoke(item, (short) (numIndex & 0x7FFF)); } else if (fieldClazz == int.class) { writeMethod.invoke(item, (int) (numIndex & 0x7FFFFFFF)); } else if (fieldClazz == long.class) { writeMethod.invoke(item, (long) numIndex); } else if (fieldClazz == float.class) { writeMethod.invoke(item, (float) numIndex); } else if (fieldClazz == double.class) { writeMethod.invoke(item, (double) numIndex); } numIndex++; if (numIndex < 0) { numIndex &= 0x7FFFFFFFFFFFFFFFL; } countrolParam.setNumIndex(numIndex); } else if (fieldClazz == boolean.class) { writeMethod.invoke(item, random.nextBoolean()); } else if (fieldClazz == Boolean.class) { writeMethod.invoke(item, Boolean.valueOf(random.nextBoolean())); } else if (fieldClazz == char.class) { writeMethod.invoke(item, CHAR_RANGE[charIndex]); charIndex++; if (charIndex >= CHAR_RANGE.length) { charIndex = 0; } countrolParam.setCharIndex(charIndex); } else if (fieldClazz == Character.class) { writeMethod.invoke(item, Character.valueOf(CHAR_RANGE[charIndex])); charIndex++; if (charIndex >= CHAR_RANGE.length) { charIndex = 0; } countrolParam.setCharIndex(charIndex); } else if (fieldClazz == String.class) { if (countrolParam.getUniqueFieldList() != null && countrolParam.getUniqueFieldList().contains(pd.getName())) { StringBuilder sb = new StringBuilder(); convertNum(strIndex, STRING_RANGE, countrolParam.getRandom(), sb); writeMethod.invoke(item, sb.toString()); strIndex += countrolParam.getStrStep(); if (strIndex < 0) { strIndex &= 0x7FFFFFFFFFFFFFFFL; } countrolParam.setStrIndex(strIndex); } else { writeMethod.invoke(item, String.valueOf(CHAR_RANGE[charIndex])); charIndex++; if (charIndex >= CHAR_RANGE.length) { charIndex = 0; } countrolParam.setCharIndex(charIndex); } } else if (fieldClazz == Date.class) { writeMethod.invoke(item, time.getTime()); time.add(Calendar.DAY_OF_YEAR, 1); } else if (fieldClazz.isEnum()) { int index = random.nextInt(fieldClazz.getEnumConstants().length); writeMethod.invoke(item, fieldClazz.getEnumConstants()[index]); } else { // throw new RuntimeException("out of countrol Class " + fieldClazz.getName()); } } else { parseClassList.push(fieldClazz); // TODO ? Set<Class> set = new HashSet<Class>(parseClassList); if (parseClassList.size() - set.size() <= countrolParam.getRecursiveCycleLimit()) { Object bean = produceBean(fieldClazz, countrolParam, parseClassList); writeMethod.invoke(item, bean); } parseClassList.pop(); } } return item; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.github.gerbsen.math.Frequency.java
/** * Returns the cumulative percentage of values less than or equal to v * (as a proportion between 0 and 1)./* ww w . j av a 2s . com*/ * <p> * Returns 0 if v is not comparable to the values set.</p> * * @param v the value to lookup * @return the proportion of values less than or equal to v */ public double getCumPct(char v) { return getCumPct(Character.valueOf(v)); }
From source file:com.softwarementors.extjs.djn.router.processor.standard.json.JsonRequestProcessor.java
private @CheckForNull Object jsonToJavaObject(JsonElement jsonValue, Class<?> parameterType, Type gsonType) { Object value;//from w w w .java 2s .c o m if (jsonValue.isJsonNull()) { return null; } // Handle string in a special way, due to possibility of having a Java char type in the Java // side if (isString(jsonValue)) { if (parameterType.equals(String.class)) { value = jsonValue.getAsString(); return value; } if (parameterType.equals(char.class) || parameterType.equals(Character.class)) { value = Character.valueOf(jsonValue.getAsString().charAt(0)); return value; } } // If Java parameter is Object, we perform 'magic': json string, number, boolean and // null are converted to Java String, Double, Boolean and null. For json objects, // we create a Map<String,Object>, and for json arrays an Object[], and then perform // internal object conversion recursively using the same technique if (parameterType.equals(Object.class) && SUPPORTS_OBJECT_TYPE_PARAMETER) { value = toSimpleJavaType(jsonValue); return value; } // If the Java parameter is an array, but we are receiving a single item, we try to convert // the item to a single item array so that the Java method can digest it boolean useCustomGsonType = gsonType != null; boolean fakeJsonArrayForManyValuedClasses = JsonDeserializationManager.isManyValuedClass(parameterType) && !jsonValue.isJsonArray(); Type typeToInstantiate = parameterType; if (useCustomGsonType) { typeToInstantiate = gsonType; } JsonElement json = jsonValue; if (fakeJsonArrayForManyValuedClasses) { JsonArray fakeJson = new JsonArray(); fakeJson.add(jsonValue); json = fakeJson; } value = getGson().fromJson(json, typeToInstantiate); return value; }