public void testSerialization() { int hashCode = ColorEnum.RED.hashCode(); assertSame(ColorEnum.RED, SerializationUtils.clone(ColorEnum.RED)); assertEquals(hashCode, SerializationUtils.clone(ColorEnum.RED).hashCode()); assertSame(ColorEnum.GREEN, SerializationUtils.clone(ColorEnum.GREEN)); assertSame(ColorEnum.BLUE, SerializationUtils.clone(ColorEnum.BLUE)); }
@Test public void testPropertiesCaseAfterSerialization() throws Exception { // Default scope MessagePropertiesContext mpc = new MessagePropertiesContext(); mpc.setProperty("FOO", "BAR"); mpc.setProperty("ABC", "abc"); mpc.setProperty("DOO", "DAR", PropertyScope.INVOCATION); doTest(mpc); // Serialize and deserialize byte[] bytes = SerializationUtils.serialize(mpc); mpc = (MessagePropertiesContext) SerializationUtils.deserialize(bytes); doTest(mpc); }
/** * ルールセット定義をロールバックする。<br> * * @param serializedRules シリアライズ化されたルールデータ */ @SuppressWarnings("unchecked") public synchronized void rollbackRuleSet(final SerializedRules serializedRules) { byte[] ruleSetConfigMapData = serializedRules.getRuleSetConfigMapData(); byte[] ruleMapData = serializedRules.getRuleMapData(); if (ruleSetConfigMapData == null || ruleSetConfigMapData.length == 0 || ruleMapData == null || ruleMapData.length == 0) { return; } this.ruleSetConfigMap_ = (HashMap<String, RuleSetConfig>) SerializationUtils.deserialize(ruleSetConfigMapData); this.ruleSetMap_ = (HashMap<String, RuleSetDef>) SerializationUtils.deserialize(ruleMapData); this.removeList_ = Collections.synchronizedList(new ArrayList<RuleSetConfig>()); }
public static SoapDirectoryUriRequest<?> deserialize(String serializedDirectoryUri) { String directoryUri = StringUtils.substringAfter(serializedDirectoryUri, DIRECTORY_URI_PREFIX); byte[] bytes = Base64.decodeBase64(directoryUri.getBytes()); return (SoapDirectoryUriRequest<?>) SerializationUtils.deserialize(bytes); }
/** * 「更新」ボタン押下時 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ @SuppressWarnings("unchecked") public ActionForward update( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { QuotationListForm listForm = (QuotationListForm) form; String voucherNo = listForm.getSel()[0]; // セッションの伝票BeanMapより選択した伝票Beanを取得。セッションに格納 Map<String, VoucherBean> voucherBeanMap = (Map<String, VoucherBean>) request.getSession(false).getAttribute(BizCommonConstants.BEAN_NAME_VOUCHER_BEAN_MAP); VoucherBean voucherBean = (VoucherBean) SerializationUtils.clone(voucherBeanMap.get(voucherNo)); request.getSession(false).setAttribute(BizCommonConstants.BEAN_NAME_VOUCHER_BEAN, voucherBean); // 伝票Beanを元に見積書FormBeanを作成。セッションに格納 QuotationForm quotationForm = new QuotationForm(); QuotationBL.reflectVoucherBeanToQuotationForm(quotationForm, voucherBean); request .getSession(false) .setAttribute(BizCommonConstants.FORM_BEAN_NAME_QUOTATION_FORM, quotationForm); // 不要となるセッション情報を破棄 request .getSession(false) .removeAttribute(BizCommonConstants.FORM_BEAN_NAME_QUOTATION_LIST_FORM); return mapping.findForward(BizCommonConstants.FWD_UPDATE); }
protected Response query(Request request, DetachedCriteria obj, boolean lazyLoad, int maxResult) throws Exception { Response rsp = new Response(); log.info("Detached Criteria Query :" + obj.toString()); if (request.getIsCount() != null && request.getIsCount()) { obj = (DetachedCriteria) SerializationUtils.clone(obj); HibernateCallback callBack = getExecuteCountCriteriaHibernateCallback(obj); Integer rowCount = (Integer) getHibernateTemplate().execute(callBack); log.debug("DetachedCriteria ORMDAOImpl ===== count = " + rowCount); rsp.setRowCount(rowCount); } else { HibernateCallback callBack = getExecuteFindQueryCriteriaHibernateCallback( obj, lazyLoad, request.getFirstRow() == null ? -1 : request.getFirstRow(), maxResult > 0 ? maxResult : this.getResultCountPerQuery()); List rs = (List) getHibernateTemplate().execute(callBack); rsp.setRowCount(rs.size()); rsp.setResponse(rs); } return rsp; }
/** {@inheritDoc} */ @Override public void configure(Job job) throws IOException { // Configure the input format class. super.configure(job); // Get the name of the HBase table that stores the Kiji table data. String hbaseTableName = KijiManagedHBaseTableName.getKijiTableName( mInputTable.getKiji().getName(), mInputTable.getName()) .toString(); // Create the HBase scan configured to read the appropriate input from the Kiji table. Scan configuredScan = createConfiguredScan(mInputTable.getLayout()); // Configure the table input using HBase. GenericTableMapReduceUtil.initTableInput(hbaseTableName, configuredScan, job); final Configuration conf = job.getConfiguration(); final String serializedRequest = Base64.encodeBase64String(SerializationUtils.serialize(mDataRequest)); conf.set(KijiConfKeys.INPUT_DATA_REQUEST, serializedRequest); final Kiji kiji = mInputTable.getKiji(); // TODO(KIJI-144): Move this to KijiTable.getTableURI() conf.set( KijiConfKeys.INPUT_TABLE_URI, String.format( "kiji://%s:%s/%s/%s", kiji.getConf().get(HConstants.ZOOKEEPER_QUORUM), kiji.getConf() .getInt(HConstants.ZOOKEEPER_CLIENT_PORT, HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT), kiji.getName(), mInputTable.getName())); }
/** * 商品在庫表リスト取得処理 * * @param form * @return * @throws IOException * @throws SQLException * @throws IllegalAccessException * @throws InvocationTargetException */ public static List<BookItemStock> getBookItemStockList(BookItemForm form) throws IOException, SQLException, IllegalAccessException, InvocationTargetException { BookItemStockDAO dao = new BookItemStockDAO(TransactionInfo.getConnection()); List<BookItemStock> bookItemStockList = new ArrayList<BookItemStock>(); List<Object> params = new ArrayList<Object>(); StringBuilder sql = new StringBuilder(); sql.append(choiceSQLSelect(form, params)); sql.append(CommonConstants.HALF_SPACE); sql.append(choiceSQLSort(form)); List<CommonDTO> retList = dao.select(sql.toString(), params); for (CommonDTO dto : retList) { BookItemStock bookItemStock = new BookItemStock(); ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class); BeanUtils.copyProperties(bookItemStock, SerializationUtils.clone((BookItemStockDTO) dto)); bookItemStock.setKabusoku( BookItemCommonBL.calcKabusoku(bookItemStock.getProperStock(), bookItemStock.getStock())); bookItemStockList.add(bookItemStock); } return bookItemStockList; }
public byte[] getPayloadAsBytes() throws Exception { if (message instanceof byte[]) { return (byte[]) message; } else { return SerializationUtils.serialize((Serializable) message); } }
private void listUser(ReqCtx ctx, HttpServletResponse response) throws IOException { try { // String sessionId = ctx.getArgVal(JSESSIONID_tag); // HttpSession session = SessionCounterListener.getSession(sessionId); OutputStream s = response.getOutputStream(); // outstmt = con.prepareStatement("SELECT Password,Status FROM User WHERE MobileNumber = ?"); // PreparedStatement stmt = con.prepareStatement("SELECT * FROM User where Name=?"); PreparedStatement stmt = con.prepareStatement("SELECT * FROM User where Status!='deleted'"); // stmt.setString(1,"First"); ResultSet rs = stmt.executeQuery(); ArrayList<HashMap<String, String>> set = new ArrayList<HashMap<String, String>>(); HashMap<String, String> cur; log(Level.INFO, "Listing User Start"); while (rs.next()) { cur = new HashMap<String, String>(); cur.put("userKeyID", rs.getString("UserId")); cur.put("usrName", rs.getString("Name")); cur.put("mobNum", rs.getString("MobileNumber")); cur.put("alias", rs.getString("Alias")); cur.put("usrEmail", rs.getString("EmailAddress")); cur.put("address", rs.getString("Address")); cur.put("notes", rs.getString("AddressVerificationNotes")); cur.put("remainingCreditPostAudit", rs.getString("RemainingCreditPostAudit")); cur.put("lastAuditedActivityAt", rs.getString("LastAuditedActivityAt")); java.sql.Blob bT = rs.getBlob("ImageFile"); String str = getBase64OfBlob(bT); cur.put("imageFile", str); cur.put("profilePic", getBase64OfBlob(rs.getBlob("ProfilePic"))); cur.put("idProofFile", getBase64OfBlob(rs.getBlob("IdProofFile"))); cur.put("addressProofFile", getBase64OfBlob(rs.getBlob("AddrProofFile"))); // Getting the MAC address corresponding to the current User Id from the Device table stmt = con.prepareStatement( "SELECT MAC FROM Device where UserId=?", Statement.RETURN_GENERATED_KEYS); stmt.setInt(1, rs.getInt("UserId")); ResultSet rs2 = stmt.executeQuery(); rs2.next(); cur.put("custDeviceId", rs2.getString(1)); // o.println("Writing : "+cur); set.add(cur); } log(INFO, "Sending the data of " + set.size() + " users"); byte objBytes[] = SerializationUtils.serialize(set); s.write(objBytes, 0, objBytes.length); s.close(); // out.close(); } catch (Exception e) { log(Level.INFO, "Listing User Failed"); errorResponse(ctx, response, e.getMessage()); log(WARNING, "Exception in listUser of Oprtr: " + e); log.error("stack trace", e); } }
public Object getResultData() { try { return strat.compressByteArray(SerializationUtils.serialize(TEST_DATA)); } catch (Exception e) { fail(e.getMessage()); return null; } }
/** {@inheritDoc} */ public Payment capture(final Payment paymentIn) { final Payment payment = (Payment) SerializationUtils.clone(paymentIn); payment.setTransactionOperation(CAPTURE); payment.setTransactionReferenceId(UUID.randomUUID().toString()); payment.setTransactionAuthorizationCode(UUID.randomUUID().toString()); payment.setPaymentProcessorResult(Payment.PAYMENT_STATUS_MANUAL_PROCESSING_REQUIRED); payment.setPaymentProcessorBatchSettlement(false); return payment; }
public static String serialize(SoapDirectoryUriRequest<?> directoryUri) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); SerializationUtils.serialize(directoryUri, baos); String serializedDirectoryUri = new String(Base64.encodeBase64(baos.toByteArray())); return DIRECTORY_URI_PREFIX + serializedDirectoryUri; }
public void sendMessage(Serializable object, String routingKey, String exchangeName) throws IOException { channel.basicPublish( exchangeName, routingKey, MessageProperties.PERSISTENT_TEXT_PLAIN, SerializationUtils.serialize(object)); channel.close(); connection.close(); }
public static void main(String[] args) { Integer a = new Integer(3); Integer b = copy(a); Integer c = (Integer) SerializationUtils.clone(a); System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(System.identityHashCode(a) + ":" + System.identityHashCode(c)); }
// @Override public Object read(InputStream is) throws IOException { byte[] tmp = (byte[]) super.read(is); if (tmp == null) { return null; } else { MessageObject serializableObject = (MessageObject) SerializationUtils.deserialize(tmp); return new NonSerializableMessageObject( serializableObject.i, serializableObject.s, serializableObject.b); } }
@Override public void write(DataOutput out) throws IOException { LOG.debug("WRITE : " + this); Bytes.writeByteArray(out, Bytes.toBytes(splits.size())); for (HBaseTableSplit hbts : splits) { Bytes.writeByteArray(out, SerializationUtils.serialize(hbts)); } LOG.debug("WROTE : " + out.toString()); }
// @Override public void write(OutputStream os, Object data) throws IOException { if (data instanceof NonSerializableMessageObject) { NonSerializableMessageObject in = (NonSerializableMessageObject) data; // do serialization... will use normal Serialization to simplify code... MessageObject serializableObject = new MessageObject(in.i, in.s, in.b); write(os, SerializationUtils.serialize(serializableObject)); } else { super.write(os, data); } }
private List<RuleSetBean> createRuleSet(Integer studyEventDefId) { List<RuleSetBean> ruleSetsDB = getRuleSetDao().findAllByStudyEventDefIdWhereItemIsNull(studyEventDefId); List<RuleSetBean> ruleSetCopies = new ArrayList<RuleSetBean>(); for (RuleSetBean ruleSetDB : ruleSetsDB) { RuleSetBean ruleSetCopy = (RuleSetBean) SerializationUtils.clone(ruleSetDB); ruleSetCopies.add(ruleSetCopy); } return ruleSetCopies; }
public byte[] getPayloadForSerialization() throws Exception { if (message instanceof InputStream) { // message is an InputStream when the HTTP method was POST return IOUtils.toByteArray((InputStream) message); } else if (message instanceof Serializable) { // message is a String when the HTTP method was GET return SerializationUtils.serialize((Serializable) message); } else { throw new NotSerializableException( "Don't know how to serialize payload of type " + message.getClass().getName()); } }
/** * Populates an environment db from a persist log. If historyMap is not provided, only logs the * entries that would have been populated. * * @param persistLogReader persist log * @param historyMap new environment db (or null for a dry run) * @return number of records * @throws UnsupportedEncodingException * @throws DatabaseException */ private static int populatePersistEnvFromLog( BufferedReader persistLogReader, StoredSortedMap<String, Map> historyMap) throws UnsupportedEncodingException, DatabaseException { int count = 0; Iterator<String> iter = new LineReadingIterator(persistLogReader); while (iter.hasNext()) { String line = iter.next(); if (line.length() == 0) { continue; } String[] splits = line.split(" "); if (splits.length != 2) { logger.severe("bad line has " + splits.length + " fields (should be 2): " + line); continue; } Map alist; try { alist = (Map) SerializationUtils.deserialize(Base64.decodeBase64(splits[1].getBytes("UTF-8"))); } catch (Exception e) { logger.severe("caught exception " + e + " deserializing line: " + line); continue; } if (logger.isLoggable(Level.FINE)) { logger.fine(splits[0] + " " + ArchiveUtils.prettyString(alist)); } if (historyMap != null) try { historyMap.put(splits[0], alist); } catch (Exception e) { logger.log( Level.SEVERE, "caught exception after loading " + count + " urls from the persist log (perhaps crawl was stopped by user?)", e); IOUtils.closeQuietly(persistLogReader); // seems to finish most cleanly when we return rather than throw something return count; } count++; } IOUtils.closeQuietly(persistLogReader); return count; }
public Object doTransform(Object src, String encoding) throws TransformerException { try { byte[] data = null; if (src instanceof byte[]) { data = (byte[]) src; } else { data = SerializationUtils.serialize((Serializable) src); } return this.getStrategy().compressByteArray(data); } catch (IOException ioex) { throw new TransformerException(this, ioex); } }
@Override public void readFields(DataInput in) throws IOException { LOG.debug("READ ME : " + in.toString()); int s = Bytes.toInt(Bytes.readByteArray(in)); for (int i = 0; i < s; i++) { HBaseTableSplit hbts = (HBaseTableSplit) SerializationUtils.deserialize(Bytes.readByteArray(in)); splits.add(hbts); } LOG.debug("READ and CREATED : " + this); }
@Test public void canBeSerialized() throws Throwable { FakeSerializableExternalResource instance = new FakeSerializableExternalResource().value(1); FakeSerializableExternalResource cloned = (FakeSerializableExternalResource) SerializationUtils.clone(instance); assertThat(instance.value()).isEqualTo(1); assertThat(cloned.value()).isEqualTo(1); instance.value(2); assertThat(instance.value()).isEqualTo(2); assertThat(cloned.value()).isEqualTo(1); }
@Subscribe public void handleJob(JobPacket jobPacket) throws Exception { JobPacket packetToClient = new JobPacket(); if (jobPacket.type == JobPacket.JOB_REQ) { jobQueue.add(jobPacket.hash); packetToClient.type = JobPacket.JOB_ACCEPTED; packetToClient.result = "none"; } if (jobPacket.type == JobPacket.JOB_STATUS) { // check under /result/<hash> try { if ((zooKeeper.exists(Joiner.on("/").join(ZK_JOBS, jobPacket.hash), false) != null) && (zooKeeper.exists(Joiner.on("/").join(ZK_RESULT, jobPacket.hash), false) == null)) { System.out.println("Job in progress, please wait!"); packetToClient.type = JobPacket.JOB_PROGRESS; packetToClient.result = "none"; } if ((zooKeeper.exists(Joiner.on("/").join(ZK_JOBS, jobPacket.hash), false) == null) && (zooKeeper.exists(Joiner.on("/").join(ZK_RESULT, jobPacket.hash), false) == null)) { System.out.println("No such Job, please enter your job again!"); packetToClient.type = JobPacket.JOB_NOTFOUND; packetToClient.result = "none"; } if (zooKeeper.exists(Joiner.on("/").join(ZK_RESULT, jobPacket.hash), false) != null) { byte[] data = zooKeeper.getData(Joiner.on("/").join(ZK_RESULT, jobPacket.hash), false, null); packetToClient.type = JobPacket.JOB_RESULT; if (data == null) { System.out.println("Result not found!"); packetToClient.result = null; } else { String result = new String(data); packetToClient.result = result; System.out.println("Result found!"); } } } catch (Exception e) { e.printStackTrace(); } } socket.send(SerializationUtils.serialize(packetToClient), 0); }
/** {@inheritDoc} */ @Override protected void configureJob(final Job job) throws IOException { if (null == mScoreFunctionClass) { throw new JobConfigurationException("Must specify a ScoreFunction class."); } if (null == mClientDataRequest) { mClientDataRequest = DEFAULT_CLIENT_REQUEST; } if (null == mAttachedColumn) { throw new JobConfigurationException("Must specified an AttachedColumn."); } if (null == mParameters) { mParameters = DEFAULT_PARAMETERS; } final Configuration conf = job.getConfiguration(); conf.setClass(SCORE_FUNCTION_CLASS_CONF_KEY, mScoreFunctionClass, ScoreFunction.class); if (!getInputTableURI().equals(mJobOutput.getOutputTableURI())) { throw new JobConfigurationException( String.format( "Output table must be the same as the input" + "table. Got input: %s output: %s", getInputTableURI(), mJobOutput.getOutputTableURI())); } conf.set(SCORE_FUNCTION_ATTACHED_COLUMN_CONF_KEY, mAttachedColumn.getName()); conf.set(SCORE_FUNCTION_PARAMETERS_CONF_KEY, GSON.toJson(mParameters, Map.class)); conf.set( SCORE_FUNCTION_CLIENT_DATA_REQUEST_CONF_KEY, Base64.encodeBase64String(SerializationUtils.serialize(mClientDataRequest))); mMapper = new ScoreFunctionMapper(); mReducer = new IdentityReducer<Object, Object>(); job.setJobName("Kiji ScoreFunction: " + mScoreFunctionClass.getSimpleName()); mScoreFunction = ReflectionUtils.newInstance(mScoreFunctionClass, conf); final FreshenerContext context = InternalFreshenerContext.create( mClientDataRequest, mAttachedColumn, mParameters, Maps.<String, String>newHashMap(), KeyValueStoreReaderFactory.create(getRequiredStores())); mScoreFunctionDataRequest = mScoreFunction.getDataRequest(context); super.configureJob(job); }
/** * Tests backwards compatible serialization/deserialization of a MergeData message with the base * and R1 Helium versions, which used the protobuff MergeData message. */ @Test public void testSerializationWithHeliumR1Version() throws Exception { YangInstanceIdentifier path = TestModel.TEST_PATH; NormalizedNode<?, ?> data = ImmutableContainerNodeBuilder.create() .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)) .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")) .build(); MergeData expected = new MergeData(path, data, DataStoreVersions.HELIUM_1_VERSION); Object serialized = expected.toSerializable(); assertEquals( "Serialized type", ShardTransactionMessages.MergeData.class, serialized.getClass()); MergeData actual = MergeData.fromSerializable(SerializationUtils.clone((Serializable) serialized)); assertEquals("getPath", expected.getPath(), actual.getPath()); assertEquals("getData", expected.getData(), actual.getData()); }
public void send(final PopBlock popBlock) throws Error { mutex.lock(); try { if (closed) { throw new ChannelClosedError(); } if (blocking_once != null) { try { blocking_once.perform( new Performable() { @Override public Object perform() { object = (T) SerializationUtils.deserialize(popBlock.yield()); received = true; cvar.signal(); if (notifier != null) { notifier.notify(Pop.this); } return null; } }); } catch (Error error) { throw error; } } else { try { this.object = (T) SerializationUtils.deserialize(popBlock.yield()); this.received = true; this.cvar.signal(); if (notifier != null) { notifier.notify(this); } } catch (Rollback e) { } } } finally { mutex.unlock(); } }
private void listTransactions(ReqCtx ctx, HttpServletResponse response) throws IOException { o.println("In listTransactions ..."); int userId = Integer.parseInt(ctx.getArgVal(userKeyID_tag)); try { OutputStream s = response.getOutputStream(); // outstmt = con.prepareStatement("SELECT Password,Status FROM User WHERE MobileNumber = ?"); // PreparedStatement stmt = con.prepareStatement("SELECT * FROM User where Name=?"); PreparedStatement stmt = con.prepareStatement( "SELECT Details,Amount,Time FROM OperatorLedger where CreditUserId=? ||" + "DebitUserId = ? ", Statement.RETURN_GENERATED_KEYS); stmt.setInt(1, userId); stmt.setInt(2, userId); ResultSet rs = stmt.executeQuery(); ArrayList<HashMap<String, String>> set = new ArrayList<HashMap<String, String>>(); HashMap<String, String> cur; while (rs.next()) { cur = new HashMap<String, String>(); cur.put("Details", rs.getString("Details")); cur.put("Amount", rs.getString("Amount")); cur.put("Time", rs.getString("Time")); set.add(cur); } o.println("Sending the data of " + set.size() + " transactions"); byte objBytes[] = SerializationUtils.serialize(set); // byte []encoded = Base64.encode(objBytes); // ObjectOutputStream out = new ObjectOutputStream(s); // out.writeObject(objBytes); o.println("Flushed Data..."); s.write(objBytes, 0, objBytes.length); s.close(); // out.close(); } catch (Exception e) { errorResponse(ctx, response, e.getMessage()); o.println("Exception in listTransactions of UserId " + userId + " : " + e); } }
@Test public void testSerialization() { YangInstanceIdentifier path = TestModel.TEST_PATH; NormalizedNode<?, ?> data = ImmutableContainerNodeBuilder.create() .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)) .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")) .build(); MergeData expected = new MergeData(path, data, DataStoreVersions.CURRENT_VERSION); Object serialized = expected.toSerializable(); assertEquals("Serialized type", MergeData.class, serialized.getClass()); assertEquals( "Version", DataStoreVersions.CURRENT_VERSION, ((MergeData) serialized).getVersion()); Object clone = SerializationUtils.clone((Serializable) serialized); MergeData actual = MergeData.fromSerializable(clone); assertEquals("Version", DataStoreVersions.CURRENT_VERSION, actual.getVersion()); assertEquals("getPath", expected.getPath(), actual.getPath()); assertEquals("getData", expected.getData(), actual.getData()); }