List of usage examples for java.sql Timestamp valueOf
@SuppressWarnings("deprecation") public static Timestamp valueOf(LocalDateTime dateTime)
From source file:org.apache.cocoon.util.JDBCTypeConversions.java
/** * Set the Statement column so that the results are mapped correctly. * * @param statement the prepared statement * @param position the position of the column * @param value the value of the column/*from ww w.ja v a 2s . co m*/ */ public static void setColumn(PreparedStatement statement, int position, Object value, Integer typeObject) throws Exception { if (value instanceof String) { value = ((String) value).trim(); } if (typeObject == null) { throw new SQLException("Can't set column because the type is unrecognized"); } if (value == null) { /** If the value is null, set the column value null and return **/ statement.setNull(position, typeObject.intValue()); return; } if ("".equals(value)) { switch (typeObject.intValue()) { case Types.CHAR: case Types.CLOB: case Types.VARCHAR: /** If the value is an empty string and the column is a string type, we can continue **/ break; default: /** If the value is an empty string and the column is something else, we treat it as a null value **/ statement.setNull(position, typeObject.intValue()); return; } } File file = null; int length = -1; InputStream asciiStream = null; //System.out.println("========================================================================"); //System.out.println("JDBCTypeConversions: setting type "+typeObject.intValue()); switch (typeObject.intValue()) { case Types.CLOB: //System.out.println("CLOB"); Clob clob = null; if (value instanceof Clob) { clob = (Clob) value; } else if (value instanceof File) { File asciiFile = (File) value; asciiStream = new BufferedInputStream(new FileInputStream(asciiFile)); length = (int) asciiFile.length(); clob = new ClobHelper(asciiStream, length); } else if (value instanceof Part) { Part anyFile = (Part) value; asciiStream = new BufferedInputStream(anyFile.getInputStream()); length = anyFile.getSize(); clob = new ClobHelper(asciiStream, length); } else if (value instanceof JDBCxlobHelper) { asciiStream = ((JDBCxlobHelper) value).inputStream; length = ((JDBCxlobHelper) value).length; clob = new ClobHelper(asciiStream, length); } else if (value instanceof Source) { asciiStream = ((Source) value).getInputStream(); length = (int) ((Source) value).getContentLength(); clob = new ClobHelper(asciiStream, length); } else { String asciiText = value.toString(); asciiStream = new ByteArrayInputStream(asciiText.getBytes()); length = asciiText.length(); clob = new ClobHelper(asciiStream, length); } statement.setClob(position, clob); break; case Types.CHAR: // simple large object, e.g. Informix's TEXT //System.out.println("CHAR"); if (value instanceof File) { File asciiFile = (File) value; asciiStream = new BufferedInputStream(new FileInputStream(asciiFile)); length = (int) asciiFile.length(); } else if (value instanceof JDBCxlobHelper) { asciiStream = ((JDBCxlobHelper) value).inputStream; length = ((JDBCxlobHelper) value).length; } else if (value instanceof Source) { asciiStream = ((Source) value).getInputStream(); length = (int) ((Source) value).getContentLength(); } else if (value instanceof Part) { Part anyFile = (Part) value; asciiStream = new BufferedInputStream(anyFile.getInputStream()); length = anyFile.getSize(); clob = new ClobHelper(asciiStream, length); } else { String asciiText = value.toString(); asciiStream = new BufferedInputStream(new ByteArrayInputStream(asciiText.getBytes())); length = asciiText.length(); } statement.setAsciiStream(position, asciiStream, length); break; case Types.BIGINT: //System.out.println("BIGINT"); BigDecimal bd = null; if (value instanceof BigDecimal) { bd = (BigDecimal) value; } else if (value instanceof Number) { bd = BigDecimal.valueOf(((Number) value).longValue()); } else { bd = new BigDecimal(value.toString()); } statement.setBigDecimal(position, bd); break; case Types.TINYINT: //System.out.println("TINYINT"); Byte b = null; if (value instanceof Byte) { b = (Byte) value; } else if (value instanceof Number) { b = new Byte(((Number) value).byteValue()); } else { b = new Byte(value.toString()); } statement.setByte(position, b.byteValue()); break; case Types.DATE: //System.out.println("DATE"); Date d = null; if (value instanceof Date) { d = (Date) value; } else if (value instanceof java.util.Date) { d = new Date(((java.util.Date) value).getTime()); } else if (value instanceof Calendar) { d = new Date(((Calendar) value).getTime().getTime()); } else { d = Date.valueOf(value.toString()); } statement.setDate(position, d); break; case Types.DOUBLE: //System.out.println("DOUBLE"); double db; if (value instanceof Number) { db = (((Number) value).doubleValue()); } else { db = Double.parseDouble(value.toString()); } statement.setDouble(position, db); break; case Types.FLOAT: //System.out.println("FLOAT"); float f; if (value instanceof Number) { f = (((Number) value).floatValue()); } else { f = Float.parseFloat(value.toString()); } statement.setFloat(position, f); break; case Types.NUMERIC: //System.out.println("NUMERIC"); long l; if (value instanceof Number) { l = (((Number) value).longValue()); } else { l = Long.parseLong(value.toString()); } statement.setLong(position, l); break; case Types.SMALLINT: //System.out.println("SMALLINT"); Short s = null; if (value instanceof Short) { s = (Short) value; } else if (value instanceof Number) { s = new Short(((Number) value).shortValue()); } else { s = new Short(value.toString()); } statement.setShort(position, s.shortValue()); break; case Types.TIME: //System.out.println("TIME"); Time t = null; if (value instanceof Time) { t = (Time) value; } else if (value instanceof java.util.Date) { t = new Time(((java.util.Date) value).getTime()); } else { t = Time.valueOf(value.toString()); } statement.setTime(position, t); break; case Types.TIMESTAMP: //System.out.println("TIMESTAMP"); Timestamp ts = null; if (value instanceof Time) { ts = (Timestamp) value; } else if (value instanceof java.util.Date) { ts = new Timestamp(((java.util.Date) value).getTime()); } else { ts = Timestamp.valueOf(value.toString()); } statement.setTimestamp(position, ts); break; case Types.ARRAY: //System.out.println("ARRAY"); statement.setArray(position, (Array) value); // no way to convert string to array break; case Types.STRUCT: //System.out.println("STRUCT"); case Types.OTHER: //System.out.println("OTHER"); statement.setObject(position, value); break; case Types.LONGVARBINARY: //System.out.println("LONGVARBINARY"); statement.setTimestamp(position, new Timestamp((new java.util.Date()).getTime())); break; case Types.VARCHAR: //System.out.println("VARCHAR"); statement.setString(position, value.toString()); break; case Types.BLOB: //System.out.println("BLOB"); if (value instanceof JDBCxlobHelper) { statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream, ((JDBCxlobHelper) value).length); } else if (value instanceof Source) { statement.setBinaryStream(position, ((Source) value).getInputStream(), (int) ((Source) value).getContentLength()); } else { Blob blob = null; if (value instanceof Blob) { blob = (Blob) value; } else if (value instanceof File) { file = (File) value; blob = new BlobHelper(new FileInputStream(file), (int) file.length()); } else if (value instanceof String) { file = new File((String) value); blob = new BlobHelper(new FileInputStream(file), (int) file.length()); } else if (value instanceof Part) { Part anyFile = (Part) value; blob = new BlobHelper(new BufferedInputStream(anyFile.getInputStream()), anyFile.getSize()); } else { throw new SQLException("Invalid type for blob: " + value.getClass().getName()); } //InputStream input = new BufferedInputStream(new FileInputStream(file)); statement.setBlob(position, blob); } break; case Types.VARBINARY: //System.out.println("VARBINARY"); if (value instanceof JDBCxlobHelper) { statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream, ((JDBCxlobHelper) value).length); } else if (value instanceof Source) { statement.setBinaryStream(position, ((Source) value).getInputStream(), (int) ((Source) value).getContentLength()); } else if (value instanceof Part) { statement.setBinaryStream(position, ((Part) value).getInputStream(), ((Part) value).getSize()); } else { if (value instanceof File) { file = (File) value; } else if (value instanceof String) { file = new File((String) value); } else { throw new SQLException("Invalid type for blob: " + value.getClass().getName()); } //InputStream input = new BufferedInputStream(new FileInputStream(file)); FileInputStream input = new FileInputStream(file); statement.setBinaryStream(position, input, (int) file.length()); } break; case Types.INTEGER: //System.out.println("INTEGER"); Integer i = null; if (value instanceof Integer) { i = (Integer) value; } else if (value instanceof Number) { i = new Integer(((Number) value).intValue()); } else { i = new Integer(value.toString()); } statement.setInt(position, i.intValue()); break; case Types.BIT: //System.out.println("BIT"); Boolean bo = null; if (value instanceof Boolean) { bo = (Boolean) value; } else if (value instanceof Number) { bo = BooleanUtils.toBooleanObject(((Number) value).intValue() == 1); } else { bo = BooleanUtils.toBooleanObject(value.toString()); } statement.setBoolean(position, bo.booleanValue()); break; default: //System.out.println("default"); throw new SQLException("Impossible exception - invalid type "); } //System.out.println("========================================================================"); }
From source file:org.apache.hive.jdbc.TestJdbcWithMiniLlap.java
@Test(timeout = 60000) public void testDataTypes() throws Exception { createDataTypesTable("datatypes"); RowCollector2 rowCollector = new RowCollector2(); String query = "select * from datatypes"; int rowCount = processQuery(query, 1, rowCollector); assertEquals(3, rowCount);/*from www. j av a 2 s.co m*/ // Verify schema String[][] colNameTypes = new String[][] { { "datatypes.c1", "int" }, { "datatypes.c2", "boolean" }, { "datatypes.c3", "double" }, { "datatypes.c4", "string" }, { "datatypes.c5", "array<int>" }, { "datatypes.c6", "map<int,string>" }, { "datatypes.c7", "map<string,string>" }, { "datatypes.c8", "struct<r:string,s:int,t:double>" }, { "datatypes.c9", "tinyint" }, { "datatypes.c10", "smallint" }, { "datatypes.c11", "float" }, { "datatypes.c12", "bigint" }, { "datatypes.c13", "array<array<string>>" }, { "datatypes.c14", "map<int,map<int,int>>" }, { "datatypes.c15", "struct<r:int,s:struct<a:int,b:string>>" }, { "datatypes.c16", "array<struct<m:map<string,string>,n:int>>" }, { "datatypes.c17", "timestamp" }, { "datatypes.c18", "decimal(16,7)" }, { "datatypes.c19", "binary" }, { "datatypes.c20", "date" }, { "datatypes.c21", "varchar(20)" }, { "datatypes.c22", "char(15)" }, { "datatypes.c23", "binary" }, }; FieldDesc fieldDesc; assertEquals(23, rowCollector.numColumns); for (int idx = 0; idx < rowCollector.numColumns; ++idx) { fieldDesc = rowCollector.schema.getColumns().get(idx); assertEquals("ColName idx=" + idx, colNameTypes[idx][0], fieldDesc.getName()); assertEquals("ColType idx=" + idx, colNameTypes[idx][1], fieldDesc.getTypeInfo().getTypeName()); } // First row is all nulls Object[] rowValues = rowCollector.rows.get(0); for (int idx = 0; idx < rowCollector.numColumns; ++idx) { assertEquals("idx=" + idx, null, rowValues[idx]); } // Second Row rowValues = rowCollector.rows.get(1); assertEquals(Integer.valueOf(-1), rowValues[0]); assertEquals(Boolean.FALSE, rowValues[1]); assertEquals(Double.valueOf(-1.1d), rowValues[2]); assertEquals("", rowValues[3]); List<?> c5Value = (List<?>) rowValues[4]; assertEquals(0, c5Value.size()); Map<?, ?> c6Value = (Map<?, ?>) rowValues[5]; assertEquals(0, c6Value.size()); Map<?, ?> c7Value = (Map<?, ?>) rowValues[6]; assertEquals(0, c7Value.size()); List<?> c8Value = (List<?>) rowValues[7]; assertEquals(null, c8Value.get(0)); assertEquals(null, c8Value.get(1)); assertEquals(null, c8Value.get(2)); assertEquals(Byte.valueOf((byte) -1), rowValues[8]); assertEquals(Short.valueOf((short) -1), rowValues[9]); assertEquals(Float.valueOf(-1.0f), rowValues[10]); assertEquals(Long.valueOf(-1l), rowValues[11]); List<?> c13Value = (List<?>) rowValues[12]; assertEquals(0, c13Value.size()); Map<?, ?> c14Value = (Map<?, ?>) rowValues[13]; assertEquals(0, c14Value.size()); List<?> c15Value = (List<?>) rowValues[14]; assertEquals(null, c15Value.get(0)); assertEquals(null, c15Value.get(1)); List<?> c16Value = (List<?>) rowValues[15]; assertEquals(0, c16Value.size()); assertEquals(null, rowValues[16]); assertEquals(null, rowValues[17]); assertEquals(null, rowValues[18]); assertEquals(null, rowValues[19]); assertEquals(null, rowValues[20]); assertEquals(null, rowValues[21]); assertEquals(null, rowValues[22]); // Third row rowValues = rowCollector.rows.get(2); assertEquals(Integer.valueOf(1), rowValues[0]); assertEquals(Boolean.TRUE, rowValues[1]); assertEquals(Double.valueOf(1.1d), rowValues[2]); assertEquals("1", rowValues[3]); c5Value = (List<?>) rowValues[4]; assertEquals(2, c5Value.size()); assertEquals(Integer.valueOf(1), c5Value.get(0)); assertEquals(Integer.valueOf(2), c5Value.get(1)); c6Value = (Map<?, ?>) rowValues[5]; assertEquals(2, c6Value.size()); assertEquals("x", c6Value.get(Integer.valueOf(1))); assertEquals("y", c6Value.get(Integer.valueOf(2))); c7Value = (Map<?, ?>) rowValues[6]; assertEquals(1, c7Value.size()); assertEquals("v", c7Value.get("k")); c8Value = (List<?>) rowValues[7]; assertEquals("a", c8Value.get(0)); assertEquals(Integer.valueOf(9), c8Value.get(1)); assertEquals(Double.valueOf(2.2d), c8Value.get(2)); assertEquals(Byte.valueOf((byte) 1), rowValues[8]); assertEquals(Short.valueOf((short) 1), rowValues[9]); assertEquals(Float.valueOf(1.0f), rowValues[10]); assertEquals(Long.valueOf(1l), rowValues[11]); c13Value = (List<?>) rowValues[12]; assertEquals(2, c13Value.size()); List<?> listVal = (List<?>) c13Value.get(0); assertEquals("a", listVal.get(0)); assertEquals("b", listVal.get(1)); listVal = (List<?>) c13Value.get(1); assertEquals("c", listVal.get(0)); assertEquals("d", listVal.get(1)); c14Value = (Map<?, ?>) rowValues[13]; assertEquals(2, c14Value.size()); Map<?, ?> mapVal = (Map<?, ?>) c14Value.get(Integer.valueOf(1)); assertEquals(2, mapVal.size()); assertEquals(Integer.valueOf(12), mapVal.get(Integer.valueOf(11))); assertEquals(Integer.valueOf(14), mapVal.get(Integer.valueOf(13))); mapVal = (Map<?, ?>) c14Value.get(Integer.valueOf(2)); assertEquals(1, mapVal.size()); assertEquals(Integer.valueOf(22), mapVal.get(Integer.valueOf(21))); c15Value = (List<?>) rowValues[14]; assertEquals(Integer.valueOf(1), c15Value.get(0)); listVal = (List<?>) c15Value.get(1); assertEquals(2, listVal.size()); assertEquals(Integer.valueOf(2), listVal.get(0)); assertEquals("x", listVal.get(1)); c16Value = (List<?>) rowValues[15]; assertEquals(2, c16Value.size()); listVal = (List<?>) c16Value.get(0); assertEquals(2, listVal.size()); mapVal = (Map<?, ?>) listVal.get(0); assertEquals(0, mapVal.size()); assertEquals(Integer.valueOf(1), listVal.get(1)); listVal = (List<?>) c16Value.get(1); mapVal = (Map<?, ?>) listVal.get(0); assertEquals(2, mapVal.size()); assertEquals("b", mapVal.get("a")); assertEquals("d", mapVal.get("c")); assertEquals(Integer.valueOf(2), listVal.get(1)); assertEquals(Timestamp.valueOf("2012-04-22 09:00:00.123456789"), rowValues[16]); assertEquals(new BigDecimal("123456789.123456"), rowValues[17]); assertArrayEquals("abcd".getBytes("UTF-8"), (byte[]) rowValues[18]); assertEquals(Date.valueOf("2013-01-01"), rowValues[19]); assertEquals("abc123", rowValues[20]); assertEquals("abc123 ", rowValues[21]); assertArrayEquals("X'01FF'".getBytes("UTF-8"), (byte[]) rowValues[22]); }
From source file:edu.umd.cs.submitServer.MultipartRequest.java
public Timestamp getTimestampParameter(String name) throws InvalidRequiredParameterException { String param = getStringParameter(name); if (param == null || param.equals("")) { throw new InvalidRequiredParameterException(name + " is a required parameter"); }//from ww w . j av a 2 s .c o m Timestamp timestamp = null; try { timestamp = Timestamp.valueOf(param); } catch (IllegalArgumentException e) { throw new InvalidRequiredParameterException("name was of an invalid form: " + e.toString()); } return timestamp; }
From source file:com.silverpeas.gallery.dao.MediaDaoTest.java
@Test public void getMediaThatWillBeNotVisible() throws Exception { performDAOTest(new DAOTest() { @Override/*w w w .jav a 2s .c o m*/ public void test(final Connection connection) throws Exception { Date today = Timestamp.valueOf("2014-03-30 11:33:45.854"); List<Media> media = MediaDAO.findByCriteria(connection, MediaCriteria.fromNbDaysBeforeThatMediaIsNotVisible(0).referenceDateOf(today)); assertThat(media, hasSize(0)); media = MediaDAO.findByCriteria(connection, MediaCriteria.fromNbDaysBeforeThatMediaIsNotVisible(1).referenceDateOf(today)); assertThat(media, hasSize(1)); media = MediaDAO.findByCriteria(connection, MediaCriteria.fromNbDaysBeforeThatMediaIsNotVisible(2).referenceDateOf(today)); assertThat(media, hasSize(0)); } }); }
From source file:com.hp.rest.GenericResource.java
@POST @Path("/putTakeOrder") @Consumes(MediaType.APPLICATION_JSON)//from w w w. j a v a 2 s .c om public Response putTakeOrder(String pTakeOrder) { // pair to object ObjectMapper mapper = new ObjectMapper(); TakeOrder takeOrder = new TakeOrder(); try { // File jsonFile = new File(jsonFilePath); takeOrder = mapper.readValue(pTakeOrder, TakeOrder.class); //System.out.println(track.getMMaKhachHang()); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date today = new Date(); if (takeOrder != null) { takeOrder.setTakeOrderDate(Timestamp.valueOf(df.format(today))); takeOrder.setDeliveryDate(Timestamp.valueOf(df.format(today))); } //Update location TakeOrderDAO takeOrderDAO = new TakeOrderDAOImpl(); boolean st = takeOrderDAO.saveOrUpdate(takeOrder); // String output = pTrack.toString(); System.out.println("pTakeOrder: " + st + "____ " + pTakeOrder); return Response.status(200).entity(st + "").build(); }
From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java
public void testDate() throws SQLException { PreparedStatement prep = conn.prepareStatement("SELECT ?"); Timestamp ts = Timestamp.valueOf("2001-02-03 04:05:06"); prep.setObject(1, new java.util.Date(ts.getTime())); ResultSet rs = prep.executeQuery(); rs.next();/*w w w. j a va2 s . c o m*/ Timestamp ts2 = rs.getTimestamp(1); assertEquals(ts.toString(), ts2.toString()); }
From source file:org.eclipse.birt.data.oda.mongodb.impl.MDbResultSet.java
private static Object tryConvertToDataType(Object value, Class<?> toDataType) throws OdaException { if (value == null || toDataType.isInstance(value)) // already in specified data type return value; try {//from w w w . j a v a2 s .co m if (value instanceof String) { String stringValue = (String) value; if (toDataType == Integer.class) return Integer.valueOf(stringValue); if (toDataType == Double.class) return Double.valueOf(stringValue); if (toDataType == BigDecimal.class) return new BigDecimal(stringValue); if (toDataType == Boolean.class) return Boolean.valueOf(stringValue); if (toDataType == Date.class) return Date.valueOf(stringValue); if (toDataType == Timestamp.class) return Timestamp.valueOf(stringValue); if (toDataType == byte[].class) return tryConvertToBytes(stringValue); } if (value instanceof java.util.Date) // the object type returned by MongoDB for a Date field { long msTime = ((java.util.Date) value).getTime(); if (toDataType == Date.class) return new Date(msTime); if (toDataType == Timestamp.class) return new Timestamp(msTime); } if (value instanceof BSONTimestamp) { long msTime = ((BSONTimestamp) value).getTime() * 1000L; if (toDataType == Date.class) return new Date(msTime); if (toDataType == Timestamp.class) return new Timestamp(msTime); } if (toDataType == Integer.class) return tryConvertToInteger(value); if (toDataType == Double.class) return tryConvertToDouble(value); if (toDataType == Boolean.class) return tryConvertToBoolean(value); } catch (Exception ex) { String errMsg = Messages.bind(Messages.mDbResultSet_cannotConvertFieldData, new Object[] { DriverUtil.EMPTY_STRING, value, value.getClass().getSimpleName(), toDataType.getSimpleName() }); getLogger().severe(errMsg); OdaException odaEx = new OdaException(errMsg); odaEx.initCause(ex); throw odaEx; } // non-handled data type conversion; return value as is return value; }
From source file:gov.nih.nci.cadsr.sentinel.tool.AlertRec.java
/** * Set the Creation date./* w w w.j a va 2 s . c o m*/ * * @param val_ * If null, today's day and time are used. If not null, must match * the form documented for java.sql.Timestamp.valueOf(). */ public void setCdate(String val_) { if (val_ == null) { Date today = new Date(); _cdate = new Timestamp(today.getTime()); } else _cdate = Timestamp.valueOf(val_); }
From source file:org.idempiere.webservices.AbstractService.java
/** * /*from w w w . j a va 2 s . c om*/ * @param strValue * @param columnClass * @param colName * @param m_webservicetype * @return */ protected Object convertToObj(String strValue, Class<?> columnClass, String colName) { Object value = null; if (columnClass == Boolean.class) { if ("Y".equalsIgnoreCase(strValue) || "true".equalsIgnoreCase(strValue)) value = new Boolean(true); else if ("N".equalsIgnoreCase(strValue) || "false".equalsIgnoreCase(strValue)) value = new Boolean(false); else throw new IdempiereServiceFault(" input column " + colName + " wrong value " + strValue, new QName("setValueAccordingToClass")); } else if (columnClass == Integer.class) { try { value = Integer.parseInt(strValue); } catch (NumberFormatException e) { throw new IdempiereServiceFault(e.getClass().toString() + " " + e.getMessage() + " for " + colName, e.getCause(), new QName("setValueAccordingToClass")); } } else if (columnClass == BigDecimal.class) { try { value = new BigDecimal(strValue); } catch (Exception e) { throw new IdempiereServiceFault(e.getClass().toString() + " " + e.getMessage() + " for " + colName, e.getCause(), new QName("setValueAccordingToClass")); } } else if (columnClass == Timestamp.class) { try { value = Timestamp.valueOf(strValue); } catch (Exception e) { throw new IdempiereServiceFault(e.getClass().toString() + " " + e.getMessage() + " for " + colName, e.getCause(), new QName("setValueAccordingToClass")); } } else if (columnClass == byte[].class) { try { value = Base64.decodeBase64(strValue.getBytes()); } catch (Exception e) { throw new IdempiereServiceFault(e.getClass().toString() + " " + e.getMessage() + " for " + colName, e.getCause(), new QName("setValueAccordingToClass")); } } else { value = strValue; } return value; }
From source file:org.waarp.openr66.protocol.localhandler.ServerActions.java
/** * Receive a validation or a special request * /* w w w. jav a 2 s .c o m*/ * @param channel * @param packet * @throws OpenR66ProtocolNotAuthenticatedException * @throws OpenR66RunnerErrorException * @throws OpenR66ProtocolSystemException * @throws OpenR66ProtocolBusinessException */ public void valid(Channel channel, ValidPacket packet) throws OpenR66ProtocolNotAuthenticatedException, OpenR66RunnerErrorException, OpenR66ProtocolSystemException, OpenR66ProtocolBusinessException { // SHUTDOWNPACKET does not need authentication if (packet.getTypeValid() != LocalPacketFactory.SHUTDOWNPACKET && (!session.isAuthenticated())) { logger.warn("Valid packet received while not authenticated: {} {}", packet, session); session.newState(ERROR); packet.clear(); throw new OpenR66ProtocolNotAuthenticatedException("Not authenticated while Valid received"); } switch (packet.getTypeValid()) { case LocalPacketFactory.SHUTDOWNPACKET: { int rank = -1; if (session.getRunner() != null && session.getRunner().isInTransfer()) { String srank = packet.getSmiddle(); if (srank != null && !srank.isEmpty()) { // Save last rank from remote point of view try { rank = Integer.parseInt(srank); } catch (NumberFormatException e) { // ignore } } } R66Result result = new R66Result(new OpenR66ProtocolShutdownException(), session, true, ErrorCode.Shutdown, session.getRunner()); result.other = packet; rank = shutdownRequest(result, rank); if (rank >= 0) { packet.setSmiddle(Integer.toString(rank)); try { ChannelUtils.writeAbstractLocalPacket(localChannelReference, packet, true); } catch (OpenR66ProtocolPacketException e) { } } shutdownLocalChannel(channel); break; } case LocalPacketFactory.STOPPACKET: case LocalPacketFactory.CANCELPACKET: { String[] keys = packet.getSmiddle().split(" "); long id = Long.parseLong(keys[2]); session.newState(VALIDOTHER); R66Result resulttest = stopOrCancel(packet.getTypeValid(), keys[0], keys[1], id); // inform back the requester ValidPacket valid = new ValidPacket(packet.getSmiddle(), resulttest.code.getCode(), LocalPacketFactory.REQUESTUSERPACKET); resulttest.other = packet; localChannelReference.validateRequest(resulttest); try { ChannelUtils.writeAbstractLocalPacket(localChannelReference, valid, true); } catch (OpenR66ProtocolPacketException e) { } session.setStatus(27); channel.close(); break; } case LocalPacketFactory.VALIDPACKET: { // header = ?; middle = requested+blank+requester+blank+specialId // note: might contains one more argument = time to reschedule in yyyyMMddHHmmss format String[] keys = packet.getSmiddle().split(" "); ValidPacket valid = null; if (keys.length < 3) { // not enough args valid = new ValidPacket(packet.getSmiddle(), ErrorCode.IncorrectCommand.getCode(), LocalPacketFactory.REQUESTUSERPACKET); R66Result resulttest = new R66Result( new OpenR66ProtocolBusinessRemoteFileNotFoundException("Not enough arguments"), session, true, ErrorCode.IncorrectCommand, null); resulttest.other = packet; localChannelReference.invalidateRequest(resulttest); } else { long id = Long.parseLong(keys[2]); Date date = null; if (keys.length > 3) { // time to reschedule in yyyyMMddHHmmss format logger.debug("Debug: restart with " + keys[3]); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); try { date = dateFormat.parse(keys[3]); } catch (ParseException e) { } } session.newState(VALIDOTHER); R66Result result = requestRestart(keys[0], keys[1], id, date); valid = new ValidPacket(packet.getSmiddle(), result.code.getCode(), LocalPacketFactory.REQUESTUSERPACKET); result.other = packet; if (isCodeValid(result.code)) { localChannelReference.validateRequest(result); } else { localChannelReference.invalidateRequest(result); } } // inform back the requester try { ChannelUtils.writeAbstractLocalPacket(localChannelReference, valid, true); } catch (OpenR66ProtocolPacketException e) { } channel.close(); break; } case LocalPacketFactory.REQUESTUSERPACKET: { session.newState(VALIDOTHER); // Validate user request R66Result resulttest = new R66Result(session, true, ErrorCode.getFromCode(packet.getSmiddle()), null); resulttest.other = packet; switch (resulttest.code) { case CompleteOk: case InitOk: case PostProcessingOk: case PreProcessingOk: case QueryAlreadyFinished: case QueryStillRunning: case Running: case TransferOk: break; default: localChannelReference.invalidateRequest(resulttest); session.setStatus(102); channel.close(); return; } localChannelReference.validateRequest(resulttest); session.setStatus(28); channel.close(); break; } case LocalPacketFactory.LOGPACKET: case LocalPacketFactory.LOGPURGEPACKET: { session.newState(VALIDOTHER); // should be from the local server or from an authorized hosts: LOGCONTROL try { if (!session.getAuth().getUser() .equals(Configuration.configuration.getHostId(session.getAuth().isSsl())) && !session.getAuth().isValidRole(ROLE.LOGCONTROL)) { throw new OpenR66ProtocolNotAuthenticatedException("Not correctly authenticated"); } } catch (OpenR66ProtocolNoSslException e1) { throw new OpenR66ProtocolNotAuthenticatedException( "Not correctly authenticated since SSL is not supported", e1); } String sstart = packet.getSheader(); String sstop = packet.getSmiddle(); boolean isPurge = (packet.getTypeValid() == LocalPacketFactory.LOGPURGEPACKET); Timestamp start = (sstart == null || sstart.isEmpty()) ? null : Timestamp.valueOf(sstart); Timestamp stop = (sstop == null || sstop.isEmpty()) ? null : Timestamp.valueOf(sstop); packet.clear(); // create export of log and optionally purge them from database DbPreparedStatement getValid = null; String filename = Configuration.configuration.baseDirectory + Configuration.configuration.archivePath + R66Dir.SEPARATOR + Configuration.configuration.HOST_ID + "_" + System.currentTimeMillis() + "_runners.xml"; try { getValid = DbTaskRunner.getLogPrepareStatement(localChannelReference.getDbSession(), start, stop); DbTaskRunner.writeXMLWriter(getValid, filename); } catch (WaarpDatabaseNoConnectionException e1) { throw new OpenR66ProtocolBusinessException(e1); } catch (WaarpDatabaseSqlException e1) { throw new OpenR66ProtocolBusinessException(e1); } finally { if (getValid != null) { getValid.realClose(); } } // in case of purge int nb = 0; if (isPurge) { // purge in same interval all runners with globallaststep // as ALLDONETASK or ERRORTASK if (Configuration.configuration.r66Mib != null) { Configuration.configuration.r66Mib.notifyWarning("Purge Log Order received", session.getAuth().getUser()); } try { nb = DbTaskRunner.purgeLogPrepareStatement(localChannelReference.getDbSession(), start, stop); } catch (WaarpDatabaseNoConnectionException e) { throw new OpenR66ProtocolBusinessException(e); } catch (WaarpDatabaseSqlException e) { throw new OpenR66ProtocolBusinessException(e); } } R66Result result = new R66Result(session, true, ErrorCode.CompleteOk, null); // Now answer ValidPacket valid = new ValidPacket(filename + " " + nb, result.code.getCode(), LocalPacketFactory.REQUESTUSERPACKET); localChannelReference.validateRequest(result); try { ChannelUtils.writeAbstractLocalPacket(localChannelReference, valid, true); } catch (OpenR66ProtocolPacketException e) { } channel.close(); break; } case LocalPacketFactory.CONFEXPORTPACKET: { String shost = packet.getSheader(); String srule = packet.getSmiddle(); boolean bhost = Boolean.parseBoolean(shost); boolean brule = Boolean.parseBoolean(srule); packet.clear(); session.newState(VALIDOTHER); String[] sresult = configExport(bhost, brule, false, false, false); R66Result result = null; if (sresult[0] != null || sresult[1] != null) { result = new R66Result(session, true, ErrorCode.CompleteOk, null); } else { result = new R66Result(session, true, ErrorCode.TransferError, null); } // Now answer ValidPacket valid = new ValidPacket(shost + " " + srule, result.code.getCode(), LocalPacketFactory.REQUESTUSERPACKET); localChannelReference.validateRequest(result); try { ChannelUtils.writeAbstractLocalPacket(localChannelReference, valid, true); } catch (OpenR66ProtocolPacketException e) { } channel.close(); break; } case LocalPacketFactory.CONFIMPORTPACKET: { session.newState(VALIDOTHER); // Authentication must be the local server or CONFIGADMIN authorization try { if (!session.getAuth().getUser() .equals(Configuration.configuration.getHostId(session.getAuth().isSsl())) && !session.getAuth().isValidRole(ROLE.CONFIGADMIN)) { throw new OpenR66ProtocolNotAuthenticatedException("Not correctly authenticated"); } } catch (OpenR66ProtocolNoSslException e1) { throw new OpenR66ProtocolNotAuthenticatedException( "Not correctly authenticated since SSL is not supported", e1); } if (Configuration.configuration.r66Mib != null) { Configuration.configuration.r66Mib.notifyWarning("Import Configuration Order received", session.getAuth().getUser()); } String shost = packet.getSheader(); String srule = packet.getSmiddle(); boolean bhostPurge = shost.startsWith("1 "); shost = shost.substring(2); boolean brulePurge = srule.startsWith("1 "); srule = srule.substring(2); boolean bhost = !shost.isEmpty(); boolean brule = !srule.isEmpty(); packet.clear(); if (bhost) { DbHostAuth[] oldHosts = null; if (bhostPurge) { // Need to first delete all entries try { oldHosts = DbHostAuth.deleteAll(localChannelReference.getDbSession()); } catch (WaarpDatabaseException e) { // ignore } } String filename = shost; if (AuthenticationFileBasedConfiguration.loadAuthentication(Configuration.configuration, filename)) { shost = "Host:OK"; } else { logger.error("Error in Load Hosts"); shost = "Host:KO"; bhost = false; } if (!bhost) { if (oldHosts != null) { for (DbHostAuth dbHost : oldHosts) { try { if (!dbHost.exist()) { dbHost.insert(); } } catch (WaarpDatabaseException e1) { // ignore } } } } } if (brule) { DbRule[] oldRules = null; if (brulePurge) { // Need to first delete all entries try { oldRules = DbRule.deleteAll(localChannelReference.getDbSession()); } catch (WaarpDatabaseException e) { // ignore } } File file = new File(srule); try { RuleFileBasedConfiguration.getMultipleFromFile(file); srule = "Rule:OK"; brule = true; } catch (WaarpDatabaseNoConnectionException e) { logger.error("Error", e); srule = "Rule:KO"; brule = false; } catch (WaarpDatabaseSqlException e) { logger.error("Error", e); srule = "Rule:KO"; brule = false; } catch (WaarpDatabaseNoDataException e) { logger.error("Error", e); srule = "Rule:KO"; brule = false; } catch (WaarpDatabaseException e) { logger.error("Error", e); srule = "Rule:KO"; brule = false; } if (!brule) { if (oldRules != null) { for (DbRule dbRule : oldRules) { try { if (!dbRule.exist()) { dbRule.insert(); } } catch (WaarpDatabaseException e1) { // ignore } } } } } R66Result result = null; if (brule || bhost) { result = new R66Result(session, true, ErrorCode.CompleteOk, null); } else { result = new R66Result(session, true, ErrorCode.TransferError, null); } // Now answer ValidPacket valid = new ValidPacket(shost + " " + srule, result.code.getCode(), LocalPacketFactory.REQUESTUSERPACKET); localChannelReference.validateRequest(result); try { ChannelUtils.writeAbstractLocalPacket(localChannelReference, valid, true); } catch (OpenR66ProtocolPacketException e) { } channel.close(); break; } case LocalPacketFactory.INFORMATIONPACKET: { session.newState(VALIDOTHER); // Validate user request R66Result resulttest = new R66Result(session, true, ErrorCode.CompleteOk, null); resulttest.other = packet; localChannelReference.validateRequest(resulttest); channel.close(); break; } case LocalPacketFactory.BANDWIDTHPACKET: { String[] splitglobal = packet.getSheader().split(" "); String[] splitsession = packet.getSmiddle().split(" "); packet.clear(); R66Result result = new R66Result(session, true, ErrorCode.CompleteOk, null); ValidPacket valid = null; if (splitglobal.length < 2 || splitsession.length < 2) { // request of current values session.newState(VALIDOTHER); long[] lresult = bandwidth(false, 0, 0, 0, 0); // Now answer valid = new ValidPacket(lresult[0] + " " + lresult[1] + " " + lresult[2] + " " + lresult[3], result.code.getCode(), LocalPacketFactory.REQUESTUSERPACKET); } else { session.newState(VALIDOTHER); bandwidth(true, Long.parseLong(splitglobal[0]), Long.parseLong(splitglobal[1]), Long.parseLong(splitsession[0]), Long.parseLong(splitsession[1])); // Now answer valid = new ValidPacket("Bandwidth changed", result.code.getCode(), LocalPacketFactory.REQUESTUSERPACKET); } localChannelReference.validateRequest(result); try { ChannelUtils.writeAbstractLocalPacket(localChannelReference, valid, true); } catch (OpenR66ProtocolPacketException e) { } channel.close(); break; } case LocalPacketFactory.TESTPACKET: { session.newState(VALIDOTHER); logger.info("Valid TEST MESSAGE: " + packet.toString()); R66Result resulttest = new R66Result(session, true, ErrorCode.CompleteOk, null); resulttest.other = packet; localChannelReference.validateRequest(resulttest); channel.close(); break; } default: logger.info("Validation is ignored: " + packet.getTypeValid()); packet.clear(); } }