List of usage examples for java.util Map toString
public String toString()
From source file:net.yacy.peers.Protocol.java
/** * this is called to enrich the seed information by - own address (if peer is behind a nat/router) - check * peer type (virgin/junior/senior/principal) to do this, we send a 'Hello' to another peer this carries * the following information: 'iam' - own hash 'youare' - remote hash, to verify that we are correct 'key' * - a session key that the remote peer may use to answer and the own seed string we expect the following * information to be send back: - 'yourip' the ip of the connection peer (we) - 'yourtype' the type of * this peer that the other peer checked by asking for a specific word and the remote seed string one * exceptional failure case is when we know the other's peers hash, the other peers responds correctly but * they appear to be another peer by comparisment of the other peer's hash this works of course only if we * know the other peer's hash./*from w w w. j a v a 2 s .c o m*/ * * @return the number of new seeds */ public static Map<String, String> hello(final Seed mySeed, final PeerActions peerActions, final MultiProtocolURL targetBaseURL, final String targetHash) { Map<String, String> result = null; final String salt = crypt.randomSalt(); long responseTime = Long.MAX_VALUE; byte[] content = null; try { // generate request final Map<String, ContentBody> parts = basicRequestParts(Switchboard.getSwitchboard(), null, salt); parts.put("count", UTF8.StringBody("20")); parts.put("magic", UTF8.StringBody(Long.toString(Network.magic))); parts.put("seed", UTF8.StringBody(mySeed.genSeedStr(salt))); // send request final long start = System.currentTimeMillis(); // final byte[] content = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + address + "/yacy/hello.html"), 30000, yacySeed.b64Hash2hexHash(otherHash) + ".yacyh", parts); final HTTPClient httpClient = new HTTPClient(ClientIdentification.yacyInternetCrawlerAgent, 30000); content = httpClient.POSTbytes(new MultiProtocolURL(targetBaseURL, "/yacy/hello.html"), Seed.b64Hash2hexHash(targetHash) + ".yacyh", parts, false, true); responseTime = System.currentTimeMillis() - start; result = FileUtils.table(content); } catch (final Exception e) { if (Thread.currentThread().isInterrupted()) { Network.log.info("yacyClient.hello thread '" + Thread.currentThread().getName() + "' interrupted."); return null; } Network.log.info("yacyClient.hello thread '" + Thread.currentThread().getName() + "', peer " + targetBaseURL + "; exception: " + e.getMessage()); // try again (go into loop) result = null; } if (result == null || result.size() == 0) { Network.log.info("yacyClient.hello result error: " + ((result == null) ? "result null" : ("result=" + result.toString()))); return null; } Network.log.info("yacyClient.hello thread '" + Thread.currentThread().getName() + "' contacted peer at " + targetBaseURL + ", received " + ((content == null) ? "null" : content.length) + " bytes, time = " + responseTime + " milliseconds"); // check consistency with expectation Seed otherPeer = null; String seed; if ((targetHash != null) && (targetHash.length() > 0) && ((seed = result.get("seed0")) != null)) { if (seed.length() > Seed.maxsize) { Network.log.info("hello/client 0: rejected contacting seed; too large (" + seed.length() + " > " + Seed.maxsize + ")"); } else { try { // patch the remote peer address to avoid that remote peers spoof the network with wrong addresses String host = Domains.stripToHostName(targetBaseURL.getHost()); InetAddress ie = Domains.dnsResolve(host); otherPeer = Seed.genRemoteSeed(seed, false, ie.getHostAddress()); if (!otherPeer.hash.equals(targetHash)) { Network.log.info("yacyClient.hello: consistency error: otherPeer.hash = " + otherPeer.hash + ", otherHash = " + targetHash); return null; // no success } } catch (final IOException e) { Network.log.info("yacyClient.hello: consistency error: other seed bad:" + e.getMessage() + ", seed=" + seed); return null; // no success } } } // get access type response String mytype = result.get(Seed.YOURTYPE); if (mytype == null) { mytype = ""; } // set my own seed according to new information // we overwrite our own IP number only if (serverCore.useStaticIP) { mySeed.setIPs(Switchboard.getSwitchboard().myPublicIPs()); } else { final String myIP = result.get("yourip"); if (myIP == null) { Network.log.info( "yacyClient.hello result error: Peer sent incompleet hello message (key yourip is missing)"); return null; // no success } // with the IPv6 extension, this may contain several ips, separated by comma ',' HashSet<String> h = new HashSet<>(); for (String s : CommonPattern.COMMA.split(myIP)) { if (s.length() > 0 && Seed.isProperIP(s)) h.add(s); } if (h.size() > 0) mySeed.setIPs(h); } mySeed.setFlagRootNode((mytype.equals(Seed.PEERTYPE_SENIOR) || mytype.equals(Seed.PEERTYPE_PRINCIPAL)) && Switchboard.getSwitchboard().index.fulltext().connectedLocalSolr() && responseTime < 1000 && Domains.isThisHostIP(mySeed.getIPs())); // change our seed-type final Accessible accessible = new Accessible(); if (mytype.equals(Seed.PEERTYPE_SENIOR) || mytype.equals(Seed.PEERTYPE_PRINCIPAL)) { accessible.IWasAccessed = true; if (mySeed.isPrincipal()) { mytype = Seed.PEERTYPE_PRINCIPAL; } } else { accessible.IWasAccessed = false; } accessible.lastUpdated = System.currentTimeMillis(); Network.amIAccessibleDB.put(targetHash, accessible); /* * If we were reported as junior we have to check if your port forwarding channel is broken * If this is true we try to reconnect the sch channel to the remote server now. */ if (mytype.equalsIgnoreCase(Seed.PEERTYPE_JUNIOR)) { Network.log.info("yacyClient.hello: Peer '" + ((otherPeer == null) ? "unknown" : otherPeer.getName()) + "' reported us as junior."); } else if ((mytype.equalsIgnoreCase(Seed.PEERTYPE_SENIOR)) || (mytype.equalsIgnoreCase(Seed.PEERTYPE_PRINCIPAL))) { if (Network.log.isFine()) { Network.log .fine("yacyClient.hello: Peer '" + ((otherPeer == null) ? "unknown" : otherPeer.getName()) + "' reported us as " + mytype + ", accepted other peer."); } } else { // wrong type report if (Network.log.isFine()) { Network.log .fine("yacyClient.hello: Peer '" + ((otherPeer == null) ? "unknown" : otherPeer.getName()) + "' reported us as " + mytype + ", rejecting other peer."); } return null; } if (mySeed.orVirgin().equals(Seed.PEERTYPE_VIRGIN)) { mySeed.put(Seed.PEERTYPE, mytype); } final String error = mySeed.isProper(true); if (error != null) { Network.log.warn("yacyClient.hello mySeed error - not proper: " + error); return null; } //final Date remoteTime = yacyCore.parseUniversalDate((String) result.get(yacySeed.MYTIME)); // read remote time // read the seeds that the peer returned and integrate them into own database int i = 0; String seedStr; Seed s; final int connectedBefore = peerActions.sizeConnected(); while ((seedStr = result.get("seed" + i++)) != null) { // integrate new seed into own database // the first seed, "seed0" is the seed of the responding peer if (seedStr.length() > Seed.maxsize) { Network.log.info("hello/client: rejected contacting seed; too large (" + seedStr.length() + " > " + Seed.maxsize + ")"); } else { try { if (i == 1) { String host = Domains.stripToHostName(targetBaseURL.getHost()); InetAddress ia = Domains.dnsResolve(host); if (ia == null) continue; host = ia.getHostAddress(); // the actual address of the target as we had been successful when contacting them is patched here s = Seed.genRemoteSeed(seedStr, false, host); } else { s = Seed.genRemoteSeed(seedStr, false, null); } peerActions.peerArrival(s, (i == 1)); } catch (final IOException e) { Network.log.info("hello/client: rejected contacting seed; bad (" + e.getMessage() + ")"); } } } final int connectedAfter = peerActions.sizeConnected(); // update event tracker EventTracker.update(EventTracker.EClass.PEERPING, new ProfilingGraph.EventPing(mySeed.getName(), targetHash, true, connectedAfter - connectedBefore), false); return result; }
From source file:azad.hallaji.farzad.com.masirezendegi.PageVirayesh.java
void postgetData() { ProgressBar progressbarsandaha = (ProgressBar) findViewById(R.id.progressbarsandaha); progressbarsandaha.setVisibility(View.VISIBLE); MyRequestQueue = Volley.newRequestQueue(this); String url = "http://telyar.dmedia.ir/webservice/Edit_profile/"; StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override/*www. j a va2 s . c o m*/ public void onResponse(String response) { Log.i("dfvflgnkjdfd", response); try { JSONObject jsonObject = new JSONObject(response); jostaruzunueymahziba(jsonObject.getString("Message")); //Toast.makeText(getApplicationContext(),jsonObject.getString("Message"), Toast.LENGTH_LONG).show(); } catch (JSONException e) { e.printStackTrace(); } //Log.i("aladffgree", response); ProgressBar progressbarsandaha = (ProgressBar) findViewById(R.id.progressbarsandaha); progressbarsandaha.setVisibility(View.INVISIBLE); } }, new Response.ErrorListener() { //Create an error listener to handle errors appropriately. @Override public void onErrorResponse(VolleyError error) { //This code is executed if there is an error. } }) { protected Map<String, String> getParams() { Map<String, String> p = new HashMap<String, String>(); try { p.put("name", namexanivadeEdit.getText().toString()); //p.setParam("name",namexanivadeEdit.getText().toString()); } catch (Exception ignored) { //p.setParam("familyname",""); // p.put("name", " "); } p.put("userid", GlobalVar.getUserID()); try { p.put("email", emailEdit.getText().toString()); } catch (Exception ignored) { p.put("email", " "); } try { p.put("gender", sexEdit.getText().toString()); } catch (Exception ignored) { p.put("gender", " "); } try { p.put("telephone", shomareteleEdit.getText().toString()); } catch (Exception ignored) { p.put("telephone", " "); } try { p.put("pic", selectedImageString); //Log.i("asssasasa",selectedImageString); } catch (Exception ignored) { p.put("pic", " "); } try { p.put("aboutme", aboutmeEdit.getText().toString()); } catch (Exception ignored) { p.put("aboutme", " "); } try { p.put("costpermin", costperminEdit.getText().toString()); } catch (Exception ignored) { p.put("costpermin", ""); } try { p.put("dialect", dialtecEdit.getText().toString()); } catch (Exception ignored) { p.put("dialect", ""); } try { p.put("advisermaxtim", maxtimeEdit.getText().toString()); } catch (Exception ignored) { p.put("advisermaxtim", " "); } try { p.put("license", " "); } catch (Exception ignored) { p.put("license", " "); } try { p.put("tag", barchasbEdit.getText().toString()); } catch (Exception ignored) { p.put("tag", " "); } //Log.i("aladffgree", "gedir ba"); Log.i("dfvflgnkjdfd", p.toString()); return p; } @Override protected void onFinish() { ProgressBar progressbarsandaha = (ProgressBar) findViewById(R.id.progressbarsandaha); progressbarsandaha.setVisibility(View.INVISIBLE); } }; MyRequestQueue.add(MyStringRequest); }
From source file:org.metis.push.PusherBean.java
@Override /**/*from www. ja v a2s. c o m*/ * This method handles an incoming message from the web socket client. */ public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { if (session == null) { LOG.error(getBeanName() + ": null session"); throw new Exception(getBeanName() + ":handleTextMessage, null session was received"); } // the session should be in the registry WdsSocketSession wdsSession = getWdsSessions().get(session.getId()); if (wdsSession == null) { LOG.error(getBeanName() + ":handleTextMessage, session with this id is not in registry: " + session.getId()); session.close(new CloseStatus(SERVER_ERROR.getCode(), "ERROR, session with this id not in registry: " + session.getId())); return; } // some sort of message should have been received if (message == null) { LOG.error(getBeanName() + ":handleTextMessage, null message parameter"); session.close(new CloseStatus(POLICY_VIOLATION.getCode(), "ERROR, session with this id gave a null message " + "parameter: " + session.getId())); return; } // we're supposed to receive a JSON object String jsonMsg = message.getPayload(); if (jsonMsg == null) { LOG.error(getBeanName() + ":handleTextMessage, getPayload returns null or empty string"); session.close(new CloseStatus(POLICY_VIOLATION.getCode(), "ERROR, session with this id did not return a payload: " + session.getId())); return; } if (jsonMsg.isEmpty()) { LOG.error(getBeanName() + ":handleTextMessage, getPayload returns zero-length string"); session.close(new CloseStatus(POLICY_VIOLATION.getCode(), "ERROR, session with this id returns zero-length payload: " + session.getId())); return; } // dump the request if trace is on if (LOG.isTraceEnabled()) { LOG.trace(getBeanName() + ":***** processing new request *****"); LOG.trace(getBeanName() + ":session id = " + session.getId()); LOG.trace(getBeanName() + ":session remote address = " + session.getRemoteAddress().toString()); LOG.trace(getBeanName() + ":session uri = " + session.getUri().toString()); LOG.trace(getBeanName() + ":session json object = " + jsonMsg); } // parse the json object List<Map<String, String>> jParams = null; try { jParams = Utils.parseJson(jsonMsg); } catch (Exception exc) { LOG.error(getBeanName() + ":caught this " + "exception while parsing json object: " + exc.toString()); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); if (exc.getCause() != null) { LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString()); LOG.error(getBeanName() + ": causing exception stack trace follows:"); dumpStackTrace(exc.getCause().getStackTrace()); } session.close(new CloseStatus(SERVER_ERROR.getCode(), "ERROR, got this json parsing exception: " + exc.getMessage())); return; } if (jParams == null || jParams.isEmpty()) { LOG.error(getBeanName() + ":json parser returns null or " + "empty json array"); session.close( new CloseStatus(SERVER_ERROR.getCode(), "ERROR, json parser returns null or empty json array")); return; } // if trace is on, dump the params (if any) to the log if (LOG.isDebugEnabled()) { LOG.debug( getBeanName() + ": handleRequestInternal, received these params: " + jParams.get(0).toString()); } // get the command portion of the json message Map<String, String> map = jParams.get(0); String command = map.remove(WS_COMMAND); if (command == null) { LOG.error(getBeanName() + ":command field not present"); session.close(POLICY_VIOLATION); session.close(new CloseStatus(POLICY_VIOLATION.getCode(), "ERROR, command string not present or improperly set: " + command)); return; } if (!command.equals(WS_SUBSCRIBE) && !command.equals(WS_PING)) { LOG.error(getBeanName() + ":received this unknown command = " + command); session.close(POLICY_VIOLATION); session.close(new CloseStatus(POLICY_VIOLATION.getCode(), "ERROR, received this unknown command = " + command)); return; } // Get the SQL Job, if any, that this session is currently subscribed to SqlJob job = wdsSession.getMyJob(); // if this is a ping command, return session's current subscription if (command.equals(WS_PING)) { LOG.debug(getBeanName() + ":received ping command"); List<Map<String, Object>> response = new ArrayList<Map<String, Object>>(); Map<String, Object> map0 = new HashMap<String, Object>(); if (job != null) { LOG.debug(getBeanName() + ": client is subscribed"); map0.put(WS_STATUS, WS_SUBSCRIBED); map = job.getParams(); if (map != null && !map.isEmpty()) { for (String key : map.keySet()) { map0.put(key, map.get(key)); } } } else { LOG.debug(getBeanName() + ": client is not subscribed"); map0.put(WS_STATUS, WS_OK); } response.add(map0); // send response back to client session.sendMessage(new TextMessage(Utils.generateJson(response))); return; } // find a sql statement that matches the incoming session request's // params SqlStmnt sqlStmnt = (map == null || map.isEmpty()) ? SqlStmnt.getMatch(getSqlStmnts4Get(), null) : SqlStmnt.getMatch(getSqlStmnts4Get(), map.keySet()); // if getMatch could not find a match, then return error to client if (sqlStmnt == null) { LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this map: " + map.toString()); List<Map<String, Object>> response = new ArrayList<Map<String, Object>>(); Map<String, Object> map0 = new HashMap<String, Object>(); if (map != null && !map.isEmpty()) { for (String key : map.keySet()) { map0.put(key, map.get(key)); } } map0.put(WS_STATUS, WS_NOT_FOUND); // send response back to client session.sendMessage(new TextMessage(Utils.generateJson(response))); return; } // other than a ping, the only other command from the client is a // subscription command // Does this session already exist in one of the sql jobs? Note that the // client can switch subscriptions. if (job != null) { // the session pertains to a job, but does that job's map match // that of this session's subscription request if (job.isParamMatch(map)) { // if so, we're done return; } else { // else remove this session from that job - the client is // switching subscriptions job.removeSession(wdsSession.getId()); } } mainLock.lock(); try { // if we've gotten this far, the session does not pertain to a job // or it is a subscription change. so we now need to find an // existing job whose params match that of the incoming session. if // no job was found, then create and start one if (sqlStmnt.findSqlJob(map, wdsSession) == null) { sqlStmnt.createSqlJob(map, wdsSession); } } finally { mainLock.unlock(); } }
From source file:io.openvidu.test.e2e.OpenViduTestAppE2eTest.java
private boolean recordedFileFine(File file, Recording recording) throws IOException { this.checkMultimediaFile(file, recording.hasAudio(), recording.hasVideo(), recording.getDuration(), recording.getResolution(), "aac", "h264", true); boolean isFine = false; Picture frame;/*from ww w. j a v a2s . c o m*/ try { // Get a frame at 75% duration and check that it has the expected color frame = FrameGrab.getFrameAtSec(file, (double) (recording.getDuration() * 0.75)); BufferedImage image = AWTUtil.toBufferedImage(frame); Map<String, Long> colorMap = this.averageColor(image); String realResolution = image.getWidth() + "x" + image.getHeight(); Assert.assertEquals("Resolution (" + recording.getResolution() + ") of recording entity is not equal to real video resolution (" + realResolution + ")", recording.getResolution(), realResolution); log.info("Recording map color: {}", colorMap.toString()); isFine = this.checkVideoAverageRgbGreen(colorMap); } catch (IOException | JCodecException e) { log.warn("Error getting frame from video recording: {}", e.getMessage()); isFine = false; } return isFine; }
From source file:com.netflix.nicobar.core.persistence.ArchiveRepositoryTest.java
/** * Test insert, update, delete/*from w w w . j a v a2 s . c o m*/ */ @Test public void testRoundTrip() throws Exception { ArchiveRepository repository = createRepository(); JarScriptArchive jarScriptArchive = new JarScriptArchive.Builder(testArchiveJarFile).build(); ModuleId testModuleId = TEST_MODULE_SPEC_JAR.getModuleId(); repository.insertArchive(jarScriptArchive); Map<ModuleId, Long> archiveUpdateTimes = repository.getDefaultView().getArchiveUpdateTimes(); long expectedUpdateTime = Files.getLastModifiedTime(testArchiveJarFile).toMillis(); assertEquals(archiveUpdateTimes, Collections.singletonMap(testModuleId, expectedUpdateTime)); // assert getScriptArchives Set<ScriptArchive> scriptArchives = repository.getScriptArchives(archiveUpdateTimes.keySet()); assertEquals(scriptArchives.size(), 1, scriptArchives.toString()); ScriptArchive scriptArchive = scriptArchives.iterator().next(); assertEquals(scriptArchive.getModuleSpec().getModuleId(), testModuleId); assertEquals(scriptArchive.getCreateTime(), expectedUpdateTime); // assert getArchiveSummaries List<ArchiveSummary> archiveSummaries = repository.getDefaultView().getArchiveSummaries(); assertEquals(archiveSummaries.size(), 1); ArchiveSummary archiveSummary = archiveSummaries.get(0); assertEquals(archiveSummary.getModuleId(), testModuleId); assertEquals(archiveSummary.getLastUpdateTime(), expectedUpdateTime); // assert getRepositorySummary RepositorySummary repositorySummary = repository.getDefaultView().getRepositorySummary(); assertNotNull(repositorySummary); assertEquals(repositorySummary.getArchiveCount(), 1); assertEquals(repositorySummary.getLastUpdated(), expectedUpdateTime); // advance the timestamp by 10 seconds and update expectedUpdateTime = expectedUpdateTime + 10000; Files.setLastModifiedTime(testArchiveJarFile, FileTime.fromMillis(expectedUpdateTime)); jarScriptArchive = new JarScriptArchive.Builder(testArchiveJarFile).build(); repository.insertArchive(jarScriptArchive); archiveUpdateTimes = repository.getDefaultView().getArchiveUpdateTimes(); assertEquals(archiveUpdateTimes, Collections.singletonMap(testModuleId, expectedUpdateTime)); // assert getScriptArchives scriptArchives = repository.getScriptArchives(archiveUpdateTimes.keySet()); assertEquals(scriptArchives.size(), 1, scriptArchives.toString()); scriptArchive = scriptArchives.iterator().next(); assertEquals(scriptArchive.getModuleSpec().getModuleId(), testModuleId); assertEquals(scriptArchive.getCreateTime(), expectedUpdateTime); // assert getArchiveSummaries archiveSummaries = repository.getDefaultView().getArchiveSummaries(); assertEquals(archiveSummaries.size(), 1); archiveSummary = archiveSummaries.get(0); assertEquals(archiveSummary.getModuleId(), testModuleId); assertEquals(archiveSummary.getLastUpdateTime(), expectedUpdateTime); // assert getRepositorySummary repositorySummary = repository.getDefaultView().getRepositorySummary(); assertNotNull(repositorySummary); assertEquals(repositorySummary.getArchiveCount(), 1); assertEquals(repositorySummary.getLastUpdated(), expectedUpdateTime); // delete module repository.deleteArchive(testModuleId); archiveUpdateTimes = repository.getDefaultView().getArchiveUpdateTimes(); assertTrue(archiveUpdateTimes.isEmpty(), archiveUpdateTimes.toString()); }
From source file:org.kuali.ole.select.document.service.impl.OleInvoiceServiceImpl.java
public void createPaymentRequestDocument(OleInvoiceDocument inv, List<OleInvoiceItem> items, boolean flag) { if (LOG.isDebugEnabled()) { LOG.debug("Creating Payment Request document"); }// w ww .j a va 2 s.c o m KNSGlobalVariables.getMessageList().clear(); // validateInvoiceOrderValidForPREQCreation(inv); if (LOG.isDebugEnabled()) { if (inv.isInvoiceCancelIndicator()) { LOG.debug("Not possible to convert cancelled Invoice details into payment request"); } else { LOG.debug("Payment request document creation validation succeeded"); } } if (inv.isInvoiceCancelIndicator()) { LOG.debug("Invoice Cancelled, Payment Request not created"); } if (LOG.isDebugEnabled()) { LOG.debug("Total Dollar Amount above line items >>>>" + inv.getTotalDollarAmountAboveLineItems()); } Integer invId = inv.getPurapDocumentIdentifier(); Integer poId = 0; List<Integer> poList = new ArrayList(); List<OleInvoiceItem> oleInvoiceItemList = items; KualiDecimal invItemCount = new KualiDecimal(0); for (OleInvoiceItem oleInvoiceItem : oleInvoiceItemList) { if (oleInvoiceItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) { invItemCount = invItemCount.add(oleInvoiceItem.getItemQuantity()); } if ((!(poList.contains(oleInvoiceItem.getPurchaseOrderIdentifier()))) && oleInvoiceItem.getExtendedPrice().isNonZero()) { poList.add(oleInvoiceItem.getPurchaseOrderIdentifier()); } } String prorateBy = inv.getProrateBy(); OlePaymentRequestDocument preqDoc = null; Integer invPoId = 0; for (Integer purchaseOrderId : poList) { if (purchaseOrderId != null && invPoId.compareTo(purchaseOrderId) != 0) { try { preqDoc = (OlePaymentRequestDocument) SpringContext.getBean(DocumentService.class) .getNewDocument("OLE_PREQ"); preqDoc.setImmediatePaymentIndicator(inv.getImmediatePaymentIndicator()); preqDoc.setInvoiceDate(inv.getInvoiceDate()); preqDoc.setInvoiceNumber(inv.getInvoiceNumber()); preqDoc.setVendorInvoiceAmount(inv.getVendorInvoiceAmount().abs()); preqDoc.setVendorDetail(inv.getVendorDetail()); preqDoc.setVendorName(inv.getVendorName()); preqDoc.setVendorHeaderGeneratedIdentifier(inv.getVendorHeaderGeneratedIdentifier()); preqDoc.setVendorDetailAssignedIdentifier(inv.getVendorDetailAssignedIdentifier()); preqDoc.setVendorNumber(inv.getVendorNumber()); preqDoc.setVendorHeaderGeneratedIdentifier(inv.getVendorHeaderGeneratedIdentifier()); preqDoc.setVendorDetailAssignedIdentifier(inv.getVendorDetailAssignedIdentifier()); preqDoc.setVendorPaymentTerms(inv.getVendorPaymentTerms()); if (inv.getVendorPaymentTerms() != null) { preqDoc.setVendorPaymentTermsCode(inv.getVendorPaymentTerms().getVendorPaymentTermsCode()); } preqDoc.setVendorShippingTitleCode(inv.getVendorShippingTitleCode()); preqDoc.setVendorShippingPaymentTerms(inv.getVendorShippingPaymentTerms()); preqDoc.setVendorCityName(inv.getVendorCityName()); preqDoc.setVendorLine1Address(inv.getVendorLine1Address()); preqDoc.setVendorLine2Address(inv.getVendorLine2Address()); preqDoc.setVendorAttentionName(inv.getVendorAttentionName()); preqDoc.setVendorPostalCode(inv.getVendorPostalCode()); preqDoc.setVendorStateCode(inv.getVendorStateCode()); preqDoc.setVendorAttentionName(inv.getVendorAttentionName()); preqDoc.setVendorAddressInternationalProvinceName( inv.getVendorAddressInternationalProvinceName()); preqDoc.setVendorCountryCode(inv.getVendorCountryCode()); preqDoc.setVendorCountry(inv.getVendorCountry()); preqDoc.setVendorCustomerNumber(inv.getVendorCustomerNumber()); preqDoc.setAccountsPayableProcessorIdentifier(inv.getAccountsPayableProcessorIdentifier()); preqDoc.setProcessingCampusCode(inv.getProcessingCampusCode()); preqDoc.setPurchaseOrderIdentifier(purchaseOrderId); // //preqDoc.setClosePurchaseOrderIndicator(oleInvoiceItem.isClosePurchaseOrderIndicator()); preqDoc.setPaymentRequestPayDate(inv.getInvoicePayDate()); preqDoc.setImmediatePaymentIndicator(inv.getImmediatePaymentIndicator()); preqDoc.setPaymentRequestCostSource(inv.getInvoiceCostSource()); preqDoc.setProrateBy(inv.getProrateBy()); preqDoc.setProrateDollar(inv.isProrateDollar()); preqDoc.setProrateQty(inv.isProrateQty()); preqDoc.setProrateManual(inv.isProrateManual()); preqDoc.setNoProrate(inv.isNoProrate()); preqDoc.setForeignVendorInvoiceAmount(inv.getForeignVendorInvoiceAmount()); if (inv.getPaymentMethodId() != null) { OlePaymentMethod olePaymentMethod = SpringContext.getBean(BusinessObjectService.class) .findBySinglePrimaryKey(OlePaymentMethod.class, inv.getPaymentMethodId()); preqDoc.setPaymentMethod(olePaymentMethod); preqDoc.getPaymentMethod().setPaymentMethodId(olePaymentMethod.getPaymentMethodId()); preqDoc.setPaymentMethodId(olePaymentMethod.getPaymentMethodId()); } preqDoc.setInvoiceIdentifier(inv.getPurapDocumentIdentifier()); preqDoc.setBankCode(inv.getBankCode()); preqDoc.setBank(inv.getBank()); } catch (WorkflowException e) { String extraDescription = "Error=" + e.getMessage(); LOG.error("Exception creating Payment request document - " + e.getMessage()); } Map invItemMap = new HashMap(); invItemMap.put(PurapConstants.PRQSDocumentsStrings.PUR_ID, inv.getPurapDocumentIdentifier()); invItemMap.put(PurapConstants.PRQSDocumentsStrings.PO_ID, purchaseOrderId); List<OleInvoiceItem> invoiceItems = (List<OleInvoiceItem>) businessObjectService .findMatchingOrderBy(OleInvoiceItem.class, invItemMap, PurapConstants.PRQSDocumentsStrings.PO_ID, true); KualiDecimal itemCount = new KualiDecimal(0); KualiDecimal itemPrice = new KualiDecimal(0); PurchaseOrderDocument poDoc = inv.getPurchaseOrderDocument(purchaseOrderId); if (poDoc == null) { throw new RuntimeException( "Purchase Order document (invPoId=" + invPoId + ") does not exist in the system"); } preqDoc.getDocumentHeader().setDocumentDescription( createPreqDocumentDescription(poDoc.getPurapDocumentIdentifier(), inv.getVendorName())); try { preqDoc.updateAndSaveAppDocStatus(PurapConstants.PaymentRequestStatuses.APPDOC_IN_PROCESS); } catch (WorkflowException we) { throw new RuntimeException( "Unable to save route status data for document: " + preqDoc.getDocumentNumber(), we); } SpringContext.getBean(KualiRuleService.class) .applyRules(new AttributedCalculateAccountsPayableEvent(preqDoc)); SpringContext.getBean(PaymentRequestService.class).calculatePaymentRequest(preqDoc, false); HashMap<String, ExpiredOrClosedAccountEntry> expiredOrClosedAccountList = SpringContext .getBean(AccountsPayableService.class).expiredOrClosedAccountsList(poDoc); if (expiredOrClosedAccountList == null) { expiredOrClosedAccountList = new HashMap(); } if (LOG.isDebugEnabled()) { LOG.debug(expiredOrClosedAccountList.size() + " accounts has been found as Expired or Closed"); } List<OlePaymentRequestItem> olePaymentRequestItems = new ArrayList<>(); // int itemLineNumberCount = 0; for (OleInvoiceItem invoiceItem : invoiceItems) { if ((flag || invoiceItem.isDebitItem()) && invoiceItem.getExtendedPrice().isNonZero()) { OlePaymentRequestItem olePaymentRequestItem = new OlePaymentRequestItem(invoiceItem, preqDoc, expiredOrClosedAccountList); if (flag && !invoiceItem.isDebitItem()) { olePaymentRequestItem .setItemListPrice(olePaymentRequestItem.getItemListPrice().negated()); olePaymentRequestItem .setItemUnitPrice(olePaymentRequestItem.getItemUnitPrice().negate()); olePaymentRequestItem .setExtendedPrice(olePaymentRequestItem.getExtendedPrice().negated()); for (PurApAccountingLine purApAccountingLine : olePaymentRequestItem .getSourceAccountingLines()) { purApAccountingLine.setAmount(purApAccountingLine.getAmount().negated()); } } olePaymentRequestItems.add(olePaymentRequestItem); if (invoiceItem.isReopenPurchaseOrderIndicator()) { preqDoc.setReopenPurchaseOrderIndicator(invoiceItem.isReopenPurchaseOrderIndicator()); } if (invoiceItem.isClosePurchaseOrderIndicator()) { preqDoc.setClosePurchaseOrderIndicator(invoiceItem.isClosePurchaseOrderIndicator()); } if (preqDoc.getAccountsPayablePurchasingDocumentLinkIdentifier() == null) { preqDoc.setAccountsPayablePurchasingDocumentLinkIdentifier( invoiceItem.getAccountsPayablePurchasingDocumentLinkIdentifier()); } preqDoc.setReceivingDocumentRequiredIndicator( invoiceItem.isReceivingDocumentRequiredIndicator()); } } invPoId = purchaseOrderId; preqDoc.setItems(olePaymentRequestItems); try { SpringContext.getBean(PaymentRequestService.class).populateAndSavePaymentRequest(preqDoc); SpringContext.getBean(PaymentRequestService.class).autoApprovePaymentRequest(preqDoc); } catch (WorkflowException e) { e.printStackTrace(); } catch (ValidationException e) { String extraDescription = GlobalVariables.getMessageMap().toString(); } } if (GlobalVariables.getMessageMap().hasErrors()) { LOG.error("***************Error in rules processing - " + GlobalVariables.getMessageMap()); Map<String, AutoPopulatingList<ErrorMessage>> errorMessages = GlobalVariables.getMessageMap() .getErrorMessages(); String errors = errorMessages.toString(); } if (KNSGlobalVariables.getMessageList().size() > 0) { if (LOG.isDebugEnabled()) { LOG.debug("Payment request contains " + KNSGlobalVariables.getMessageList().size() + " warning message(s)"); for (int i = 0; i < KNSGlobalVariables.getMessageList().size(); i++) { LOG.debug("Warning " + i + " - " + KNSGlobalVariables.getMessageList().get(i)); } } } String routingAnnotation = null; if (!inv.isInvoiceCancelIndicator()) { routingAnnotation = "Routed by New Invoice Creation"; } } }
From source file:org.apache.accumulo.examples.wikisearch.logic.AbstractQueryLogic.java
/** * Queries metadata table to determine which terms are indexed. * /*from w w w .j a v a 2s .c om*/ * @param c * @param auths * @param queryLiterals * @param datatypes * - optional list of types * @return map of indexed field names to types to normalizers used in this date range * @throws TableNotFoundException * @throws IllegalAccessException * @throws InstantiationException */ protected Map<String, Multimap<String, Class<? extends Normalizer>>> findIndexedTerms(Connector c, Authorizations auths, Set<String> queryLiterals, Set<String> datatypes) throws TableNotFoundException, InstantiationException, IllegalAccessException { Map<String, Multimap<String, Class<? extends Normalizer>>> results = new HashMap<String, Multimap<String, Class<? extends Normalizer>>>(); for (String literal : queryLiterals) { if (log.isDebugEnabled()) log.debug("Querying " + this.getMetadataTableName() + " table for " + literal); Range range = new Range(literal.toUpperCase()); Scanner scanner = c.createScanner(this.getMetadataTableName(), auths); scanner.setRange(range); scanner.fetchColumnFamily(new Text(WikipediaMapper.METADATA_INDEX_COLUMN_FAMILY)); for (Entry<Key, Value> entry : scanner) { if (!results.containsKey(literal)) { Multimap<String, Class<? extends Normalizer>> m = HashMultimap.create(); results.put(literal, m); } // Get the column qualifier from the key. It contains the datatype and normalizer class String colq = entry.getKey().getColumnQualifier().toString(); if (null != colq && colq.contains("\0")) { int idx = colq.indexOf("\0"); if (idx != -1) { String type = colq.substring(0, idx); // If types are specified and this type is not in the list then skip it. if (null != datatypes && !datatypes.contains(type)) continue; try { @SuppressWarnings("unchecked") Class<? extends Normalizer> clazz = (Class<? extends Normalizer>) Class .forName(colq.substring(idx + 1)); if (!normalizerCacheMap.containsKey(clazz)) normalizerCacheMap.put(clazz, clazz.newInstance()); results.get(literal).put(type, clazz); } catch (ClassNotFoundException e) { log.error("Unable to find normalizer on class path: " + colq.substring(idx + 1), e); results.get(literal).put(type, LcNoDiacriticsNormalizer.class); } } else { log.warn("EventMetadata entry did not contain NULL byte: " + entry.getKey().toString()); } } else { log.warn("ColumnQualifier null in EventMetadata for key: " + entry.getKey().toString()); } } } if (log.isDebugEnabled()) log.debug("METADATA RESULTS: " + results.toString()); return results; }
From source file:org.apache.pig.impl.builtin.PartitionSkewedKeys.java
/** * first field in the input tuple is the number of reducers * * second field is the *sorted* bag of samples * this should be called only once/* w w w . ja v a 2 s . c om*/ */ public Map<String, Object> exec(Tuple in) throws IOException { if (in == null || in.size() == 0) { return null; } Map<String, Object> output = new HashMap<String, Object>(); totalMemory_ = (long) (Runtime.getRuntime().maxMemory() * heapPercentage_); log.info("Maximum of available memory is " + totalMemory_); ArrayList<Tuple> reducerList = new ArrayList<Tuple>(); Tuple currentTuple = null; long count = 0; // total size in memory for tuples in sample long totalSampleMSize = 0; //total input rows for the join long totalInputRows = 0; try { if (totalReducers_ == -1) { totalReducers_ = (Integer) in.get(0); } DataBag samples = (DataBag) in.get(1); totalSampleCount_ = samples.size(); log.info("totalSample: " + totalSampleCount_); log.info("totalReducers: " + totalReducers_); int maxReducers = 0; // first iterate the samples to find total number of rows Iterator<Tuple> iter1 = samples.iterator(); while (iter1.hasNext()) { Tuple t = iter1.next(); totalInputRows += (Long) t.get(t.size() - 1); } // now iterate samples to do the reducer calculation Iterator<Tuple> iter2 = samples.iterator(); while (iter2.hasNext()) { Tuple t = iter2.next(); if (hasSameKey(currentTuple, t) || currentTuple == null) { count++; totalSampleMSize += getMemorySize(t); } else { Pair<Tuple, Integer> p = calculateReducers(currentTuple, count, totalSampleMSize, totalInputRows); Tuple rt = p.first; if (rt != null) { reducerList.add(rt); } if (maxReducers < p.second) { maxReducers = p.second; } count = 1; totalSampleMSize = getMemorySize(t); } currentTuple = t; } // add last key if (count > 0) { Pair<Tuple, Integer> p = calculateReducers(currentTuple, count, totalSampleMSize, totalInputRows); Tuple rt = p.first; if (rt != null) { reducerList.add(rt); } if (maxReducers < p.second) { maxReducers = p.second; } } if (maxReducers > totalReducers_) { if (pigLogger != null) { pigLogger.warn(this, "You need at least " + maxReducers + " reducers to avoid spillage and run this job efficiently.", PigWarning.REDUCER_COUNT_LOW); } else { log.warn("You need at least " + maxReducers + " reducers to avoid spillage and run this job efficiently."); } } output.put(PARTITION_LIST, mBagFactory.newDefaultBag(reducerList)); output.put(TOTAL_REDUCERS, Integer.valueOf(totalReducers_)); log.info(output.toString()); if (log.isDebugEnabled()) { log.debug(output.toString()); } return output; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }
From source file:com.google.gwt.emultest.java.util.TreeMapTest.java
/** * Test method for 'java.lang.Object.toString()'. *///from ww w . j a v a2s . co m public void testToString() { K[] keys = getKeys(); V[] values = getValues(); Map<K, V> map = createMap(); map.put(keys[0], values[0]); String entryString = makeEntryString(keys[0], values[0]); assertEquals(entryString, map.toString()); }
From source file:com.elementwin.bs.controller.RevisitExportController.java
/** * ?// www . ja v a 2 s.co m * @param request * @param response * @param modelMap * @return * @throws Exception */ @SuppressWarnings("unchecked") @RequestMapping(value = "/export", method = RequestMethod.GET) public String export(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception { OrgUser user = AppHelper.getCurrentUser(); Map<String, Object> criteria = new HashMap<String, Object>(); criteria.put("org_id", user.getOrgId()); buildCriteriaWithFilter(criteria, request, modelMap); List<RevisitTask> tasks = (List<RevisitTask>) revisitTaskService.getModelList(criteria); if (tasks == null || tasks.isEmpty()) { addResultMsg(request, false, "??"); return view(request, modelMap, "index"); } //taskId? List<Long> taskIds = new ArrayList<Long>(); //workOrderIds? List<Long> workOrderIds = new ArrayList<Long>(); // ?Sheet? Map<Long, List<RevisitTask>> qMap = new HashMap<Long, List<RevisitTask>>(); // ??task for (RevisitTask task : tasks) { taskIds.add(task.getId()); if (task.getWorkOrderId() != null && task.getWorkOrderId() > 0L) { workOrderIds.add(task.getWorkOrderId()); } // ??Map task Long key = task.getQuestionId(); List<RevisitTask> list = qMap.get(key); if (list == null) { list = new ArrayList<RevisitTask>(); qMap.put(key, list); } list.add(task); } //taskId? List<RevisitAnswer> allAnswers = revisitTaskService.getAnswersInTasks(taskIds); Map<Long, List<BaseModel>> allAnswerMap = AppHelper.list2map(allAnswers); //taskId?record List<RevisitRecord> allRecords = revisitTaskService.getRecordsInTasks(taskIds); Map<Long, List<BaseModel>> allRecordMap = AppHelper.list2map(allRecords); //task?? List<RevisitWorkOrder> allWorkOrders = revisitTaskService.getWorkOrders(workOrderIds); //?? revisitTaskService.appendWorkOrderOpinions(allWorkOrders); Map<Long, List<BaseModel>> allWorkOrderMap = AppHelper.list2map(allWorkOrders); // excel String outFileName = "_" + DateUtils.getDate(new Date()) + ".xls"; ExcelWriter writer = new ExcelWriter(outFileName); for (Map.Entry<Long, List<RevisitTask>> entry : qMap.entrySet()) { List<QuestionItem> qItems = revisitTaskService.getQuestionItems(entry.getKey()); List<String> headers = getExportHeader(qItems); //?? List<String> rows = getExportData(entry.getValue(), allAnswerMap, allRecordMap, allWorkOrderMap, qItems.size()); // sheet writer.addSheet(headers, rows); } // ? String path = writer.generate(); // if (StringUtils.isNotBlank(path)) { FileHelper.downloadFile(path, request, response); } // ? asyncWorker.saveTraceLog(user, Cons.OPERATION.EXPORT, tasks.get(0), ":" + criteria.toString()); //?? tasks = null; taskIds = null; workOrderIds = null; allAnswers = null; allRecords = null; allWorkOrderMap = null; criteria = null; allAnswerMap = null; allRecordMap = null; qMap = null; return null; }