List of usage examples for java.lang Byte parseByte
public static byte parseByte(String s) throws NumberFormatException
From source file:net.sf.l2j.gameserver.instancemanager.DimensionalRiftManager.java
public void loadSpawns() { int countGood = 0, countBad = 0; try {//from w ww .j a v a2 s. co m DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); File file = new File(Config.DATAPACK_ROOT + "/data/dimensionalRift.xml"); if (!file.exists()) throw new IOException(); Document doc = factory.newDocumentBuilder().parse(file); NamedNodeMap attrs; byte type, roomId; int mobId, x, y, z, delay, count; L2Spawn spawnDat; L2NpcTemplate template; for (Node rift = doc.getFirstChild(); rift != null; rift = rift.getNextSibling()) { if ("rift".equalsIgnoreCase(rift.getNodeName())) { for (Node area = rift.getFirstChild(); area != null; area = area.getNextSibling()) { if ("area".equalsIgnoreCase(area.getNodeName())) { attrs = area.getAttributes(); type = Byte.parseByte(attrs.getNamedItem("type").getNodeValue()); for (Node room = area.getFirstChild(); room != null; room = room.getNextSibling()) { if ("room".equalsIgnoreCase(room.getNodeName())) { attrs = room.getAttributes(); roomId = Byte.parseByte(attrs.getNamedItem("id").getNodeValue()); for (Node spawn = room.getFirstChild(); spawn != null; spawn = spawn .getNextSibling()) { if ("spawn".equalsIgnoreCase(spawn.getNodeName())) { attrs = spawn.getAttributes(); mobId = Integer.parseInt(attrs.getNamedItem("mobId").getNodeValue()); delay = Integer.parseInt(attrs.getNamedItem("delay").getNodeValue()); count = Integer.parseInt(attrs.getNamedItem("count").getNodeValue()); template = NpcTable.getInstance().getTemplate(mobId); if (template == null) _log.warn("Template " + mobId + " not found!"); if (!_rooms.containsKey(type)) _log.warn("Type " + type + " not found!"); else if (!_rooms.get(type).containsKey(roomId)) _log.warn("Room " + roomId + " in Type " + type + " not found!"); for (int i = 0; i < count; i++) { DimensionalRiftRoom riftRoom = _rooms.get(type).get(roomId); x = riftRoom.getRandomX(); y = riftRoom.getRandomY(); z = riftRoom.getTeleportCoords()[2]; if (template != null && _rooms.containsKey(type) && _rooms.get(type).containsKey(roomId)) { spawnDat = new L2Spawn(template); spawnDat.setAmount(1); spawnDat.setLocx(x); spawnDat.setLocy(y); spawnDat.setLocz(z); spawnDat.setHeading(-1); spawnDat.setRespawnDelay(delay); SpawnTable.getInstance().addNewSpawn(spawnDat, false); _rooms.get(type).get(roomId).getSpawns().add(spawnDat); countGood++; } else { countBad++; } } } } } } } } } } } catch (Exception e) { _log.warn("Error on loading dimensional rift spawns: " + e); e.printStackTrace(); } _log.info("DimensionalRiftManager: Loaded " + countGood + " dimensional rift spawns, " + countBad + " errors."); }
From source file:com.youTransactor.uCube.Tools.java
/** * this function is to convert the Version from string od decimal in format (xxx.xxx.xxx.xxx) to byteArray * with the length 4 bytes every byte has a value in hexadecimal in format(AB), The maximum value is (FF)=255 * and minimum (00)=0.//from www . j a v a 2 s. com * @param version : the String of version * @return Byte[] of the version * example : (1.10.100.10) => {1,A,64,A} */ public static byte[] stringDecimalVersionToHexByteArray(String version) { byte versionByteArray[] = new byte[SVPP_VERSION_LEN]; // look up until dot (.) // then put it into byte array int offset = 0; int i; int index; String hexStringTemp; String intStringTemp; // Check string length 0.0.0.0 => 255.255.255.255 // Count the number of dots for (i = 0; i < versionByteArray.length; i++) { index = version.indexOf(".", offset); // If dot is not found that means we inspect the last element (xxx) if (index != -1) { intStringTemp = version.substring(offset, index); offset = index + 1; } else { intStringTemp = version.substring(offset); } hexStringTemp = Integer.toHexString(Integer.parseInt(intStringTemp, 16)); versionByteArray[i] = Byte.parseByte(hexStringTemp); } return versionByteArray; }
From source file:com.itemanalysis.psychometrics.irt.estimation.ItemResponseFileSummary.java
/** * Summarize comma delimited file. It will extract the data beginning in the column indicated by start * and it will continue for nItems columns. * * @param f file to summarize//from ww w. j av a2 s . c o m * @param start the column index of the first item. It is zero based. If teh data start in the first column, then start=0. * @param nItems number of items to read from the file. It will begin at the column indicated by start. * @param headerIncluded true if header is included. False otherwise. The header will be omitted. * @return an array of item resposne vectors */ public ItemResponseVector[] getCondensedResponseVectors(File f, int start, int nItems, boolean headerIncluded) { Frequency freq = new Frequency(); String responseString = ""; try { BufferedReader br = new BufferedReader(new FileReader(f)); String line = ""; String[] s = null; if (headerIncluded) br.readLine();//skip header while ((line = br.readLine()) != null) { s = line.split(","); line = ""; for (int j = 0; j < nItems; j++) { line += s[j + start]; } freq.addValue(line); } br.close(); } catch (IOException ex) { ex.printStackTrace(); } ItemResponseVector[] responseData = new ItemResponseVector[freq.getUniqueCount()]; ItemResponseVector irv = null; Iterator<Comparable<?>> iter = freq.valuesIterator(); int index = 0; byte[] rv = null; //create array of ItemResponseVector objects while (iter.hasNext()) { Comparable<?> value = iter.next(); responseString = value.toString(); int n = responseString.length(); rv = new byte[n]; String response = ""; for (int i = 0; i < n; i++) { response = String.valueOf(responseString.charAt(i)).toString(); rv[i] = Byte.parseByte(response); } //create response vector objects irv = new ItemResponseVector(rv, Long.valueOf(freq.getCount(value)).doubleValue()); responseData[index] = irv; index++; } return responseData; }
From source file:com.jeans.iservlet.controller.impl.AssetsController.java
private Map<String, Object> parseFilters(String filters) { Map<String, Object> ret = new HashMap<String, Object>(); String[] fs = filters.split("&"); Set<String> vendors = new HashSet<String>(); String[] vs = fs[0].split(","); for (String v : vs) { if (!StringUtils.isBlank(v)) { vendors.add(v);//from ww w . j a v a 2s . c o m } } ret.put("vendor", vendors); Calendar start = Calendar.getInstance(); try { start.set(Calendar.YEAR, Integer.parseInt(fs[1])); start.set(Calendar.MONTH, Calendar.JANUARY); start.set(Calendar.DATE, 1); start.set(Calendar.HOUR_OF_DAY, 0); start.set(Calendar.MINUTE, 0); start.set(Calendar.SECOND, 0); start.set(Calendar.MILLISECOND, 0); ret.put("purchaseTimeStart", start.getTime()); } catch (Exception e) { ret.put("purchaseTimeStart", null); } Calendar end = Calendar.getInstance(); try { end.set(Calendar.YEAR, Integer.parseInt(fs[2])); end.set(Calendar.MONTH, Calendar.DECEMBER); end.set(Calendar.DATE, 31); end.set(Calendar.HOUR_OF_DAY, 23); end.set(Calendar.MINUTE, 59); end.set(Calendar.SECOND, 59); end.set(Calendar.MILLISECOND, 999); ret.put("purchaseTimeEnd", end.getTime()); } catch (Exception e) { ret.put("purchaseTimeEnd", null); } try { ret.put("state", Byte.parseByte(fs[3])); } catch (Exception e) { ret.put("state", (byte) 9); } if (fs.length == 6) { // : warranty, importance try { ret.put("warranty", Byte.parseByte(fs[5])); } catch (Exception e) { ret.put("warranty", (byte) 9); } try { ret.put("importance", Byte.parseByte(fs[6])); } catch (Exception e) { ret.put("importance", (byte) 9); } } else if (fs.length == 5) { // : softwareType try { ret.put("softwareType", Byte.parseByte(fs[4])); } catch (Exception e) { ret.put("softwareType", (byte) 9); } } return ret; }
From source file:org.wso2.carbon.datasource.core.utils.RDBMSDataSourceUtils.java
private static Object convertStringToGivenType(Object value, Class<?> type) throws DataSourceException { if (String.class.equals(type) || Properties.class.equals(type)) { return value; }/* ww w . j a v a 2 s . co m*/ if (boolean.class.equals(type) || Boolean.class.equals(type)) { return Boolean.parseBoolean(String.valueOf(value)); } if (int.class.equals(type) || Integer.class.equals(type)) { return Integer.parseInt(String.valueOf(value)); } if (short.class.equals(type) || Short.class.equals(type)) { return Short.parseShort(String.valueOf(value)); } if (byte.class.equals(type) || Byte.class.equals(type)) { return Byte.parseByte(String.valueOf(value)); } if (long.class.equals(type) || Long.class.equals(type)) { return Long.parseLong(String.valueOf(value)); } if (float.class.equals(type) || Float.class.equals(type)) { return Float.parseFloat(String.valueOf(value)); } if (double.class.equals(type) || Double.class.equals(type)) { return Double.parseDouble(String.valueOf(value)); } throw new DataSourceException("Cannot convert value: '" + value + "' to type: '" + type.getName() + "'"); }
From source file:org.apache.tajo.plan.function.stream.TextFieldSerializerDeserializer.java
@Override public Datum deserialize(ByteBuf buf, TajoDataTypes.DataType dataType, ByteBuf nullChars) throws IOException { Datum datum;/*from ww w. j a v a 2 s . c om*/ TajoDataTypes.Type type = dataType.getType(); boolean nullField; if (type == TajoDataTypes.Type.TEXT || type == TajoDataTypes.Type.CHAR) { nullField = isNullText(buf, nullChars); } else { nullField = isNull(buf, nullChars); } if (nullField) { datum = NullDatum.get(); } else { switch (type) { case BOOLEAN: byte bool = buf.readByte(); datum = DatumFactory.createBool(bool == 't' || bool == 'T'); break; case BIT: datum = DatumFactory.createBit(Byte.parseByte( decoder.decode(buf.nioBuffer(buf.readerIndex(), buf.readableBytes())).toString())); break; case CHAR: datum = DatumFactory.createChar( decoder.decode(buf.nioBuffer(buf.readerIndex(), buf.readableBytes())).toString().trim()); break; case INT1: case INT2: datum = DatumFactory.createInt2((short) NumberUtil.parseInt(buf)); break; case INT4: datum = DatumFactory.createInt4(NumberUtil.parseInt(buf)); break; case INT8: datum = DatumFactory.createInt8(NumberUtil.parseLong(buf)); break; case FLOAT4: datum = DatumFactory.createFloat4( decoder.decode(buf.nioBuffer(buf.readerIndex(), buf.readableBytes())).toString()); break; case FLOAT8: datum = DatumFactory.createFloat8(NumberUtil.parseDouble(buf)); break; case TEXT: { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); datum = DatumFactory.createText(bytes); break; } case DATE: datum = DatumFactory.createDate( decoder.decode(buf.nioBuffer(buf.readerIndex(), buf.readableBytes())).toString()); break; case TIME: datum = DatumFactory.createTime( decoder.decode(buf.nioBuffer(buf.readerIndex(), buf.readableBytes())).toString()); break; case TIMESTAMP: // table timezone to UTC datum = DatumFactory.createTimestamp( decoder.decode(buf.nioBuffer(buf.readerIndex(), buf.readableBytes())).toString(), tableTimezone); break; case INTERVAL: datum = DatumFactory.createInterval( decoder.decode(buf.nioBuffer(buf.readerIndex(), buf.readableBytes())).toString()); break; case PROTOBUF: { ProtobufDatumFactory factory = ProtobufDatumFactory.get(dataType); Message.Builder builder = factory.newBuilder(); try { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); protobufJsonFormat.merge(bytes, builder); datum = ProtobufDatumFactory.createDatum(builder.build()); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } break; } case BLOB: { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); datum = DatumFactory.createBlob(Base64.decodeBase64(bytes)); break; } default: datum = NullDatum.get(); break; } } return datum; }
From source file:org.apache.tajo.storage.text.TextFieldSerializerDeserializer.java
@Override public Datum deserialize(int columnIndex, ByteBuf buf, ByteBuf nullChars) throws IOException { Datum datum;//from w w w. j a v a 2 s.c o m Column col = schema.getColumn(columnIndex); TajoDataTypes.Type type = col.getDataType().getType(); boolean nullField; if (type == TajoDataTypes.Type.TEXT || type == TajoDataTypes.Type.CHAR) { nullField = isNullText(buf, nullChars); } else { nullField = isNull(buf, nullChars); } if (nullField) { datum = NullDatum.get(); } else { switch (type) { case BOOLEAN: byte bool = buf.readByte(); datum = DatumFactory.createBool(bool == 't' || bool == 'T'); break; case BIT: datum = DatumFactory.createBit(Byte.parseByte( decoder.decode(buf.nioBuffer(buf.readerIndex(), buf.readableBytes())).toString())); break; case CHAR: datum = DatumFactory.createChar( decoder.decode(buf.nioBuffer(buf.readerIndex(), buf.readableBytes())).toString().trim()); break; case INT1: case INT2: datum = DatumFactory.createInt2((short) NumberUtil.parseInt(buf)); break; case INT4: datum = DatumFactory.createInt4(NumberUtil.parseInt(buf)); break; case INT8: datum = DatumFactory.createInt8(NumberUtil.parseLong(buf)); break; case FLOAT4: datum = DatumFactory.createFloat4( decoder.decode(buf.nioBuffer(buf.readerIndex(), buf.readableBytes())).toString()); break; case FLOAT8: datum = DatumFactory.createFloat8(NumberUtil.parseDouble(buf)); break; case TEXT: { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); datum = DatumFactory.createText(bytes); break; } case DATE: datum = DatumFactory.createDate( decoder.decode(buf.nioBuffer(buf.readerIndex(), buf.readableBytes())).toString()); break; case TIME: datum = DatumFactory.createTime( decoder.decode(buf.nioBuffer(buf.readerIndex(), buf.readableBytes())).toString()); break; case TIMESTAMP: // Convert to UTC by table timezone datum = DatumFactory.createTimestamp( decoder.decode(buf.nioBuffer(buf.readerIndex(), buf.readableBytes())).toString(), tableTimezone); break; case INTERVAL: datum = DatumFactory.createInterval( decoder.decode(buf.nioBuffer(buf.readerIndex(), buf.readableBytes())).toString()); break; case PROTOBUF: { ProtobufDatumFactory factory = ProtobufDatumFactory.get(col.getDataType()); Message.Builder builder = factory.newBuilder(); try { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); protobufJsonFormat.merge(bytes, builder); datum = ProtobufDatumFactory.createDatum(builder.build()); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } break; } case BLOB: { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); datum = DatumFactory.createBlob(Base64.decodeBase64(bytes)); break; } default: datum = NullDatum.get(); break; } } return datum; }
From source file:com.msopentech.odatajclient.engine.data.ODataPrimitiveValue.java
/** * Parses given text as object value./*from w ww . j a v a2s .c om*/ */ private void parseText() { switch (this.type) { case Null: this.value = null; break; case Binary: this.value = Base64.decodeBase64(this.toString()); break; case SByte: this.value = Byte.parseByte(this.toString()); break; case Boolean: this.value = Boolean.parseBoolean(this.toString()); break; case Date: case DateTime: case DateTimeOffset: this.value = ODataTimestamp.parse(this.type, this.toString()); break; case Time: case TimeOfDay: this.value = new ODataDuration(this.toString()); break; case Decimal: this.value = new BigDecimal(this.toString()); break; case Single: this.value = Float.parseFloat(this.toString()); break; case Double: this.value = Double.parseDouble(this.toString()); break; case Guid: this.value = UUID.fromString(this.toString()); break; case Int16: this.value = Short.parseShort(this.toString()); break; case Byte: case Int32: this.value = Integer.parseInt(this.toString()); break; case Int64: this.value = Long.parseLong(this.toString()); break; case Stream: this.value = URI.create(this.toString()); break; case String: this.value = this.toString(); break; default: } }
From source file:de.inpiraten.jdemocrator.TAN.generator.TANGenerator.java
private byte inputOption() throws NumberFormatException, IOException { String inputString = commandLineInput.readLine(); // System.out.println("DEBUG: Read the following line: "+inputString); if (inputString.equals("")) return 0; else//from ww w .ja va2 s . c o m return Byte.parseByte(inputString); }
From source file:org.pentaho.platform.engine.services.connection.datasource.dbcp.PooledDatasourceHelper.java
public static PoolingDataSource setupPooledDataSource(IDatabaseConnection databaseConnection) throws DBDatasourceServiceException { PoolingDataSource poolingDataSource = null; String driverClass = null;/*from ww w . ja v a2s .com*/ String url = null; try { if (databaseConnection.getAccessType().equals(DatabaseAccessType.JNDI)) { throw new DBDatasourceServiceException(Messages.getInstance().getErrorString( "PooledDatasourceHelper.ERROR_0008_UNABLE_TO_POOL_DATASOURCE_IT_IS_JNDI", databaseConnection.getName())); } ICacheManager cacheManager = PentahoSystem.getCacheManager(null); IDatabaseDialectService databaseDialectService = PentahoSystem.get(IDatabaseDialectService.class); if (databaseDialectService == null) { throw new DBDatasourceServiceException(Messages.getInstance().getErrorString( "PooledDatasourceHelper.ERROR_0005_UNABLE_TO_POOL_DATASOURCE_NO_DIALECT_SERVICE", databaseConnection.getName())); } IDatabaseDialect dialect = databaseDialectService.getDialect(databaseConnection); if (dialect == null || dialect.getDatabaseType() == null) { throw new DBDatasourceServiceException(Messages.getInstance().getErrorString( "PooledDatasourceHelper.ERROR_0004_UNABLE_TO_POOL_DATASOURCE_NO_DIALECT", databaseConnection.getName())); } if (databaseConnection.getDatabaseType().getShortName().equals("GENERIC")) { //$NON-NLS-1$ driverClass = databaseConnection.getAttributes() .get(GenericDatabaseDialect.ATTRIBUTE_CUSTOM_DRIVER_CLASS); if (StringUtils.isEmpty(driverClass)) { throw new DBDatasourceServiceException(Messages.getInstance().getErrorString( "PooledDatasourceHelper.ERROR_0006_UNABLE_TO_POOL_DATASOURCE_NO_CLASSNAME", databaseConnection.getName())); } } else { driverClass = dialect.getNativeDriver(); if (StringUtils.isEmpty(driverClass)) { throw new DBDatasourceServiceException(Messages.getInstance().getErrorString( "PooledDatasourceHelper.ERROR_0007_UNABLE_TO_POOL_DATASOURCE_NO_DRIVER", databaseConnection.getName())); } } try { url = dialect.getURLWithExtraOptions(databaseConnection); } catch (DatabaseDialectException e) { url = null; } // Read default connection pooling parameter String maxdleConn = PentahoSystem.getSystemSetting("dbcp-defaults/max-idle-conn", null); //$NON-NLS-1$ String minIdleConn = PentahoSystem.getSystemSetting("dbcp-defaults/min-idle-conn", null); //$NON-NLS-1$ String maxActConn = PentahoSystem.getSystemSetting("dbcp-defaults/max-act-conn", null); //$NON-NLS-1$ String validQuery = null; String whenExhaustedAction = PentahoSystem.getSystemSetting("dbcp-defaults/when-exhausted-action", //$NON-NLS-1$ null); String wait = PentahoSystem.getSystemSetting("dbcp-defaults/wait", null); //$NON-NLS-1$ String testWhileIdleValue = PentahoSystem.getSystemSetting("dbcp-defaults/test-while-idle", null); //$NON-NLS-1$ String testOnBorrowValue = PentahoSystem.getSystemSetting("dbcp-defaults/test-on-borrow", null); //$NON-NLS-1$ String testOnReturnValue = PentahoSystem.getSystemSetting("dbcp-defaults/test-on-return", null); //$NON-NLS-1$ // property initialization boolean testWhileIdle = !StringUtil.isEmpty(testWhileIdleValue) ? Boolean.parseBoolean(testWhileIdleValue) : false; boolean testOnBorrow = !StringUtil.isEmpty(testOnBorrowValue) ? Boolean.parseBoolean(testOnBorrowValue) : false; boolean testOnReturn = !StringUtil.isEmpty(testOnReturnValue) ? Boolean.parseBoolean(testOnReturnValue) : false; int maxActiveConnection = !StringUtil.isEmpty(maxActConn) ? Integer.parseInt(maxActConn) : -1; long waitTime = !StringUtil.isEmpty(wait) ? Integer.parseInt(wait) : -1; byte whenExhaustedActionType = !StringUtil.isEmpty(whenExhaustedAction) ? Byte.parseByte(whenExhaustedAction) : GenericObjectPool.WHEN_EXHAUSTED_BLOCK; int minIdleConnection = !StringUtil.isEmpty(minIdleConn) ? Integer.parseInt(minIdleConn) : -1; int maxIdleConnection = !StringUtil.isEmpty(maxdleConn) ? Integer.parseInt(maxdleConn) : -1; // setting properties according to user specifications Map<String, String> attributes = databaseConnection.getConnectionPoolingProperties(); if (attributes.containsKey(IDBDatasourceService.MAX_ACTIVE_KEY) && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MAX_ACTIVE_KEY))) { maxActiveConnection = Integer.parseInt(attributes.get(IDBDatasourceService.MAX_ACTIVE_KEY)); } if (attributes.containsKey(IDBDatasourceService.MAX_WAIT_KEY) && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MAX_WAIT_KEY))) { waitTime = Integer.parseInt(attributes.get(IDBDatasourceService.MAX_WAIT_KEY)); } if (attributes.containsKey(IDBDatasourceService.MIN_IDLE_KEY) && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MIN_IDLE_KEY))) { minIdleConnection = Integer.parseInt(attributes.get(IDBDatasourceService.MIN_IDLE_KEY)); } if (attributes.containsKey(IDBDatasourceService.MAX_IDLE_KEY) && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MAX_IDLE_KEY))) { maxIdleConnection = Integer.parseInt(attributes.get(IDBDatasourceService.MAX_IDLE_KEY)); } if (attributes.containsKey(IDBDatasourceService.QUERY_KEY)) { validQuery = attributes.get(IDBDatasourceService.QUERY_KEY); } if (attributes.containsKey(IDBDatasourceService.TEST_ON_BORROW)) { testOnBorrow = Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_ON_BORROW)); } if (attributes.containsKey(IDBDatasourceService.TEST_ON_RETURN)) { testOnReturn = Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_ON_RETURN)); } if (attributes.containsKey(IDBDatasourceService.TEST_WHILE_IDLE)) { testWhileIdle = Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_WHILE_IDLE)); } poolingDataSource = new PoolingDataSource(); Class.forName(driverClass); // As the name says, this is a generic pool; it returns basic Object-class objects. GenericObjectPool pool = new GenericObjectPool(null); // if removedAbandoned = true, then an AbandonedObjectPool object will take GenericObjectPool's place if (attributes.containsKey(IDBDatasourceService.REMOVE_ABANDONED) && true == Boolean.parseBoolean(attributes.get(IDBDatasourceService.REMOVE_ABANDONED))) { AbandonedConfig config = new AbandonedConfig(); config.setRemoveAbandoned( Boolean.parseBoolean(attributes.get(IDBDatasourceService.REMOVE_ABANDONED))); if (attributes.containsKey(IDBDatasourceService.LOG_ABANDONED)) { config.setLogAbandoned( Boolean.parseBoolean(attributes.get(IDBDatasourceService.LOG_ABANDONED))); } if (attributes.containsKey(IDBDatasourceService.REMOVE_ABANDONED_TIMEOUT) && NumberUtils.isNumber(attributes.get(IDBDatasourceService.REMOVE_ABANDONED_TIMEOUT))) { config.setRemoveAbandonedTimeout( Integer.parseInt(attributes.get(IDBDatasourceService.REMOVE_ABANDONED_TIMEOUT))); } pool = new AbandonedObjectPool(null, config); } pool.setWhenExhaustedAction(whenExhaustedActionType); // Tuning the connection pool pool.setMaxActive(maxActiveConnection); pool.setMaxIdle(maxIdleConnection); pool.setMaxWait(waitTime); pool.setMinIdle(minIdleConnection); pool.setTestWhileIdle(testWhileIdle); pool.setTestOnReturn(testOnReturn); pool.setTestOnBorrow(testOnBorrow); pool.setTestWhileIdle(testWhileIdle); if (attributes.containsKey(IDBDatasourceService.TIME_BETWEEN_EVICTION_RUNS_MILLIS) && NumberUtils .isNumber(attributes.get(IDBDatasourceService.TIME_BETWEEN_EVICTION_RUNS_MILLIS))) { pool.setTimeBetweenEvictionRunsMillis( Long.parseLong(attributes.get(IDBDatasourceService.TIME_BETWEEN_EVICTION_RUNS_MILLIS))); } /* * ConnectionFactory creates connections on behalf of the pool. Here, we use the DriverManagerConnectionFactory * because that essentially uses DriverManager as the source of connections. */ ConnectionFactory factory = null; if (url.startsWith("jdbc:mysql:")) { Properties props = new Properties(); props.put("user", databaseConnection.getUsername()); props.put("password", databaseConnection.getPassword()); props.put("socketTimeout", "0"); props.put("connectTimeout", "5000"); factory = new DriverManagerConnectionFactory(url, props); } else { factory = new DriverManagerConnectionFactory(url, databaseConnection.getUsername(), databaseConnection.getPassword()); } boolean defaultReadOnly = attributes.containsKey(IDBDatasourceService.DEFAULT_READ_ONLY) ? Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_WHILE_IDLE)) : false; // default to false boolean defaultAutoCommit = attributes.containsKey(IDBDatasourceService.DEFAULT_AUTO_COMMIT) ? Boolean.parseBoolean(attributes.get(IDBDatasourceService.DEFAULT_AUTO_COMMIT)) : true; // default to true KeyedObjectPoolFactory kopf = null; if (attributes.containsKey(IDBDatasourceService.POOL_PREPARED_STATEMENTS) && true == Boolean .parseBoolean(attributes.get(IDBDatasourceService.POOL_PREPARED_STATEMENTS))) { int maxOpenPreparedStatements = -1; // unlimited if (attributes.containsKey(IDBDatasourceService.MAX_OPEN_PREPARED_STATEMENTS) && NumberUtils .isNumber(attributes.get(IDBDatasourceService.MAX_OPEN_PREPARED_STATEMENTS))) { maxOpenPreparedStatements = Integer .parseInt(attributes.get(IDBDatasourceService.MAX_OPEN_PREPARED_STATEMENTS)); } kopf = new GenericKeyedObjectPoolFactory(null, pool.getMaxActive(), pool.getWhenExhaustedAction(), pool.getMaxWait(), pool.getMaxIdle(), maxOpenPreparedStatements); } /* * Puts pool-specific wrappers on factory connections. For clarification: "[PoolableConnection]Factory," not * "Poolable[ConnectionFactory]." */ PoolableConnectionFactory pcf = new PoolableConnectionFactory(factory, // ConnectionFactory pool, // ObjectPool kopf, // KeyedObjectPoolFactory validQuery, // String (validation query) defaultReadOnly, // boolean (default to read-only?) defaultAutoCommit // boolean (default to auto-commit statements?) ); if (attributes.containsKey(IDBDatasourceService.DEFAULT_TRANSACTION_ISOLATION) && !IDBDatasourceService.TRANSACTION_ISOLATION_NONE_VALUE .equalsIgnoreCase(attributes.get(IDBDatasourceService.DEFAULT_TRANSACTION_ISOLATION))) { Isolation isolationLevel = Isolation .valueOf(attributes.get(IDBDatasourceService.DEFAULT_TRANSACTION_ISOLATION)); if (isolationLevel != null) { pcf.setDefaultTransactionIsolation(isolationLevel.value()); } } if (attributes.containsKey(IDBDatasourceService.DEFAULT_CATALOG)) { pcf.setDefaultCatalog(attributes.get(IDBDatasourceService.DEFAULT_CATALOG)); } /* * initialize the pool to X connections */ Logger.debug(PooledDatasourceHelper.class, "Pool defaults to " + maxActiveConnection + " max active/" + maxIdleConnection + "max idle" //$NON-NLS-3$ + "with " + waitTime + "wait time"//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-4$ //$NON-NLS-5$ + " idle connections."); //$NON-NLS-1$ for (int i = 0; i < maxIdleConnection; ++i) { pool.addObject(); } Logger.debug(PooledDatasourceHelper.class, "Pool now has " + pool.getNumActive() + " active/" + pool.getNumIdle() + " idle connections."); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-3$ /* * All of this is wrapped in a DataSource, which client code should already know how to handle (since it's the * same class of object they'd fetch via the container's JNDI tree */ poolingDataSource.setPool(pool); if (attributes.containsKey(IDBDatasourceService.ACCESS_TO_UNDERLYING_CONNECTION_ALLOWED)) { poolingDataSource.setAccessToUnderlyingConnectionAllowed(Boolean.parseBoolean( attributes.get(IDBDatasourceService.ACCESS_TO_UNDERLYING_CONNECTION_ALLOWED))); } // store the pool, so we can get to it later cacheManager.putInRegionCache(IDBDatasourceService.JDBC_POOL, databaseConnection.getName(), pool); return (poolingDataSource); } catch (Exception e) { throw new DBDatasourceServiceException(e); } }