List of usage examples for java.lang Long toHexString
public static String toHexString(long i)
From source file:io.warp10.continuum.egress.EgressFetchHandler.java
@Override public void handle(String target, Request baseRequest, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { boolean fromArchive = false; boolean splitFetch = false; boolean writeTimestamp = false; if (Constants.API_ENDPOINT_FETCH.equals(target)) { baseRequest.setHandled(true);/*from ww w . j a va 2 s .c o m*/ fromArchive = false; } else if (Constants.API_ENDPOINT_AFETCH.equals(target)) { baseRequest.setHandled(true); fromArchive = true; } else if (Constants.API_ENDPOINT_SFETCH.equals(target)) { baseRequest.setHandled(true); splitFetch = true; } else if (Constants.API_ENDPOINT_CHECK.equals(target)) { baseRequest.setHandled(true); resp.setStatus(HttpServletResponse.SC_OK); return; } else { return; } try { // Labels for Sensision Map<String, String> labels = new HashMap<String, String>(); labels.put(SensisionConstants.SENSISION_LABEL_TYPE, target); // // Add CORS header // resp.setHeader("Access-Control-Allow-Origin", "*"); String start = null; String stop = null; long now = Long.MIN_VALUE; long timespan = 0L; String nowParam = null; String timespanParam = null; String dedupParam = null; String showErrorsParam = null; if (splitFetch) { nowParam = req.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_NOW_HEADERX)); timespanParam = req.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TIMESPAN_HEADERX)); showErrorsParam = req.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_SHOW_ERRORS_HEADERX)); } else { start = req.getParameter(Constants.HTTP_PARAM_START); stop = req.getParameter(Constants.HTTP_PARAM_STOP); nowParam = req.getParameter(Constants.HTTP_PARAM_NOW); timespanParam = req.getParameter(Constants.HTTP_PARAM_TIMESPAN); dedupParam = req.getParameter(Constants.HTTP_PARAM_DEDUP); showErrorsParam = req.getParameter(Constants.HTTP_PARAM_SHOW_ERRORS); } String maxDecoderLenParam = req.getParameter(Constants.HTTP_PARAM_MAXSIZE); int maxDecoderLen = null != maxDecoderLenParam ? Integer.parseInt(maxDecoderLenParam) : Constants.DEFAULT_PACKED_MAXSIZE; String suffix = req.getParameter(Constants.HTTP_PARAM_SUFFIX); if (null == suffix) { suffix = Constants.DEFAULT_PACKED_CLASS_SUFFIX; } boolean unpack = null != req.getParameter(Constants.HTTP_PARAM_UNPACK); long chunksize = Long.MAX_VALUE; if (null != req.getParameter(Constants.HTTP_PARAM_CHUNKSIZE)) { chunksize = Long.parseLong(req.getParameter(Constants.HTTP_PARAM_CHUNKSIZE)); } if (chunksize <= 0) { throw new IOException("Invalid chunksize."); } boolean showErrors = null != showErrorsParam; boolean dedup = null != dedupParam && "true".equals(dedupParam); if (null != start && null != stop) { long tsstart = fmt.parseDateTime(start).getMillis() * Constants.TIME_UNITS_PER_MS; long tsstop = fmt.parseDateTime(stop).getMillis() * Constants.TIME_UNITS_PER_MS; if (tsstart < tsstop) { now = tsstop; timespan = tsstop - tsstart; } else { now = tsstart; timespan = tsstart - tsstop; } } else if (null != nowParam && null != timespanParam) { if ("now".equals(nowParam)) { now = TimeSource.getTime(); } else { try { now = Long.parseLong(nowParam); } catch (Exception e) { now = fmt.parseDateTime(nowParam).getMillis() * Constants.TIME_UNITS_PER_MS; } } timespan = Long.parseLong(timespanParam); } if (Long.MIN_VALUE == now) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing now/timespan or start/stop parameters."); return; } String selector = splitFetch ? null : req.getParameter(Constants.HTTP_PARAM_SELECTOR); // // Extract token from header // String token = req.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX)); // If token was not found in header, extract it from the 'token' parameter if (null == token && !splitFetch) { token = req.getParameter(Constants.HTTP_PARAM_TOKEN); } String fetchSig = req.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_FETCH_SIGNATURE)); // // Check token signature if it was provided // boolean signed = false; if (splitFetch) { // Force showErrors showErrors = true; signed = true; } if (null != fetchSig) { if (null != fetchPSK) { String[] subelts = fetchSig.split(":"); if (2 != subelts.length) { throw new IOException("Invalid fetch signature."); } long nowts = System.currentTimeMillis(); long sigts = new BigInteger(subelts[0], 16).longValue(); long sighash = new BigInteger(subelts[1], 16).longValue(); if (nowts - sigts > 10000L) { throw new IOException("Fetch signature has expired."); } // Recompute hash of ts:token String tstoken = Long.toString(sigts) + ":" + token; long checkedhash = SipHashInline.hash24(fetchPSK, tstoken.getBytes(Charsets.ISO_8859_1)); if (checkedhash != sighash) { throw new IOException("Corrupted fetch signature"); } signed = true; } else { throw new IOException("Fetch PreSharedKey is not set."); } } ReadToken rtoken = null; String format = splitFetch ? "wrapper" : req.getParameter(Constants.HTTP_PARAM_FORMAT); if (!splitFetch) { try { rtoken = Tokens.extractReadToken(token); if (rtoken.getHooksSize() > 0) { throw new IOException("Tokens with hooks cannot be used for fetching data."); } } catch (WarpScriptException ee) { throw new IOException(ee); } if (null == rtoken) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Missing token."); return; } } boolean showAttr = "true".equals(req.getParameter(Constants.HTTP_PARAM_SHOWATTR)); boolean sortMeta = "true".equals(req.getParameter(Constants.HTTP_PARAM_SORTMETA)); // // Extract the class and labels selectors // The class selector and label selectors are supposed to have // values which use percent encoding, i.e. explicit percent encoding which // might have been re-encoded using percent encoding when passed as parameter // // Set<Metadata> metadatas = new HashSet<Metadata>(); List<Iterator<Metadata>> iterators = new ArrayList<Iterator<Metadata>>(); if (!splitFetch) { if (null == selector) { throw new IOException("Missing '" + Constants.HTTP_PARAM_SELECTOR + "' parameter."); } String[] selectors = selector.split("\\s+"); for (String sel : selectors) { Matcher m = SELECTOR_RE.matcher(sel); if (!m.matches()) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } String classSelector = URLDecoder.decode(m.group(1), "UTF-8"); String labelsSelection = m.group(2); Map<String, String> labelsSelectors; try { labelsSelectors = GTSHelper.parseLabelsSelectors(labelsSelection); } catch (ParseException pe) { throw new IOException(pe); } // // Force 'producer'/'owner'/'app' from token // labelsSelectors.remove(Constants.PRODUCER_LABEL); labelsSelectors.remove(Constants.OWNER_LABEL); labelsSelectors.remove(Constants.APPLICATION_LABEL); labelsSelectors.putAll(Tokens.labelSelectorsFromReadToken(rtoken)); List<Metadata> metas = null; List<String> clsSels = new ArrayList<String>(); List<Map<String, String>> lblsSels = new ArrayList<Map<String, String>>(); clsSels.add(classSelector); lblsSels.add(labelsSelectors); try { metas = directoryClient.find(clsSels, lblsSels); metadatas.addAll(metas); } catch (Exception e) { // // If metadatas is not empty, create an iterator for it, then clear it // if (!metadatas.isEmpty()) { iterators.add(metadatas.iterator()); metadatas.clear(); } iterators.add(directoryClient.iterator(clsSels, lblsSels)); } } } else { // // Add an iterator which reads splits from the request body // boolean gzipped = false; if (null != req.getHeader("Content-Type") && "application/gzip".equals(req.getHeader("Content-Type"))) { gzipped = true; } BufferedReader br = null; if (gzipped) { GZIPInputStream is = new GZIPInputStream(req.getInputStream()); br = new BufferedReader(new InputStreamReader(is)); } else { br = req.getReader(); } final BufferedReader fbr = br; MetadataIterator iterator = new MetadataIterator() { private List<Metadata> metadatas = new ArrayList<Metadata>(); private boolean done = false; private String lasttoken = ""; @Override public void close() throws Exception { fbr.close(); } @Override public Metadata next() { if (!metadatas.isEmpty()) { Metadata meta = metadatas.get(metadatas.size() - 1); metadatas.remove(metadatas.size() - 1); return meta; } else { if (hasNext()) { return next(); } else { throw new NoSuchElementException(); } } } @Override public boolean hasNext() { if (!metadatas.isEmpty()) { return true; } if (done) { return false; } String line = null; try { line = fbr.readLine(); } catch (IOException ioe) { throw new RuntimeException(ioe); } if (null == line) { done = true; return false; } // // Decode/Unwrap/Deserialize the split // byte[] data = OrderPreservingBase64.decode(line.getBytes(Charsets.US_ASCII)); if (null != fetchAES) { data = CryptoUtils.unwrap(fetchAES, data); } if (null == data) { throw new RuntimeException("Invalid wrapped content."); } TDeserializer deserializer = new TDeserializer(new TCompactProtocol.Factory()); GTSSplit split = new GTSSplit(); try { deserializer.deserialize(split, data); } catch (TException te) { throw new RuntimeException(te); } // // Check the expiry // long instant = System.currentTimeMillis(); if (instant - split.getTimestamp() > maxSplitAge || instant > split.getExpiry()) { throw new RuntimeException("Split has expired."); } this.metadatas.addAll(split.getMetadatas()); // We assume there was at least one metadata instance in the split!!! return true; } }; iterators.add(iterator); } List<Metadata> metas = new ArrayList<Metadata>(); metas.addAll(metadatas); if (!metas.isEmpty()) { iterators.add(metas.iterator()); } // // Loop over the iterators, storing the read metadata to a temporary file encrypted on disk // Data is encrypted using a onetime pad // final byte[] onetimepad = new byte[(int) Math.min(65537, System.currentTimeMillis() % 100000)]; new Random().nextBytes(onetimepad); final File cache = File.createTempFile( Long.toHexString(System.currentTimeMillis()) + "-" + Long.toHexString(System.nanoTime()), ".dircache"); cache.deleteOnExit(); FileWriter writer = new FileWriter(cache); TSerializer serializer = new TSerializer(new TCompactProtocol.Factory()); int padidx = 0; for (Iterator<Metadata> itermeta : iterators) { try { while (itermeta.hasNext()) { Metadata metadata = itermeta.next(); try { byte[] bytes = serializer.serialize(metadata); // Apply onetimepad for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) (bytes[i] ^ onetimepad[padidx++]); if (padidx >= onetimepad.length) { padidx = 0; } } OrderPreservingBase64.encodeToWriter(bytes, writer); writer.write('\n'); } catch (TException te) { } } if (!itermeta.hasNext() && (itermeta instanceof MetadataIterator)) { try { ((MetadataIterator) itermeta).close(); } catch (Exception e) { } } } catch (Throwable t) { throw t; } finally { if (itermeta instanceof MetadataIterator) { try { ((MetadataIterator) itermeta).close(); } catch (Exception e) { } } } } writer.close(); // // Create an iterator based on the cache // MetadataIterator cacheiterator = new MetadataIterator() { BufferedReader reader = new BufferedReader(new FileReader(cache)); private Metadata current = null; private boolean done = false; private TDeserializer deserializer = new TDeserializer(new TCompactProtocol.Factory()); int padidx = 0; @Override public boolean hasNext() { if (done) { return false; } if (null != current) { return true; } try { String line = reader.readLine(); if (null == line) { done = true; return false; } byte[] raw = OrderPreservingBase64.decode(line.getBytes(Charsets.US_ASCII)); // Apply one time pad for (int i = 0; i < raw.length; i++) { raw[i] = (byte) (raw[i] ^ onetimepad[padidx++]); if (padidx >= onetimepad.length) { padidx = 0; } } Metadata metadata = new Metadata(); try { deserializer.deserialize(metadata, raw); this.current = metadata; return true; } catch (TException te) { LOG.error("", te); } } catch (IOException ioe) { LOG.error("", ioe); } return false; } @Override public Metadata next() { if (null != this.current) { Metadata metadata = this.current; this.current = null; return metadata; } else { throw new NoSuchElementException(); } } @Override public void close() throws Exception { this.reader.close(); cache.delete(); } }; iterators.clear(); iterators.add(cacheiterator); metas = new ArrayList<Metadata>(); PrintWriter pw = resp.getWriter(); AtomicReference<Metadata> lastMeta = new AtomicReference<Metadata>(null); AtomicLong lastCount = new AtomicLong(0L); long fetchtimespan = timespan; for (Iterator<Metadata> itermeta : iterators) { while (itermeta.hasNext()) { metas.add(itermeta.next()); // // Access the data store every 'FETCH_BATCHSIZE' GTS or at the end of each iterator // if (metas.size() > FETCH_BATCHSIZE || !itermeta.hasNext()) { try (GTSDecoderIterator iterrsc = storeClient.fetch(rtoken, metas, now, fetchtimespan, fromArchive, writeTimestamp)) { GTSDecoderIterator iter = iterrsc; if (unpack) { iter = new UnpackingGTSDecoderIterator(iter, suffix); timespan = Long.MIN_VALUE + 1; } if ("text".equals(format)) { textDump(pw, iter, now, timespan, false, dedup, signed, showAttr, lastMeta, lastCount, sortMeta); } else if ("fulltext".equals(format)) { textDump(pw, iter, now, timespan, true, dedup, signed, showAttr, lastMeta, lastCount, sortMeta); } else if ("raw".equals(format)) { rawDump(pw, iter, dedup, signed, timespan, lastMeta, lastCount, sortMeta); } else if ("wrapper".equals(format)) { wrapperDump(pw, iter, dedup, signed, fetchPSK, timespan, lastMeta, lastCount); } else if ("json".equals(format)) { jsonDump(pw, iter, now, timespan, dedup, signed, lastMeta, lastCount); } else if ("tsv".equals(format)) { tsvDump(pw, iter, now, timespan, false, dedup, signed, lastMeta, lastCount, sortMeta); } else if ("fulltsv".equals(format)) { tsvDump(pw, iter, now, timespan, true, dedup, signed, lastMeta, lastCount, sortMeta); } else if ("pack".equals(format)) { packedDump(pw, iter, now, timespan, dedup, signed, lastMeta, lastCount, maxDecoderLen, suffix, chunksize, sortMeta); } else if ("null".equals(format)) { nullDump(iter); } else { textDump(pw, iter, now, timespan, false, dedup, signed, showAttr, lastMeta, lastCount, sortMeta); } } catch (Throwable t) { LOG.error("", t); Sensision.update(SensisionConstants.CLASS_WARP_FETCH_ERRORS, Sensision.EMPTY_LABELS, 1); if (showErrors) { pw.println(); StringWriter sw = new StringWriter(); PrintWriter pw2 = new PrintWriter(sw); t.printStackTrace(pw2); pw2.close(); sw.flush(); String error = URLEncoder.encode(sw.toString(), "UTF-8"); pw.println(Constants.EGRESS_FETCH_ERROR_PREFIX + error); } throw new IOException(t); } finally { if (!itermeta.hasNext() && (itermeta instanceof MetadataIterator)) { try { ((MetadataIterator) itermeta).close(); } catch (Exception e) { } } } // // Reset 'metas' // metas.clear(); } } if (!itermeta.hasNext() && (itermeta instanceof MetadataIterator)) { try { ((MetadataIterator) itermeta).close(); } catch (Exception e) { } } } Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_FETCH_REQUESTS, labels, 1); } catch (Exception e) { if (!resp.isCommitted()) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); return; } } }
From source file:VASSAL.chat.node.NodeClient.java
public void initializeControls(ChatServerControls controls) { playerStatusControls.initializeControls(controls); messageBoardControls.initializeControls(controls); roomControls.initializeControls(controls); serverStatusControls.initializeControls(controls); final GameModule g = GameModule.getGameModule(); g.addCommandEncoder(synchEncoder);//from w w w .jav a 2 s . com g.addCommandEncoder(privateChatEncoder); g.addCommandEncoder(soundEncoder); g.addCommandEncoder(inviteEncoder); me.setName((String) g.getPrefs().getValue(GameModule.REAL_NAME)); g.getPrefs().getOption(GameModule.REAL_NAME).addPropertyChangeListener(nameChangeListener); SimpleStatus s = (SimpleStatus) me.getStatus(); s = new SimpleStatus(s.isLooking(), s.isAway(), (String) g.getPrefs().getValue(GameModule.PERSONAL_INFO), Info.getVersion(), s.getIp(), g.getGameVersion() + ((g.getArchiveWriter() == null) ? "" : " (Editing)"), Long.toHexString(g.getCrc())); me.setStatus(s); g.getPrefs().getOption(GameModule.PERSONAL_INFO).addPropertyChangeListener(profileChangeListener); controls.getRoomTree().setCellRenderer(new LockableRoomTreeRenderer()); }
From source file:org.trafodion.dtm.TmAuditTlog.java
public void putSingleRecord(final long lvTransid, final String lvTxState, final Set<TransactionRegionLocation> regions, boolean forced, long recoveryASN) throws Exception { long threadId = Thread.currentThread().getId(); if (LOG.isTraceEnabled()) LOG.trace("putSingleRecord start in thread " + threadId); StringBuilder tableString = new StringBuilder(); String transidString = new String(String.valueOf(lvTransid)); boolean lvResult = true; long lvAsn;// ww w . ja v a 2 s.c o m long startSynch = 0; long endSynch = 0; int lv_lockIndex = 0; int lv_TimeIndex = (timeIndex.getAndIncrement() % 50); long lv_TotalWrites = totalWrites.incrementAndGet(); long lv_TotalRecords = totalRecords.incrementAndGet(); if (regions != null) { // Regions passed in indicate a state record where recovery might be needed following a crash. // To facilitate branch notification we translate the regions into table names that can then // be translated back into new region names following a restart. THis allows us to ensure all // branches reply prior to cleanup Iterator<TransactionRegionLocation> it = regions.iterator(); List<String> tableNameList = new ArrayList<String>(); while (it.hasNext()) { String name = new String(it.next().getRegionInfo().getTable().getNameAsString()); if ((name.length() > 0) && (tableNameList.contains(name) != true)) { // We have a table name not already in the list tableNameList.add(name); tableString.append(","); tableString.append(name); } } if (LOG.isTraceEnabled()) LOG.trace("table names: " + tableString.toString()); } //Create the Put as directed by the hashed key boolean Put p; //create our own hashed key long key = (((lvTransid & tLogHashKey) << tLogHashShiftFactor) + (lvTransid & 0xFFFFFFFF)); lv_lockIndex = (int) (lvTransid & tLogHashKey); if (LOG.isTraceEnabled()) LOG.trace("key: " + key + ", hex: " + Long.toHexString(key) + ", transid: " + lvTransid); p = new Put(Bytes.toBytes(key)); if (recoveryASN == -1) { // This is a normal audit record so we manage the ASN lvAsn = asn.getAndIncrement(); } else { // This is a recovery audit record so use the ASN passed in lvAsn = recoveryASN; } if (LOG.isTraceEnabled()) LOG.trace("transid: " + lvTransid + " state: " + lvTxState + " ASN: " + lvAsn); p.add(TLOG_FAMILY, ASN_STATE, Bytes.toBytes(String.valueOf(lvAsn) + "," + transidString + "," + lvTxState + "," + Bytes.toString(filler) + "," + tableString.toString())); if (recoveryASN != -1) { // We need to send this to a remote Tlog, not our local one, so open the appropriate table HTableInterface recoveryTable; int lv_ownerNid = (int) (lvTransid >> 32); String lv_tLogName = new String("TRAFODION._DTM_.TLOG" + String.valueOf(lv_ownerNid) + "_LOG_" + Integer.toHexString(lv_lockIndex)); HConnection recoveryTableConnection = HConnectionManager.createConnection(this.config); recoveryTable = recoveryTableConnection.getTable(TableName.valueOf(lv_tLogName)); try { recoveryTable.put(p); } catch (Exception e2) { // create record of the exception LOG.error("putSingleRecord Exception in recoveryTable" + e2); e2.printStackTrace(); throw e2; } finally { try { recoveryTable.close(); recoveryTableConnection.close(); } catch (IOException e) { LOG.error("putSingleRecord IOException closing recovery table or connection for table " + lv_tLogName); e.printStackTrace(); } } } else { // THis goes to our local TLOG if (LOG.isTraceEnabled()) LOG.trace("TLOG putSingleRecord synchronizing tlogAuditLock[" + lv_lockIndex + "] in thread " + threadId); startSynch = System.nanoTime(); try { synchronized (tlogAuditLock[lv_lockIndex]) { endSynch = System.nanoTime(); try { if (LOG.isTraceEnabled()) LOG.trace("try table.put " + p); startTimes[lv_TimeIndex] = System.nanoTime(); table[lv_lockIndex].put(p); if ((forced) && (useAutoFlush == false)) { if (LOG.isTraceEnabled()) LOG.trace("flushing commits"); table[lv_lockIndex].flushCommits(); } endTimes[lv_TimeIndex] = System.nanoTime(); } catch (Exception e2) { // create record of the exception LOG.error("putSingleRecord Exception " + e2); e2.printStackTrace(); throw e2; } } // End global synchronization } catch (Exception e) { // create record of the exception LOG.error("Synchronizing on tlogAuditLock[" + lv_lockIndex + "] Exception " + e); e.printStackTrace(); throw e; } if (LOG.isTraceEnabled()) LOG.trace("TLOG putSingleRecord synchronization complete in thread " + threadId); synchTimes[lv_TimeIndex] = endSynch - startSynch; totalSynchTime += synchTimes[lv_TimeIndex]; totalWriteTime += (endTimes[lv_TimeIndex] - startTimes[lv_TimeIndex]); if (synchTimes[lv_TimeIndex] > maxSynchTime) { maxSynchTime = synchTimes[lv_TimeIndex]; } if (synchTimes[lv_TimeIndex] < minSynchTime) { minSynchTime = synchTimes[lv_TimeIndex]; } if ((endTimes[lv_TimeIndex] - startTimes[lv_TimeIndex]) > maxWriteTime) { maxWriteTime = (endTimes[lv_TimeIndex] - startTimes[lv_TimeIndex]); } if ((endTimes[lv_TimeIndex] - startTimes[lv_TimeIndex]) < minWriteTime) { minWriteTime = (endTimes[lv_TimeIndex] - startTimes[lv_TimeIndex]); } if (lv_TimeIndex == 49) { timeIndex.set(1); // Start over so we don't exceed the array size } if (lv_TotalWrites == 59999) { avgWriteTime = (double) (totalWriteTime / lv_TotalWrites); avgSynchTime = (double) (totalSynchTime / lv_TotalWrites); LOG.info("TLog Audit Write Report\n" + " Total records: " + lv_TotalRecords + " in " + lv_TotalWrites + " write operations\n" + " Write time:\n" + " Min: " + minWriteTime / 1000 + " microseconds\n" + " Max: " + maxWriteTime / 1000 + " microseconds\n" + " Avg: " + avgWriteTime / 1000 + " microseconds\n" + " Synch time:\n" + " Min: " + minSynchTime / 1000 + " microseconds\n" + " Max: " + maxSynchTime / 1000 + " microseconds\n" + " Avg: " + avgSynchTime / 1000 + " microseconds\n"); // Start at index 1 since there is no startTimes[0] timeIndex.set(1); endTimes[0] = System.nanoTime(); totalWriteTime = 0; totalSynchTime = 0; totalPrepTime = 0; totalRecords.set(0); totalWrites.set(0); minWriteTime = 50000; // Some arbitrary high value maxWriteTime = 0; minWriteTimeBuffSize = 0; maxWriteTimeBuffSize = 0; minSynchTime = 50000; // Some arbitrary high value maxSynchTime = 0; minPrepTime = 50000; // Some arbitrary high value maxPrepTime = 0; minBufferSize = 1000; // Some arbitrary high value maxBufferSize = 0; } } // End else revoveryASN == -1 if (LOG.isTraceEnabled()) LOG.trace("putSingleRecord exit"); }
From source file:org.apache.bookkeeper.bookie.CreateNewLogTest.java
@Test public void testCreateNewLogWithGaps() throws Exception { ServerConfiguration conf = TestBKConfiguration.newServerConfiguration(); // Creating a new configuration with a number of // ledger directories. conf.setLedgerDirNames(ledgerDirs);/*w w w. j a v a 2 s . c om*/ conf.setEntryLogFilePreAllocationEnabled(false); LedgerDirsManager ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())); EntryLogger el = new EntryLogger(conf, ledgerDirsManager); EntryLogManagerBase entryLogManagerBase = (EntryLogManagerBase) el.getEntryLogManager(); entryLogManagerBase.createNewLog(0L); Assert.assertEquals("previousAllocatedEntryLogId after initialization", 0, el.getPreviousAllocatedEntryLogId()); // Extracted from createNewLog() String logFileName = Long.toHexString(1) + ".log"; File dir = ledgerDirsManager.pickRandomWritableDir(); LOG.info("Picked this directory: {}", dir); File newLogFile = new File(dir, logFileName); newLogFile.createNewFile(); entryLogManagerBase.createNewLog(0L); Assert.assertEquals("previousAllocatedEntryLogId since entrylogid 1 is already taken", 2, el.getPreviousAllocatedEntryLogId()); // Extracted from createNewLog() logFileName = Long.toHexString(3) + ".log"; dir = ledgerDirsManager.pickRandomWritableDir(); LOG.info("Picked this directory: {}", dir); newLogFile = new File(dir, logFileName); newLogFile.createNewFile(); entryLogManagerBase.createNewLog(0L); Assert.assertEquals("previousAllocatedEntryLogId since entrylogid 3 is already taken", 4, el.getPreviousAllocatedEntryLogId()); }
From source file:org.dataconservancy.packaging.tool.impl.AnnotationDrivenPackageStateSerializer.java
/** * Deserializes the identified stream ({@code streamId}) from the supplied input stream into the package state. * If {@code streamId} is {@code null}, then all streams found in the supplied input stream are deserialized to * {@code state}./*ww w .j av a2 s . c o m*/ * <p> * If the specified stream is not found, this method will do nothing. If an unrecognized stream is encountered, it * will be skipped. * </p> * <p> * An unrecognized stream is a Zip entry with a name that is not present in the {@code StreamId enum}. Unrecognized * streams can be encountered when the supplied {@code streamId} is {@code null}. * </p> * * @param state the package state to be populated * @param streamId the stream to be deserialized, may be {@code null} to specify all streams found in the supplied * input stream * @param in the input stream containing the identified {@code streamId} * @throws RuntimeException when there are errors accessing fields of the state using reflection * @throws StreamChecksumMismatch when {@code failOnChecksumMismatch} is {@code true} and a checksum mismatch is * encountered */ void deserialize(PackageState state, StreamId streamId, ZipArchiveInputStream in) { ArchiveEntry entry; Object deserializedStream; boolean all = streamId == null; // deserialize the specified stream identifier (or all stream identifiers if streamId is null) from the // inputStream to the package state try { while ((entry = in.getNextEntry()) != null) { if (entry.getSize() == 0) { // Skip empty entries continue; } if (all || streamId.name().equals(entry.getName())) { if (all) { try { streamId = StreamId.valueOf(entry.getName().toUpperCase()); } catch (IllegalArgumentException e) { LOG.warn(String.format(WARN_UNKNOWN_STREAM, entry.getName().toUpperCase())); continue; } } if (!hasPropertyDescription(streamId)) { throw new NullPointerException(String.format(ERR_MISSING_DESCRIPTOR, streamId)); } if (!hasUnmarshaller(streamId)) { throw new NullPointerException( String.format(ERR_MISSING_SPRINGMARSHALLER, streamId, streamId)); } CRC32CalculatingInputStream crcIn = new CRC32CalculatingInputStream(in); long expectedCrc = ((ZipArchiveEntry) entry).getCrc(); deserializedStream = marshallerMap.get(streamId).getUnmarshaller() .unmarshal(new StreamSource(crcIn)); long actualCrc = crcIn.resetCrc(); if (actualCrc != expectedCrc) { if (failOnChecksumMismatch) { throw new StreamChecksumMismatch(String.format(WARN_CRC_MISMATCH, streamId, Long.toHexString(expectedCrc), Long.toHexString(actualCrc))); } else { LOG.warn(String.format(WARN_CRC_MISMATCH, streamId, Long.toHexString(expectedCrc), Long.toHexString(actualCrc))); } } propertyDescriptors.get(streamId).getWriteMethod().invoke(state, deserializedStream); } } } catch (StreamChecksumMismatch e) { throw e; // don't wrap this exception, throw it as-is per Javadoc } catch (Exception e) { if (streamId == null) { throw new RuntimeException(String.format(ERR_UNMARSHALLING_ARCHIVE, e.getMessage()), e); } else { throw new RuntimeException( String.format(ERR_UNMARSHALLING_STREAMID_ARCHIVE, streamId, e.getMessage()), e); } } }
From source file:com.alibaba.wasp.master.FMaster.java
/** * Initialize all ZK based system trackers. * /*w ww . j ava 2s.c o m*/ * @throws java.io.IOException * @throws InterruptedException */ private void initializeZKBasedSystemTrackers() throws IOException, InterruptedException, KeeperException { this.balancer = LoadBalancerFactory.getLoadBalancer(conf); this.loadBalancerTracker = new LoadBalancerTracker(zooKeeper, this); this.loadBalancerTracker.start(); this.assignmentManager = new AssignmentManager(this, serverManager, this.balancer, this.executorService, this.metricsMaster); zooKeeper.registerListenerFirst(assignmentManager); this.fserverTracker = new FServerTracker(zooKeeper, this, this.serverManager); this.fserverTracker.start(); this.drainingServerTracker = new DrainingServerTracker(zooKeeper, this, this.serverManager); this.drainingServerTracker.start(); this.tableLockManager = new TableLockManager(); // Set the cluster as up. If new FSs, they'll be waiting on this before // going ahead with their startup. boolean wasUp = this.clusterStatusTracker.isClusterUp(); if (!wasUp) this.clusterStatusTracker.setClusterUp(); LOG.info("Server active/primary master; " + this.serverName + ", sessionid=0x" + Long.toHexString(this.zooKeeper.getRecoverableZooKeeper().getSessionId()) + ", cluster-up flag was=" + wasUp); }
From source file:org.apache.flink.runtime.rest.RestServerEndpointITCase.java
private static String generateMultiPartBoundary() { return Long.toHexString(System.currentTimeMillis()); }
From source file:io.orchestrate.client.itest.KvTest.java
@Theory public void patchKey(@ForAll(sampleSize = 10) final String key) { assumeThat(key, not(isEmptyString())); final KvMetadata kvMetadata = insertItem(key, "{}"); String name = Long.toHexString(RAND.nextLong()); final KvMetadata patched = client.kv(collection(), key).patch(JsonPatch.builder().add("name", name).build()) .get();/* w ww . j a v a 2s . c o m*/ assertNotEquals(kvMetadata, patched); final KvObject<ObjectNode> kvObject = client.kv(kvMetadata.getCollection(), kvMetadata.getKey()) .get(ObjectNode.class).get(); assertNotNull(kvMetadata); assertNotNull(kvObject); assertEquals(kvMetadata.getCollection(), kvObject.getCollection()); assertEquals(kvMetadata.getKey(), kvObject.getKey()); assertEquals(patched.getRef(), kvObject.getRef()); assertEquals(name, kvObject.getValue().get("name").asText()); }
From source file:org.geowebcache.GeoWebCacheDispatcher.java
/** * Happy ending, sets the headers and writes the response back to the client. *//*from w w w. j av a2 s. c o m*/ private void writeData(ConveyorTile tile) throws IOException { HttpServletResponse servletResp = tile.servletResp; final HttpServletRequest servletReq = tile.servletReq; final CacheResult cacheResult = tile.getCacheResult(); int httpCode = HttpServletResponse.SC_OK; String mimeType = tile.getMimeType().getMimeType(); Resource blob = tile.getBlob(); servletResp.setHeader("geowebcache-cache-result", String.valueOf(cacheResult)); servletResp.setHeader("geowebcache-tile-index", Arrays.toString(tile.getTileIndex())); long[] tileIndex = tile.getTileIndex(); TileLayer layer = tile.getLayer(); GridSubset gridSubset = layer.getGridSubset(tile.getGridSetId()); BoundingBox tileBounds = gridSubset.boundsFromIndex(tileIndex); servletResp.setHeader("geowebcache-tile-bounds", tileBounds.toString()); servletResp.setHeader("geowebcache-gridset", gridSubset.getName()); servletResp.setHeader("geowebcache-crs", gridSubset.getSRS().toString()); final long tileTimeStamp = tile.getTSCreated(); final String ifModSinceHeader = servletReq.getHeader("If-Modified-Since"); // commons-httpclient's DateUtil can encode and decode timestamps formatted as per RFC-1123, // which is one of the three formats allowed for Last-Modified and If-Modified-Since headers // (e.g. 'Sun, 06 Nov 1994 08:49:37 GMT'). See // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 final String lastModified = org.apache.commons.httpclient.util.DateUtil.formatDate(new Date(tileTimeStamp)); servletResp.setHeader("Last-Modified", lastModified); final Date ifModifiedSince; if (ifModSinceHeader != null && ifModSinceHeader.length() > 0) { try { ifModifiedSince = DateUtil.parseDate(ifModSinceHeader); // the HTTP header has second precision long ifModSinceSeconds = 1000 * (ifModifiedSince.getTime() / 1000); long tileTimeStampSeconds = 1000 * (tileTimeStamp / 1000); if (ifModSinceSeconds >= tileTimeStampSeconds) { httpCode = HttpServletResponse.SC_NOT_MODIFIED; blob = null; } } catch (DateParseException e) { if (log.isDebugEnabled()) { log.debug("Can't parse client's If-Modified-Since header: '" + ifModSinceHeader + "'"); } } } if (httpCode == HttpServletResponse.SC_OK && tile.getLayer().useETags()) { String ifNoneMatch = servletReq.getHeader("If-None-Match"); String hexTag = Long.toHexString(tileTimeStamp); if (ifNoneMatch != null) { if (ifNoneMatch.equals(hexTag)) { httpCode = HttpServletResponse.SC_NOT_MODIFIED; blob = null; } } // If we get here, we want ETags but the client did not have the tile. servletResp.setHeader("ETag", hexTag); } int contentLength = (int) (blob == null ? -1 : blob.getSize()); writeFixedResponse(servletResp, httpCode, mimeType, blob, cacheResult, contentLength); }
From source file:com.wirecard.ezlinkwebservices.services.impl.DebitCommandServiceImpl.java
@Override public DebitCommandRes getDebitCommand(EZLINGWSREQENV parameters) throws DebitCommandFault_Exception { ezlink.info("DC Request received in " + DebitCommandServiceImpl.class.getName()); String merchantNo, merchantTranxRefNo, orderNo, cardNo, termRndNo, CardRndNo, purseData; String xorAmount;/* w w w . j ava 2 s . c o m*/ double amount; int result; boolean debitTraxValidationFlag = false; ETranxLogDto objETranxLogDto; EMerchantDetailsDto objEMerchantDetailsDto; int hostRepeatedCounter = 0; List<ETerminalDataDto> ETerminalDataDtolist; Date updatedDate = new Date(); ETerminalDataDto objAvailableETerminalDataDto; ETerminalDataDto objTerminalDataFromTerminal; TerminalUtil objTerminalUtil; DebitCommandRes objDebitCommandRes = new DebitCommandRes(); //MerchantDtoMapper objMerchantDtoMapper=new MerchantDtoMapper(); try { merchantNo = parameters.getEZLINGWSREQBODY().getDebitCommandReq().getMERCHANTNO(); merchantTranxRefNo = parameters.getEZLINGWSREQBODY().getDebitCommandReq().getMERCHANTREFNO(); orderNo = parameters.getEZLINGWSREQBODY().getDebitCommandReq().getORDERNO(); amount = parameters.getEZLINGWSREQBODY().getDebitCommandReq().getAMOUNT().doubleValue(); cardNo = parameters.getEZLINGWSREQBODY().getDebitCommandReq().getCAN(); termRndNo = parameters.getEZLINGWSREQBODY().getDebitCommandReq().getTERMINALRANDOMNO(); //termRndNo = "CF549C2B7520389C"; CardRndNo = parameters.getEZLINGWSREQBODY().getDebitCommandReq().getCARDRANDOMNO(); purseData = parameters.getEZLINGWSREQBODY().getDebitCommandReq().getPURSEDATA(); // log the response send time and parameters ezlink.info("\n-------DC----REQUEST----------------------------------------------"); ezlink.info("SOURCE ID : " + parameters.getEZLINGWSHEADER().getSOURCEID()); ezlink.info("IP : " + parameters.getEZLINGWSHEADER().getIPADDRESS()); ezlink.info("SEC LEVEL : " + parameters.getEZLINGWSHEADER().getSECURITYLEVEL()); ezlink.info("BODY+++ getDebitCommand : " + new Date()); ezlink.info("merchantNo : " + merchantNo); ezlink.info("merchantTranxRefNo : " + merchantTranxRefNo); ezlink.info("orderNo : " + orderNo); ezlink.info("amount : " + amount); ezlink.info("cardNo : " + cardNo); ezlink.info("Terminal Rnd No : " + termRndNo); ezlink.info("card Rnd No : " + CardRndNo); ezlink.info("Purse Data : " + purseData); ezlink.info("\n-------DC-----REQUEST----------------------------------------------"); } catch (Exception ex) { ezlink.error(new Object(), ex); Logger.getLogger(DebitCommandServiceImpl.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); ezlink.error(new Object(), ex); DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.Common.REQUIRED_FIELD_MISSING); objDebitCommandFault.setFaultInfo(StringConstants.Common.REQUIRED_FIELD_MISSING_INFO); ezlink.info("\n-----DC------EXCEPTION------------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n------DC---------EXCEPTION--------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } try { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); objEMerchantDetailsDto = objEMerchantDetailsDtoMapper.getMerchantByMerchantId(merchantNo); } catch (SQLException ex) { Logger.getLogger(DebitCommandServiceImpl.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); ezlink.error(new Object(), ex); DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.Common.CONNECTION_ISSUE_MESSAGE); objDebitCommandFault.setFaultInfo(StringConstants.Common.CONNECTION_ISSUE_MESSAGE_INFO); ezlink.info("\n------DC-------EXCEPTION----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n-------DC---------EXCEPTION-------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } if (objEMerchantDetailsDto == null) { DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.Common.NO_MERCHANT_AVAILABLE); objDebitCommandFault.setFaultInfo(StringConstants.Common.NO_MERCHANT_AVAILABLE_INFO); ezlink.info("\n-------DC-------EXCEPTION---------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n--------DC-------EXCEPTION--------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } if ((!objEMerchantDetailsDto.getSecurityLevel() .equalsIgnoreCase(parameters.getEZLINGWSHEADER().getSECURITYLEVEL()))) { DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.ExceptionInfo.INVALID_SECURITY_LEVEL_MESSAGE); objDebitCommandFault.setFaultInfo(StringConstants.ExceptionInfo.INVALID_SECURITY_LEVEL_MESSAGE_INFO); ezlink.info("\n-------DC------EXCEPTION----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n-------DC--------EXCEPTION--------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } if ((!objEMerchantDetailsDto.getAccessCode() .equalsIgnoreCase(parameters.getEZLINGWSHEADER().getACCESSCODE()))) { DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.ExceptionInfo.INVALID_ACCESS_CODE_MESSAGE); objDebitCommandFault.setFaultInfo(StringConstants.ExceptionInfo.INVALID_ACCESS_CODE_MESSAGE_INFO); ezlink.info("\n-------DC--------EXCEPTION--------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n--------DC---------EXCEPTION------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } try { //Check transaction available in ETranxLog objETranxLogDto = objETranxLogDtoMapper.validateTransactionLog(merchantNo, merchantTranxRefNo, orderNo, amount); } catch (Exception ex) { Logger.getLogger(DebitCommandServiceImpl.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); ezlink.error(new Object(), ex); DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.Common.CONNECTION_ISSUE_MESSAGE); objDebitCommandFault.setFaultInfo(StringConstants.Common.CONNECTION_ISSUE_MESSAGE_INFO); ezlink.info("\n--------DC-------EXCEPTION--------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n---------DC-------EXCEPTION-------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } //if source id WD.. if (parameters.getEZLINGWSHEADER().getSOURCEID().equals(StringConstants.Common.SOURCE_ID)) { ezlink.info("\n-------DC-------SOURCE ID WD---------------------"); if (null == objETranxLogDto) { DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.ExceptionInfo.NO_TRANSACTION_AVAILABLE_MESSAGE); objDebitCommandFault .setFaultInfo(StringConstants.ExceptionInfo.NO_TRANSACTION_AVAILABLE_MESSAGE_INFO); ezlink.info("\n------DC------EXCEPTION-----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n--------DC-------EXCEPTION--------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } //check status not "Completed" System.out.println("+++++++++++++++Tranx Status from DB : " + objETranxLogDto.getTranxStatus()); System.out.println("+++++++++++++++Response Code from DB : " + objETranxLogDto.getResponseCode()); ezlink.info("++Transaction Status in DB ++: " + objETranxLogDto.getTranxStatus()); ezlink.info("++Response Code in DB ++: " + objETranxLogDto.getResponseCode()); debitTraxValidationFlag = TerminalUtil.ValidateDebitTransaction(objETranxLogDto); if (!debitTraxValidationFlag) { DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.ExceptionInfo.TRANX_COMPLETED_MESSAGE); objDebitCommandFault.setFaultInfo(StringConstants.ExceptionInfo.TRANX_COMPLETED_MESSAGE_INFO); ezlink.info("\n-----DC--------EXCEPTION----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n---------DC---------EXCEPTION-----------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } } //Source ID WD else { //Source ID not 'WD' ezlink.info("\n-------DC-------SOURCE ID NOT WD---------------------"); if (objETranxLogDto != null) { //Record available System.out.println("++++++NOT WD BUT RECORD AVAILABLE++++Tranx Status from DB : " + objETranxLogDto.getTranxStatus()); System.out.println("+++++++++++++++Response Code from DB : " + objETranxLogDto.getResponseCode()); ezlink.info("++Transaction Status in DB ++: " + objETranxLogDto.getTranxStatus()); ezlink.info("++Response Code in DB ++: " + objETranxLogDto.getResponseCode()); debitTraxValidationFlag = TerminalUtil.ValidateDebitTransaction(objETranxLogDto); if (!debitTraxValidationFlag) { insertFaiedTranxDetail(objETranxLogDto.getTranxlogid(), StringConstants.ResponseCode.TRANX_COMPLETED_ALREADY, StringConstants.ExceptionInfo.TRANX_COMPLETED_MESSAGE); DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.ExceptionInfo.TRANX_COMPLETED_MESSAGE); objDebitCommandFault.setFaultInfo(StringConstants.ExceptionInfo.TRANX_COMPLETED_MESSAGE_INFO); ezlink.info("\n-----DC--------EXCEPTION----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n---------DC---------EXCEPTION-----------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } } else { //NOT WD but record not available in tranxlog table in our DB objTerminalUtil = new TerminalUtil(); objETranxLogDto = objTerminalUtil.insertNonWDTransaction(merchantNo, merchantTranxRefNo, orderNo, amount); if (null == objETranxLogDto) { ezlink.info("\n-----NON WC--------TRANXLOG INSERTION FAILED------------"); DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.ExceptionInfo.DB_INSERTION_FAILED_MESSAGE); objDebitCommandFault .setFaultInfo(StringConstants.ExceptionInfo.DB_INSERTION_FAILED_MESSAGE_INFO); ezlink.info("\n-------DC-----EXCEPTION-----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n--------DC------EXCEPTION---------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } } } //-------------------------------------------------------------------------------------------------- //Checking get debit command time from when generating qrcode try { Date generateQrcode = objETranxLogDto.getDatetime(); Date timeout = new Date(generateQrcode.getTime() + 2 * 60 * 1000); if (updatedDate.after(timeout)) { objETranxLogDto.setDatetime(updatedDate); objETranxLogDto.setResponseCode(StringConstants.ResponseCode.TIME_OUT); result = objETranxLogDtoMapper.updateResponseCode(objETranxLogDto); System.out.println(" tranxlog Updation Result : " + result); if (result != 1) { DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.Common.INSERTION_FAILED_MESSAGE); objDebitCommandFault.setFaultInfo(StringConstants.Common.INSERTION_FAILED_MESSAGE_INFO); ezlink.info("\n------DC------EXCEPTION-----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n---------DC-------EXCEPTION-------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } objDebitCommandRes.setORDERNO(objETerminalDataDto.getOrderNo()); objDebitCommandRes.setMERCHANTREFNO(objETerminalDataDto.getMerchantTranxRefNo()); objDebitCommandRes.setCAN(objETerminalDataDto.getCan()); return objDebitCommandRes; } } catch (DebitCommandFault_Exception e) { throw e; } catch (Exception e) { e.printStackTrace(); } try { //Repeated host Count objAvailableETerminalDataDto = objETerminalDataDtoMapper.isRepeatedMerchantTranxRefNo(merchantNo, merchantTranxRefNo, orderNo); } catch (Exception ex) { Logger.getLogger(DebitCommandServiceImpl.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); ezlink.error(new Object(), ex); DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.Common.CONNECTION_ISSUE_MESSAGE); objDebitCommandFault.setFaultInfo(StringConstants.Common.CONNECTION_ISSUE_MESSAGE_INFO); ezlink.info("\n-------DC-----EXCEPTION-----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n--------DC------EXCEPTION---------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } if (objAvailableETerminalDataDto != null) { hostRepeatedCounter = objAvailableETerminalDataDto.getHostCounter(); hostRepeatedCounter++; } objETerminalDataDto.setMerchantNo(merchantNo); objETerminalDataDto.setCan(cardNo); objETerminalDataDto.setOrderNo(orderNo); objETerminalDataDto.setMerchantTranxRefNo(merchantTranxRefNo); objETerminalDataDto.setHostCounter(hostRepeatedCounter); objETerminalDataDto.setAmount(amount); objETerminalDataDto.setUpdatedBy(StringConstants.Common.DBT_CMD_USER); objETerminalDataDto.setUpdatedDate(updatedDate); objETerminalDataDto.setTerminalRndNo(termRndNo); objETerminalDataDto.setCardRndNo(CardRndNo); objETerminalDataDto.setPurseData(purseData); objETerminalDataDto.setTranxlogId(objETranxLogDto.getTranxlogid()); //---------------------------------------------------------------------------------------------------- /* //Updating tranxlog status D try { objETranxLogDto.setDatetime(updatedDate); //objETranxLogDto.setResponseCode(StringConstants.ResponseCode.SUCCESS); result = objETranxLogDtoMapper.updateDebitCommandStatus(objETranxLogDto); System.out.println(" tranxlog Updation Result : " + result); if (result == 0) { DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.Common.INSERTION_FAILED_MESSAGE); objDebitCommandFault.setFaultInfo(StringConstants.Common.INSERTION_FAILED_MESSAGE_INFO); ezlink.info("\n------DC------EXCEPTION-----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n---------DC-------EXCEPTION-------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } } catch (Exception e) { DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.ExceptionInfo.DB_CONNECTION_ERROR_MESSAGE); objDebitCommandFault.setFaultInfo(StringConstants.ExceptionInfo.DB_CONNECTION_ERROR_MESSAGE_INFO); e.printStackTrace(); ezlink.error(new Object(), e); ezlink.info("\n-------DC-----EXCEPTION-----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n-------DC-------EXCEPTION---------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } */ //---------------------------------------------------------------------------------------------------- try { //objETerminalDataDto = TerminalUtil.getDebitCommandFromTerminal(objETerminalDataDto); SerialManager objSerialManager = new SerialManager(); //String xorAmount="FFFFFE"; BigDecimal beforeAmt = new BigDecimal( parameters.getEZLINGWSREQBODY().getDebitCommandReq().getAMOUNT().doubleValue()).setScale(2, RoundingMode.HALF_DOWN); System.out.println("AMOUNT BEFORE : " + beforeAmt); BigDecimal amt = new BigDecimal( parameters.getEZLINGWSREQBODY().getDebitCommandReq().getAMOUNT().doubleValue()) .setScale(2, RoundingMode.HALF_DOWN).subtract(new BigDecimal("0.01")); System.out.println("AMOUNT After -0.01 : " + amt); String amountForXor = String.valueOf(amt).replace(".", ""); String amountForHexXor = Long.toHexString(Long.valueOf(amountForXor)); ezlink.info("Amount for HEX XOR : " + amountForHexXor); System.out.println("AMOUNT For Hex XOR : " + amountForHexXor); xorAmount = TerminalUtil.strXor(amountForHexXor, StringConstants.Common.XOR_FORMAT); ezlink.info("Amount in XOR : " + xorAmount); System.out.println("AMOUNT IN XOR : " + xorAmount); ezlink.info("\n-----DC----------START of Serial Manager--------------------"); System.out.println( "---------------START of Serial Manager -----------------------------------------------------------"); System.out.println("++++++++++TERMINAL RANDOM NO++++++++++++++++++++++++++++ : " + termRndNo); ezlink.info("---------------TERMINAL RANDOM NO -----------: " + termRndNo); long serialReqTime = System.currentTimeMillis(); System.out.println("++++++++SerialManager REQUEST time :+++++ " + serialReqTime); synchronized (this) { objTerminalDataFromTerminal = objSerialManager.getDebitCmd(CardRndNo, termRndNo, xorAmount, purseData); } long serialResTime = System.currentTimeMillis(); System.out.println("+++++++SerialManager Response time :++++++++ " + serialResTime); long timeTaken = serialResTime - serialReqTime; System.out.println("+++++++++Time taken to Serve within SERIALMANAGER +++++++ : " + timeTaken); if (null == objTerminalDataFromTerminal) { insertFaiedTranxDetail(objETranxLogDto.getTranxlogid(), StringConstants.ResponseCode.TERMINAL_CONNECTION_FAILED, StringConstants.ExceptionInfo.TERMINAL_CONNECTION_ERROR_MESSAGE); System.out.println("---------------Not recieving Debit Command from terminal -----------"); ezlink.info("---------------Not recieving Debit Command from terminal -----------"); DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.ExceptionInfo.TERMINAL_CONNECTION_ERROR_MESSAGE); objDebitCommandFault .setFaultInfo(StringConstants.ExceptionInfo.TERMINAL_CONNECTION_ERROR_MESSAGE_INFO); ezlink.info("\n------DC----EXCEPTION-------------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n-------DC-----EXCEPTION-----------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } System.out.println( "---------------END of Serial Manager -----------------------------------------------------------"); ezlink.info("\n-----DC----------END of Serial Manager--------------------"); System.out.println("+++Debit Command ++++" + objTerminalDataFromTerminal.getDebitCmd()); objETerminalDataDto.setDebitCmd(objTerminalDataFromTerminal.getDebitCmd()); objETerminalDataDto.setTerminalSessionKey(objTerminalDataFromTerminal.getTerminalSessionKey()); objETerminalDataDto.setDebitSessionKey(objTerminalDataFromTerminal.getDebitSessionKey()); objETerminalDataDto.setEzLinkString(objTerminalDataFromTerminal.getEzLinkString()); System.out.println("++++" + objETerminalDataDto.toString()); ETerminalDataDtolist = objETerminalDataDtoMapper.isRecordAvailable(merchantNo, merchantTranxRefNo, orderNo); System.out.println("SIZE : " + ETerminalDataDtolist.size()); if (ETerminalDataDtolist.isEmpty()) { result = objETerminalDataDtoMapper.insert(objETerminalDataDto); System.out.println(" Insertion Result : " + result); } else { objETerminalDataDto.setSno(ETerminalDataDtolist.get(0).getSno()); result = objETerminalDataDtoMapper.updateETerminalDataBySNo(objETerminalDataDto); System.out.println(" Updation Result : " + result); } } catch (Exception e) { insertFaiedTranxDetail(objETranxLogDto.getTranxlogid(), StringConstants.ResponseCode.TERMINAL_CONNECTION_FAILED, StringConstants.ExceptionInfo.TERMINAL_CONNECTION_ERROR_MESSAGE); DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.ExceptionInfo.TERMINAL_CONNECTION_ERROR_MESSAGE); objDebitCommandFault.setFaultInfo(StringConstants.ExceptionInfo.TERMINAL_CONNECTION_ERROR_MESSAGE_INFO); e.printStackTrace(); ezlink.error(new Object(), e); ezlink.info("\n------DC----EXCEPTION-------------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n-------DC-----EXCEPTION-----------------------"); //--------------------------------------------------------------------------------------------------- //Updating Terminal COnnection failed response code try { objETranxLogDto.setDatetime(updatedDate); objETranxLogDto.setResponseCode(StringConstants.ResponseCode.TERMINAL_CONNECTION_FAILED); result = objETranxLogDtoMapper.updateResponseCode(objETranxLogDto); System.out.println(" tranxlog Updation Result : " + result); if (result != 1) { DebitCommandFault objTerminalFailedDebitCommandFault = new DebitCommandFault(); objTerminalFailedDebitCommandFault.setMessage(StringConstants.Common.INSERTION_FAILED_MESSAGE); objTerminalFailedDebitCommandFault .setFaultInfo(StringConstants.Common.INSERTION_FAILED_MESSAGE_INFO); ezlink.info("\n------DC------EXCEPTION-----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objTerminalFailedDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objTerminalFailedDebitCommandFault.getFaultInfo()); ezlink.info("\n---------DC-------EXCEPTION-------------------"); throw new DebitCommandFault_Exception(objTerminalFailedDebitCommandFault.getMessage(), objTerminalFailedDebitCommandFault); } else { objTerminalUtil = new TerminalUtil(); if (result != 1) { DebitCommandFault objTranxDetailDebitCommandFault = new DebitCommandFault(); objTranxDetailDebitCommandFault.setMessage(StringConstants.Common.INSERTION_FAILED_MESSAGE); objTranxDetailDebitCommandFault .setFaultInfo(StringConstants.Common.INSERTION_FAILED_MESSAGE_INFO); ezlink.info("\n------DC--TRANX DETAIL----EXCEPTION-----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n---------DC-------EXCEPTION-------------------"); throw new DebitCommandFault_Exception(objTranxDetailDebitCommandFault.getMessage(), objTranxDetailDebitCommandFault); } } } catch (DebitCommandFault_Exception ex) { throw ex; } catch (Exception ex) { DebitCommandFault objSQLDebitCommandFault = new DebitCommandFault(); objSQLDebitCommandFault.setMessage(StringConstants.ExceptionInfo.DB_CONNECTION_ERROR_MESSAGE); objSQLDebitCommandFault .setFaultInfo(StringConstants.ExceptionInfo.DB_CONNECTION_ERROR_MESSAGE_INFO); ex.printStackTrace(); ezlink.error(new Object(), ex); ezlink.info("\n-------DC-----EXCEPTION-----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objSQLDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objSQLDebitCommandFault.getFaultInfo()); ezlink.info("\n-------DC-------EXCEPTION---------------------"); throw new DebitCommandFault_Exception(objSQLDebitCommandFault.getMessage(), objSQLDebitCommandFault); } throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } //Transaction detail insertion failed if (result == 0) { DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.Common.INSERTION_FAILED_MESSAGE); objDebitCommandFault.setFaultInfo(StringConstants.Common.INSERTION_FAILED_MESSAGE_INFO); ezlink.info("\n-----DC-------EXCEPTION-----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n-----DC--------EXCEPTION----------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } //--------------------------------------------------------------------------------------------------- //Updating success response code try { objETranxLogDto.setDatetime(updatedDate); objETranxLogDto.setResponseCode(StringConstants.ResponseCode.SUCCESS); result = objETranxLogDtoMapper.updateDebitCommandStatus(objETranxLogDto); System.out.println(" tranxlog Updation Result : " + result); if (result != 1) { DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.Common.INSERTION_FAILED_MESSAGE); objDebitCommandFault.setFaultInfo(StringConstants.Common.INSERTION_FAILED_MESSAGE_INFO); ezlink.info("\n------DC------EXCEPTION-----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n---------DC-------EXCEPTION-------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } else { objTerminalUtil = new TerminalUtil(); result = objTerminalUtil.insertTransactionDetail(objETranxLogDto.getTranxlogid(), StringConstants.Common.TRANX_TYPE_DEBIT, StringConstants.ResponseCode.SUCCESS, StringConstants.Common.STATUS_SUCCESS); if (result != 1) { DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.Common.INSERTION_FAILED_MESSAGE); objDebitCommandFault.setFaultInfo(StringConstants.Common.INSERTION_FAILED_MESSAGE_INFO); ezlink.info("\n------DC--TRANX DETAIL----EXCEPTION-----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n---------DC-------EXCEPTION-------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } } } catch (DebitCommandFault_Exception e) { throw e; } catch (Exception e) { DebitCommandFault objDebitCommandFault = new DebitCommandFault(); objDebitCommandFault.setMessage(StringConstants.ExceptionInfo.DB_CONNECTION_ERROR_MESSAGE); objDebitCommandFault.setFaultInfo(StringConstants.ExceptionInfo.DB_CONNECTION_ERROR_MESSAGE_INFO); e.printStackTrace(); ezlink.error(new Object(), e); ezlink.info("\n-------DC-----EXCEPTION-----------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Status : " + objDebitCommandFault.getMessage()); ezlink.info("Remarks : " + objDebitCommandFault.getFaultInfo()); ezlink.info("\n-------DC-------EXCEPTION---------------------"); throw new DebitCommandFault_Exception(objDebitCommandFault.getMessage(), objDebitCommandFault); } objDebitCommandRes.setORDERNO(objETerminalDataDto.getOrderNo()); objDebitCommandRes.setMERCHANTREFNO(objETerminalDataDto.getMerchantTranxRefNo()); objDebitCommandRes.setCAN(objETerminalDataDto.getCan()); objDebitCommandRes.setDEBITCOMMAND(objETerminalDataDto.getDebitCmd()); ezlink.info("\n-------DC-------RESPONSE---------------------"); ezlink.info("Response sent from getDebitCommand : " + new Date()); ezlink.info("Order No : " + objDebitCommandRes.getORDERNO()); ezlink.info("Merchant Ref no : " + objDebitCommandRes.getMERCHANTREFNO()); ezlink.info("CAN: " + objDebitCommandRes.getCAN()); ezlink.info("Debit Command : " + objDebitCommandRes.getDEBITCOMMAND()); ezlink.info("\n-------DC-------RESPONSE---------------------"); ezlink.info("\n-------DC-------PURSE DATA---------------" + purseData); result = objTerminalUtil.insertTransactionDetail(objETranxLogDto.getTranxlogid(), StringConstants.Common.TRANX_TYPE_DEBIT, StringConstants.ResponseCode.SUCCESS, StringConstants.Common.STATUS_SUCCESS); return objDebitCommandRes; }