List of usage examples for java.lang String valueOf
public static String valueOf(double d)
From source file:com.datumbox.opensource.examples.DPMMExample.java
/** * @param args the command line arguments *///ww w . j a v a2 s .co m public static void main(String[] args) { long startTime = System.currentTimeMillis(); GDPMM(); System.out.println(); MDPMM(); long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; System.out.println("Completed in " + String.valueOf(elapsedTime / 1000.0) + " sec"); }
From source file:DcmQR.java
@SuppressWarnings("unchecked") public static void main(String[] args) { CommandLine cl = parse(args);/* w w w .ja v a 2 s .c o m*/ DcmQR dcmqr = new DcmQR(); final List<String> argList = cl.getArgList(); String remoteAE = argList.get(0); String[] calledAETAddress = split(remoteAE, '@'); dcmqr.setCalledAET(calledAETAddress[0], cl.hasOption("reuseassoc")); if (calledAETAddress[1] == null) { dcmqr.setRemoteHost("127.0.0.1"); dcmqr.setRemotePort(104); } else { String[] hostPort = split(calledAETAddress[1], ':'); dcmqr.setRemoteHost(hostPort[0]); dcmqr.setRemotePort(toPort(hostPort[1])); } if (cl.hasOption("L")) { String localAE = cl.getOptionValue("L"); String[] localPort = split(localAE, ':'); if (localPort[1] != null) { dcmqr.setLocalPort(toPort(localPort[1])); } String[] callingAETHost = split(localPort[0], '@'); dcmqr.setCalling(callingAETHost[0]); if (callingAETHost[1] != null) { dcmqr.setLocalHost(callingAETHost[1]); } } if (cl.hasOption("username")) { String username = cl.getOptionValue("username"); UserIdentity userId; if (cl.hasOption("passcode")) { String passcode = cl.getOptionValue("passcode"); userId = new UserIdentity.UsernamePasscode(username, passcode.toCharArray()); } else { userId = new UserIdentity.Username(username); } userId.setPositiveResponseRequested(cl.hasOption("uidnegrsp")); dcmqr.setUserIdentity(userId); } if (cl.hasOption("connectTO")) dcmqr.setConnectTimeout(parseInt(cl.getOptionValue("connectTO"), "illegal argument of option -connectTO", 1, Integer.MAX_VALUE)); if (cl.hasOption("reaper")) dcmqr.setAssociationReaperPeriod(parseInt(cl.getOptionValue("reaper"), "illegal argument of option -reaper", 1, Integer.MAX_VALUE)); if (cl.hasOption("cfindrspTO")) dcmqr.setDimseRspTimeout(parseInt(cl.getOptionValue("cfindrspTO"), "illegal argument of option -cfindrspTO", 1, Integer.MAX_VALUE)); if (cl.hasOption("cmoverspTO")) dcmqr.setRetrieveRspTimeout(parseInt(cl.getOptionValue("cmoverspTO"), "illegal argument of option -cmoverspTO", 1, Integer.MAX_VALUE)); if (cl.hasOption("cgetrspTO")) dcmqr.setRetrieveRspTimeout(parseInt(cl.getOptionValue("cgetrspTO"), "illegal argument of option -cgetrspTO", 1, Integer.MAX_VALUE)); if (cl.hasOption("acceptTO")) dcmqr.setAcceptTimeout(parseInt(cl.getOptionValue("acceptTO"), "illegal argument of option -acceptTO", 1, Integer.MAX_VALUE)); if (cl.hasOption("releaseTO")) dcmqr.setReleaseTimeout(parseInt(cl.getOptionValue("releaseTO"), "illegal argument of option -releaseTO", 1, Integer.MAX_VALUE)); if (cl.hasOption("soclosedelay")) dcmqr.setSocketCloseDelay(parseInt(cl.getOptionValue("soclosedelay"), "illegal argument of option -soclosedelay", 1, 10000)); if (cl.hasOption("rcvpdulen")) dcmqr.setMaxPDULengthReceive( parseInt(cl.getOptionValue("rcvpdulen"), "illegal argument of option -rcvpdulen", 1, 10000) * KB); if (cl.hasOption("sndpdulen")) dcmqr.setMaxPDULengthSend( parseInt(cl.getOptionValue("sndpdulen"), "illegal argument of option -sndpdulen", 1, 10000) * KB); if (cl.hasOption("sosndbuf")) dcmqr.setSendBufferSize( parseInt(cl.getOptionValue("sosndbuf"), "illegal argument of option -sosndbuf", 1, 10000) * KB); if (cl.hasOption("sorcvbuf")) dcmqr.setReceiveBufferSize( parseInt(cl.getOptionValue("sorcvbuf"), "illegal argument of option -sorcvbuf", 1, 10000) * KB); if (cl.hasOption("filebuf")) dcmqr.setFileBufferSize( parseInt(cl.getOptionValue("filebuf"), "illegal argument of option -filebuf", 1, 10000) * KB); dcmqr.setPackPDV(!cl.hasOption("pdv1")); dcmqr.setTcpNoDelay(!cl.hasOption("tcpdelay")); dcmqr.setMaxOpsInvoked(cl.hasOption("async") ? parseInt(cl.getOptionValue("async"), "illegal argument of option -async", 0, 0xffff) : 1); dcmqr.setMaxOpsPerformed(cl.hasOption("cstoreasync") ? parseInt(cl.getOptionValue("cstoreasync"), "illegal argument of option -cstoreasync", 0, 0xffff) : 0); if (cl.hasOption("C")) dcmqr.setCancelAfter( parseInt(cl.getOptionValue("C"), "illegal argument of option -C", 1, Integer.MAX_VALUE)); if (cl.hasOption("lowprior")) dcmqr.setPriority(CommandUtils.LOW); if (cl.hasOption("highprior")) dcmqr.setPriority(CommandUtils.HIGH); if (cl.hasOption("cstore")) { String[] storeTCs = cl.getOptionValues("cstore"); for (String storeTC : storeTCs) { String cuid; String[] tsuids; int colon = storeTC.indexOf(':'); if (colon == -1) { cuid = storeTC; tsuids = DEF_TS; } else { cuid = storeTC.substring(0, colon); String ts = storeTC.substring(colon + 1); try { tsuids = TS.valueOf(ts).uids; } catch (IllegalArgumentException e) { tsuids = ts.split(","); } } try { cuid = CUID.valueOf(cuid).uid; } catch (IllegalArgumentException e) { // assume cuid already contains UID } dcmqr.addStoreTransferCapability(cuid, tsuids); } if (cl.hasOption("cstoredest")) dcmqr.setStoreDestination(cl.getOptionValue("cstoredest")); } dcmqr.setCGet(cl.hasOption("cget")); if (cl.hasOption("cmove")) dcmqr.setMoveDest(cl.getOptionValue("cmove")); if (cl.hasOption("evalRetrieveAET")) dcmqr.setEvalRetrieveAET(true); if (cl.hasOption("P")) dcmqr.setQueryLevel(QueryRetrieveLevel.PATIENT); else if (cl.hasOption("S")) dcmqr.setQueryLevel(QueryRetrieveLevel.SERIES); else if (cl.hasOption("I")) dcmqr.setQueryLevel(QueryRetrieveLevel.IMAGE); else dcmqr.setQueryLevel(QueryRetrieveLevel.STUDY); if (cl.hasOption("noextneg")) dcmqr.setNoExtNegotiation(true); if (cl.hasOption("rel")) dcmqr.setRelationQR(true); if (cl.hasOption("datetime")) dcmqr.setDateTimeMatching(true); if (cl.hasOption("fuzzy")) dcmqr.setFuzzySemanticPersonNameMatching(true); if (!cl.hasOption("P")) { if (cl.hasOption("retall")) dcmqr.addPrivate(UID.PrivateStudyRootQueryRetrieveInformationModelFIND); if (cl.hasOption("blocked")) dcmqr.addPrivate(UID.PrivateBlockedStudyRootQueryRetrieveInformationModelFIND); if (cl.hasOption("vmf")) dcmqr.addPrivate(UID.PrivateVirtualMultiframeStudyRootQueryRetrieveInformationModelFIND); } if (cl.hasOption("q")) { String[] matchingKeys = cl.getOptionValues("q"); for (int i = 1; i < matchingKeys.length; i++, i++) dcmqr.addMatchingKey(Tag.toTagPath(matchingKeys[i - 1]), matchingKeys[i]); } if (cl.hasOption("r")) { String[] returnKeys = cl.getOptionValues("r"); for (int i = 0; i < returnKeys.length; i++) dcmqr.addReturnKey(Tag.toTagPath(returnKeys[i])); } dcmqr.configureTransferCapability(cl.hasOption("ivrle")); int repeat = cl.hasOption("repeat") ? parseInt(cl.getOptionValue("repeat"), "illegal argument of option -repeat", 1, Integer.MAX_VALUE) : 0; int interval = cl.hasOption("repeatdelay") ? parseInt(cl.getOptionValue("repeatdelay"), "illegal argument of option -repeatdelay", 1, Integer.MAX_VALUE) : 0; boolean closeAssoc = cl.hasOption("closeassoc"); if (cl.hasOption("tls")) { String cipher = cl.getOptionValue("tls"); if ("NULL".equalsIgnoreCase(cipher)) { dcmqr.setTlsWithoutEncyrption(); } else if ("3DES".equalsIgnoreCase(cipher)) { dcmqr.setTls3DES_EDE_CBC(); } else if ("AES".equalsIgnoreCase(cipher)) { dcmqr.setTlsAES_128_CBC(); } else { exit("Invalid parameter for option -tls: " + cipher); } if (cl.hasOption("nossl2")) { dcmqr.disableSSLv2Hello(); } dcmqr.setTlsNeedClientAuth(!cl.hasOption("noclientauth")); if (cl.hasOption("keystore")) { dcmqr.setKeyStoreURL(cl.getOptionValue("keystore")); } if (cl.hasOption("keystorepw")) { dcmqr.setKeyStorePassword(cl.getOptionValue("keystorepw")); } if (cl.hasOption("keypw")) { dcmqr.setKeyPassword(cl.getOptionValue("keypw")); } if (cl.hasOption("truststore")) { dcmqr.setTrustStoreURL(cl.getOptionValue("truststore")); } if (cl.hasOption("truststorepw")) { dcmqr.setTrustStorePassword(cl.getOptionValue("truststorepw")); } long t1 = System.currentTimeMillis(); try { dcmqr.initTLS(); } catch (Exception e) { System.err.println("ERROR: Failed to initialize TLS context:" + e.getMessage()); System.exit(2); } long t2 = System.currentTimeMillis(); LOG.info("Initialize TLS context in {} s", Float.valueOf((t2 - t1) / 1000f)); } try { dcmqr.start(); } catch (Exception e) { System.err.println( "ERROR: Failed to start server for receiving " + "requested objects:" + e.getMessage()); System.exit(2); } try { long t1 = System.currentTimeMillis(); try { dcmqr.open(); } catch (Exception e) { LOG.error("Failed to establish association:", e); System.exit(2); } long t2 = System.currentTimeMillis(); LOG.info("Connected to {} in {} s", remoteAE, Float.valueOf((t2 - t1) / 1000f)); for (;;) { List<DicomObject> result = dcmqr.query(); long t3 = System.currentTimeMillis(); LOG.info("Received {} matching entries in {} s", Integer.valueOf(result.size()), Float.valueOf((t3 - t2) / 1000f)); if (dcmqr.isCMove() || dcmqr.isCGet()) { if (dcmqr.isCMove()) dcmqr.move(result); else dcmqr.get(result); long t4 = System.currentTimeMillis(); LOG.info("Retrieved {} objects (warning: {}, failed: {}) in {}s", new Object[] { Integer.valueOf(dcmqr.getTotalRetrieved()), Integer.valueOf(dcmqr.getWarning()), Integer.valueOf(dcmqr.getFailed()), Float.valueOf((t4 - t3) / 1000f) }); } if (repeat == 0 || closeAssoc) { try { dcmqr.close(); } catch (InterruptedException e) { LOG.error(e.getMessage(), e); } LOG.info("Released connection to {}", remoteAE); } if (repeat-- == 0) break; Thread.sleep(interval); long t4 = System.currentTimeMillis(); dcmqr.open(); t2 = System.currentTimeMillis(); LOG.info("Reconnect or reuse connection to {} in {} s", remoteAE, Float.valueOf((t2 - t4) / 1000f)); } } catch (IOException e) { LOG.error(e.getMessage(), e); } catch (InterruptedException e) { LOG.error(e.getMessage(), e); } catch (ConfigurationException e) { LOG.error(e.getMessage(), e); } finally { dcmqr.stop(); } }
From source file:mod.org.dcm4che2.tool.DcmQR.java
@SuppressWarnings("unchecked") public static void main(String[] args) { CommandLine cl = parse(args);// ww w . j av a 2 s. co m DcmQR dcmqr = new DcmQR(cl.hasOption("device") ? cl.getOptionValue("device") : "DCMQR"); final List<String> argList = cl.getArgList(); String remoteAE = argList.get(0); String[] calledAETAddress = split(remoteAE, '@'); dcmqr.setCalledAET(calledAETAddress[0], cl.hasOption("reuseassoc")); if (calledAETAddress[1] == null) { dcmqr.setRemoteHost("127.0.0.1"); dcmqr.setRemotePort(104); } else { String[] hostPort = split(calledAETAddress[1], ':'); dcmqr.setRemoteHost(hostPort[0]); dcmqr.setRemotePort(toPort(hostPort[1])); } if (cl.hasOption("L")) { String localAE = cl.getOptionValue("L"); String[] localPort = split(localAE, ':'); if (localPort[1] != null) { dcmqr.setLocalPort(toPort(localPort[1])); } String[] callingAETHost = split(localPort[0], '@'); dcmqr.setCalling(callingAETHost[0]); if (callingAETHost[1] != null) { dcmqr.setLocalHost(callingAETHost[1]); } } if (cl.hasOption("username")) { String username = cl.getOptionValue("username"); UserIdentity userId; if (cl.hasOption("passcode")) { String passcode = cl.getOptionValue("passcode"); userId = new UserIdentity.UsernamePasscode(username, passcode.toCharArray()); } else { userId = new UserIdentity.Username(username); } userId.setPositiveResponseRequested(cl.hasOption("uidnegrsp")); dcmqr.setUserIdentity(userId); } if (cl.hasOption("connectTO")) dcmqr.setConnectTimeout(parseInt(cl.getOptionValue("connectTO"), "illegal argument of option -connectTO", 1, Integer.MAX_VALUE)); if (cl.hasOption("reaper")) dcmqr.setAssociationReaperPeriod(parseInt(cl.getOptionValue("reaper"), "illegal argument of option -reaper", 1, Integer.MAX_VALUE)); if (cl.hasOption("cfindrspTO")) dcmqr.setDimseRspTimeout(parseInt(cl.getOptionValue("cfindrspTO"), "illegal argument of option -cfindrspTO", 1, Integer.MAX_VALUE)); if (cl.hasOption("cmoverspTO")) dcmqr.setRetrieveRspTimeout(parseInt(cl.getOptionValue("cmoverspTO"), "illegal argument of option -cmoverspTO", 1, Integer.MAX_VALUE)); if (cl.hasOption("cgetrspTO")) dcmqr.setRetrieveRspTimeout(parseInt(cl.getOptionValue("cgetrspTO"), "illegal argument of option -cgetrspTO", 1, Integer.MAX_VALUE)); if (cl.hasOption("acceptTO")) dcmqr.setAcceptTimeout(parseInt(cl.getOptionValue("acceptTO"), "illegal argument of option -acceptTO", 1, Integer.MAX_VALUE)); if (cl.hasOption("releaseTO")) dcmqr.setReleaseTimeout(parseInt(cl.getOptionValue("releaseTO"), "illegal argument of option -releaseTO", 1, Integer.MAX_VALUE)); if (cl.hasOption("soclosedelay")) dcmqr.setSocketCloseDelay(parseInt(cl.getOptionValue("soclosedelay"), "illegal argument of option -soclosedelay", 1, 10000)); if (cl.hasOption("rcvpdulen")) dcmqr.setMaxPDULengthReceive( parseInt(cl.getOptionValue("rcvpdulen"), "illegal argument of option -rcvpdulen", 1, 10000) * KB); if (cl.hasOption("sndpdulen")) dcmqr.setMaxPDULengthSend( parseInt(cl.getOptionValue("sndpdulen"), "illegal argument of option -sndpdulen", 1, 10000) * KB); if (cl.hasOption("sosndbuf")) dcmqr.setSendBufferSize( parseInt(cl.getOptionValue("sosndbuf"), "illegal argument of option -sosndbuf", 1, 10000) * KB); if (cl.hasOption("sorcvbuf")) dcmqr.setReceiveBufferSize( parseInt(cl.getOptionValue("sorcvbuf"), "illegal argument of option -sorcvbuf", 1, 10000) * KB); if (cl.hasOption("filebuf")) dcmqr.setFileBufferSize( parseInt(cl.getOptionValue("filebuf"), "illegal argument of option -filebuf", 1, 10000) * KB); dcmqr.setPackPDV(!cl.hasOption("pdv1")); dcmqr.setTcpNoDelay(!cl.hasOption("tcpdelay")); dcmqr.setMaxOpsInvoked(cl.hasOption("async") ? parseInt(cl.getOptionValue("async"), "illegal argument of option -async", 0, 0xffff) : 1); dcmqr.setMaxOpsPerformed(cl.hasOption("cstoreasync") ? parseInt(cl.getOptionValue("cstoreasync"), "illegal argument of option -cstoreasync", 0, 0xffff) : 0); if (cl.hasOption("C")) dcmqr.setCancelAfter( parseInt(cl.getOptionValue("C"), "illegal argument of option -C", 1, Integer.MAX_VALUE)); if (cl.hasOption("lowprior")) dcmqr.setPriority(CommandUtils.LOW); if (cl.hasOption("highprior")) dcmqr.setPriority(CommandUtils.HIGH); if (cl.hasOption("cstore")) { String[] storeTCs = cl.getOptionValues("cstore"); for (String storeTC : storeTCs) { String cuid; String[] tsuids; int colon = storeTC.indexOf(':'); if (colon == -1) { cuid = storeTC; tsuids = DEF_TS; } else { cuid = storeTC.substring(0, colon); String ts = storeTC.substring(colon + 1); try { tsuids = TS.valueOf(ts).uids; } catch (IllegalArgumentException e) { tsuids = ts.split(","); } } try { cuid = CUID.valueOf(cuid).uid; } catch (IllegalArgumentException e) { // assume cuid already contains UID } dcmqr.addStoreTransferCapability(cuid, tsuids); } if (cl.hasOption("cstoredest")) dcmqr.setStoreDestination(cl.getOptionValue("cstoredest")); } dcmqr.setCFind(!cl.hasOption("nocfind")); dcmqr.setCGet(cl.hasOption("cget")); if (cl.hasOption("cmove")) dcmqr.setMoveDest(cl.getOptionValue("cmove")); if (cl.hasOption("evalRetrieveAET")) dcmqr.setEvalRetrieveAET(true); dcmqr.setQueryLevel(cl.hasOption("P") ? QueryRetrieveLevel.PATIENT : cl.hasOption("S") ? QueryRetrieveLevel.SERIES : cl.hasOption("I") ? QueryRetrieveLevel.IMAGE : QueryRetrieveLevel.STUDY); if (cl.hasOption("noextneg")) dcmqr.setNoExtNegotiation(true); if (cl.hasOption("rel")) dcmqr.setRelationQR(true); if (cl.hasOption("datetime")) dcmqr.setDateTimeMatching(true); if (cl.hasOption("fuzzy")) dcmqr.setFuzzySemanticPersonNameMatching(true); if (!cl.hasOption("P")) { if (cl.hasOption("retall")) dcmqr.addPrivate(UID.PrivateStudyRootQueryRetrieveInformationModelFIND); if (cl.hasOption("blocked")) dcmqr.addPrivate(UID.PrivateBlockedStudyRootQueryRetrieveInformationModelFIND); if (cl.hasOption("vmf")) dcmqr.addPrivate(UID.PrivateVirtualMultiframeStudyRootQueryRetrieveInformationModelFIND); } if (cl.hasOption("cfind")) { String[] cuids = cl.getOptionValues("cfind"); for (int i = 0; i < cuids.length; i++) dcmqr.addPrivate(cuids[i]); } if (!cl.hasOption("nodefret")) dcmqr.addDefReturnKeys(); if (cl.hasOption("r")) { String[] returnKeys = cl.getOptionValues("r"); for (int i = 0; i < returnKeys.length; i++) dcmqr.addReturnKey(Tag.toTagPath(returnKeys[i])); } if (cl.hasOption("q")) { String[] matchingKeys = cl.getOptionValues("q"); for (int i = 1; i < matchingKeys.length; i++, i++) dcmqr.addMatchingKey(Tag.toTagPath(matchingKeys[i - 1]), matchingKeys[i]); } dcmqr.configureTransferCapability(cl.hasOption("ivrle")); int repeat = cl.hasOption("repeat") ? parseInt(cl.getOptionValue("repeat"), "illegal argument of option -repeat", 1, Integer.MAX_VALUE) : 0; int interval = cl.hasOption("repeatdelay") ? parseInt(cl.getOptionValue("repeatdelay"), "illegal argument of option -repeatdelay", 1, Integer.MAX_VALUE) : 0; boolean closeAssoc = cl.hasOption("closeassoc"); if (cl.hasOption("tls")) { String cipher = cl.getOptionValue("tls"); if ("NULL".equalsIgnoreCase(cipher)) { dcmqr.setTlsWithoutEncyrption(); } else if ("3DES".equalsIgnoreCase(cipher)) { dcmqr.setTls3DES_EDE_CBC(); } else if ("AES".equalsIgnoreCase(cipher)) { dcmqr.setTlsAES_128_CBC(); } else { exit("Invalid parameter for option -tls: " + cipher); } if (cl.hasOption("tls1")) { dcmqr.setTlsProtocol(TLS1); } else if (cl.hasOption("ssl3")) { dcmqr.setTlsProtocol(SSL3); } else if (cl.hasOption("no_tls1")) { dcmqr.setTlsProtocol(NO_TLS1); } else if (cl.hasOption("no_ssl3")) { dcmqr.setTlsProtocol(NO_SSL3); } else if (cl.hasOption("no_ssl2")) { dcmqr.setTlsProtocol(NO_SSL2); } dcmqr.setTlsNeedClientAuth(!cl.hasOption("noclientauth")); if (cl.hasOption("keystore")) { dcmqr.setKeyStoreURL(cl.getOptionValue("keystore")); } if (cl.hasOption("keystorepw")) { dcmqr.setKeyStorePassword(cl.getOptionValue("keystorepw")); } if (cl.hasOption("keypw")) { dcmqr.setKeyPassword(cl.getOptionValue("keypw")); } if (cl.hasOption("truststore")) { dcmqr.setTrustStoreURL(cl.getOptionValue("truststore")); } if (cl.hasOption("truststorepw")) { dcmqr.setTrustStorePassword(cl.getOptionValue("truststorepw")); } long t1 = System.currentTimeMillis(); try { dcmqr.initTLS(); } catch (Exception e) { System.err.println("ERROR: Failed to initialize TLS context:" + e.getMessage()); System.exit(2); } long t2 = System.currentTimeMillis(); LOG.info("Initialize TLS context in {} s", Float.valueOf((t2 - t1) / 1000f)); } try { dcmqr.start(); } catch (Exception e) { System.err.println( "ERROR: Failed to start server for receiving " + "requested objects:" + e.getMessage()); System.exit(2); } try { long t1 = System.currentTimeMillis(); try { dcmqr.open(); } catch (Exception e) { LOG.error("Failed to establish association:", e); System.exit(2); } long t2 = System.currentTimeMillis(); LOG.info("Connected to {} in {} s", remoteAE, Float.valueOf((t2 - t1) / 1000f)); for (;;) { List<DicomObject> result; if (dcmqr.isCFind()) { result = dcmqr.query(); long t3 = System.currentTimeMillis(); LOG.info("Received {} matching entries in {} s", Integer.valueOf(result.size()), Float.valueOf((t3 - t2) / 1000f)); t2 = t3; } else { result = Collections.singletonList(dcmqr.getKeys()); } if (dcmqr.isCMove() || dcmqr.isCGet()) { if (dcmqr.isCMove()) dcmqr.move(result); else dcmqr.get(result); long t4 = System.currentTimeMillis(); LOG.info("Retrieved {} objects (warning: {}, failed: {}) in {}s", new Object[] { Integer.valueOf(dcmqr.getTotalRetrieved()), Integer.valueOf(dcmqr.getWarning()), Integer.valueOf(dcmqr.getFailed()), Float.valueOf((t4 - t2) / 1000f) }); } if (repeat == 0 || closeAssoc) { try { dcmqr.close(); } catch (InterruptedException e) { LOG.error(e.getMessage(), e); } LOG.info("Released connection to {}", remoteAE); } if (repeat-- == 0) break; Thread.sleep(interval); long t4 = System.currentTimeMillis(); dcmqr.open(); t2 = System.currentTimeMillis(); LOG.info("Reconnect or reuse connection to {} in {} s", remoteAE, Float.valueOf((t2 - t4) / 1000f)); } } catch (IOException e) { LOG.error(e.getMessage(), e); } catch (InterruptedException e) { LOG.error(e.getMessage(), e); } catch (ConfigurationException e) { LOG.error(e.getMessage(), e); } finally { dcmqr.stop(); } }
From source file:com.alibaba.dubbo.examples.cache.CacheConsumer.java
public static void main(String[] args) throws Exception { String config = CacheConsumer.class.getPackage().getName().replace('.', '/') + "/cache-consumer.xml"; ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); context.start();/*w w w. ja v a 2 s. c o m*/ CacheService cacheService = (CacheService) context.getBean("cacheService"); // ?(?) String fix = null; for (int i = 0; i < 5; i++) { String result = cacheService.findCache("0"); if (fix == null || fix.equals(result)) { System.out.println("OK: " + result); } else { System.err.println("ERROR: " + result); } fix = result; Thread.sleep(500); } // LRU?cache.size10001001 for (int n = 0; n < 1001; n++) { String pre = null; for (int i = 0; i < 10; i++) { String result = cacheService.findCache(String.valueOf(n)); if (pre != null && !pre.equals(result)) { System.err.println("ERROR: " + result); } pre = result; } } // LRU String result = cacheService.findCache("0"); System.out.println("OK--->: " + result); if (fix != null && !fix.equals(result)) { System.out.println("OK: " + result); } else { System.err.println("ERROR: " + result); } }
From source file:org.eclipse.swt.examples.accessibility.AccessibleValueExample.java
public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new FillLayout()); shell.setText("Accessible Value Example"); final Canvas canvas = new Canvas(shell, SWT.DOUBLE_BUFFERED); canvas.addPaintListener(e -> {/*from w w w . j a v a2s . c o m*/ Rectangle rect = canvas.getClientArea(); String val = String.valueOf(value); Point size = e.gc.stringExtent(val); e.gc.setBackground(e.display.getSystemColor(SWT.COLOR_LIST_SELECTION)); e.gc.fillRectangle(0, 0, rect.width * value / (max - min), rect.height); e.gc.drawString(val, rect.x + (rect.width - size.x) / 2, rect.y + (rect.height - size.y) / 2, true); }); Accessible accessible = canvas.getAccessible(); accessible.addAccessibleListener(new AccessibleAdapter() { @Override public void getName(AccessibleEvent e) { e.result = "The value of this canvas is " + value; } }); accessible.addAccessibleControlListener(new AccessibleControlAdapter() { @Override public void getRole(AccessibleControlEvent e) { e.detail = ACC.ROLE_PROGRESSBAR; } }); accessible.addAccessibleValueListener(new AccessibleValueAdapter() { @Override public void setCurrentValue(AccessibleValueEvent e) { value = e.value.intValue(); canvas.redraw(); } @Override public void getMinimumValue(AccessibleValueEvent e) { e.value = Integer.valueOf(min); } @Override public void getMaximumValue(AccessibleValueEvent e) { e.value = Integer.valueOf(max); } @Override public void getCurrentValue(AccessibleValueEvent e) { e.value = Integer.valueOf(value); } }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
From source file:examples.cnn.ImagesClassification.java
public static void main(String[] args) { SparkConf conf = new SparkConf(); conf.setAppName("Images CNN Classification"); conf.setMaster(String.format("local[%d]", NUM_CORES)); conf.set(SparkDl4jMultiLayer.AVERAGE_EACH_ITERATION, String.valueOf(true)); try (JavaSparkContext sc = new JavaSparkContext(conf)) { JavaRDD<String> raw = sc.textFile("data/images-data-rgb.csv"); String first = raw.first(); JavaPairRDD<String, String> labelData = raw.filter(f -> f.equals(first) == false).mapToPair(r -> { String[] tab = r.split(";"); return new Tuple2<>(tab[0], tab[1]); });/*from ww w.j a v a 2 s . c o m*/ Map<String, Long> labels = labelData.map(t -> t._1).distinct().zipWithIndex() .mapToPair(t -> new Tuple2<>(t._1, t._2)).collectAsMap(); log.info("Number of labels {}", labels.size()); labels.forEach((a, b) -> log.info("{}: {}", a, b)); NetworkTrainer trainer = new NetworkTrainer.Builder().model(ModelLibrary.net1) .networkToSparkNetwork(net -> new SparkDl4jMultiLayer(sc, net)).numLabels(labels.size()) .cores(NUM_CORES).build(); JavaRDD<Tuple2<INDArray, double[]>> labelsWithData = labelData.map(t -> { INDArray label = FeatureUtil.toOutcomeVector(labels.get(t._1).intValue(), labels.size()); double[] arr = Arrays.stream(t._2.split(" ")).map(normalize1).mapToDouble(Double::doubleValue) .toArray(); return new Tuple2<>(label, arr); }); JavaRDD<Tuple2<INDArray, double[]>>[] splited = labelsWithData.randomSplit(new double[] { .8, .2 }, seed); JavaRDD<DataSet> testDataset = splited[1].map(t -> { INDArray features = Nd4j.create(t._2, new int[] { 1, t._2.length }); return new DataSet(features, t._1); }).cache(); log.info("Number of test images {}", testDataset.count()); JavaRDD<DataSet> plain = splited[0].map(t -> { INDArray features = Nd4j.create(t._2, new int[] { 1, t._2.length }); return new DataSet(features, t._1); }); /* * JavaRDD<DataSet> flipped = splited[0].randomSplit(new double[] { .5, .5 }, seed)[0]. */ JavaRDD<DataSet> flipped = splited[0].map(t -> { double[] arr = t._2; int idx = 0; double[] farr = new double[arr.length]; for (int i = 0; i < arr.length; i += trainer.width) { double[] temp = Arrays.copyOfRange(arr, i, i + trainer.width); ArrayUtils.reverse(temp); for (int j = 0; j < trainer.height; ++j) { farr[idx++] = temp[j]; } } INDArray features = Nd4j.create(farr, new int[] { 1, farr.length }); return new DataSet(features, t._1); }); JavaRDD<DataSet> trainDataset = plain.union(flipped).cache(); log.info("Number of train images {}", trainDataset.count()); trainer.train(trainDataset, testDataset); } }
From source file:com.quangphuong.crawler.util.HighlightsOfflineCrawler.java
public static void main(String[] args) { webClient.getOptions().setJavaScriptEnabled(false); webClient.getOptions().setCssEnabled(false); webClient.getOptions().setThrowExceptionOnFailingStatusCode(false); // webClient.setJavaScriptTimeout(2 * 1000); int y = startY; int m = startM; int d = startD; int date = 0; File f = new File(cachePath); if (f.exists() && !f.isDirectory()) { date = (Integer) ObjectIO.read(cachePath); y = date / 10000;// www .j a v a 2 s. co m m = date % 10000; d = m % 100; System.out.println("D: " + d + "-M: " + m + "-Y: " + y); } boolean goNext = true; while (date != stopDate) { date = y + m + d; // Crawler String dateStr = String.valueOf(date); String link = AppConstant.videoPrefix + dateStr; try { System.out.println("Link: " + link); HtmlPage page = webClient.getPage(link); goNext = page.getWebResponse().getStatusCode() != 503; List<HtmlElement> tables = (List<HtmlElement>) page.getByXPath(AppConstant.hightlightTables); int count = 0; String kind = ""; String tournament = ""; for (HtmlElement table : tables) { count++; //Get kind HtmlElement span = table.getFirstByXPath(AppConstant.highlightKind); if (span != null && span.getAttribute("class").equals("whitetitle")) { kind = span.getTextContent(); System.out.println(kind); } // Get Tournament if (table.getAttribute("background") != null && !"".equals(table.getAttribute("background"))) { HtmlElement el = table.getFirstByXPath(AppConstant.highlightTournament); tournament = el.getTextContent(); System.out.println(tournament); } else // Get matches { if (count != 1 && (table.getAttribute("bgcolor").equals(""))) { List<HtmlElement> matches = (List<HtmlElement>) table .getByXPath(AppConstant.highlightMatches); for (HtmlElement el : matches) { // System.out.println(el.asXml()); HtmlElement tmp = el.getFirstByXPath(AppConstant.highlightMatch); String match = tmp.getTextContent().trim(); tmp = el.getFirstByXPath(AppConstant.highlightMatchTime); String time = tmp.getTextContent().trim(); tmp = el.getFirstByXPath(AppConstant.highlightMatchLogoTeam1); String logoTeam1; try { logoTeam1 = tmp.getAttribute("src"); } catch (Exception e) { logoTeam1 = ""; } tmp = el.getFirstByXPath(AppConstant.highlightMatchScore); String score = tmp.getTextContent().trim(); tmp = el.getFirstByXPath(AppConstant.highlightMatchLogoTeam2); String logoTeam2; try { logoTeam2 = tmp.getAttribute("src"); } catch (Exception e) { logoTeam2 = ""; } // webClient.waitForBackgroundJavaScript(10 * 1000); tmp = el.getFirstByXPath(AppConstant.highlightMatchLink); String highlightLink; try { highlightLink = tmp.getAttribute("href"); } catch (Exception e) { highlightLink = ""; } tmp = el.getFirstByXPath(AppConstant.highlightMatchFullLink); String fullMatchLink; try { fullMatchLink = tmp.getAttribute("href"); } catch (Exception e) { fullMatchLink = ""; } tmp = el.getFirstByXPath(AppConstant.highlightMatchLongLink); String longHighlightLink; try { longHighlightLink = tmp.getAttribute("href"); } catch (Exception e) { longHighlightLink = ""; } System.out.println("----" + match + "-" + time + "-" + logoTeam1 + "-" + score + "-" + logoTeam2 + "-" + highlightLink + "-" + fullMatchLink + "-" + longHighlightLink); // System.out.println("kindddddddddddddddd: " + kind); Highlight highlight = new Highlight(0, kind, tournament, match, logoTeam1, logoTeam2, highlightLink, longHighlightLink, fullMatchLink, score, dateStr, time); DBWrapper dBWrapper = new DBWrapper(false); dBWrapper.updateEntity(highlight); } } } } // System.out.println("-------------------"); // System.out.println("Page memory: " + Agent.sizeOf(page)); } catch (Exception ex) { Logger.getLogger(HighlightsOfflineCrawler.class.getName()).log(Level.SEVERE, null, ex); } ObjectIO.write(cachePath, date); if (goNext) { if (m == 1200 && isLastDayOfMonth(d, m, y)) { y += 10000; m = 100; d = 1; } else if (isLastDayOfMonth(d, m, y)) { m += 100; d = 1; } else { d += 1; } } } }
From source file:org.eclipse.swt.snippets.SnippetLauncher.java
public static void main(String[] args) { File sourceDir = SnippetsConfig.SNIPPETS_SOURCE_DIR; boolean hasSource = sourceDir.exists(); int count = 500; if (hasSource) { File[] files = sourceDir.listFiles(); if (files.length > 0) count = files.length;/* www. j av a 2s . c o m*/ } for (int i = 1; i < count; i++) { if (SnippetsConfig.isPrintingSnippet(i)) continue; // avoid printing to printer String className = "Snippet" + i; Class<?> clazz = null; try { clazz = Class.forName(SnippetsConfig.SNIPPETS_PACKAGE + "." + className); } catch (ClassNotFoundException e) { } if (clazz != null) { System.out.println("\n" + clazz.getName()); if (hasSource) { File sourceFile = new File(sourceDir, className + ".java"); try (FileReader reader = new FileReader(sourceFile);) { char[] buffer = new char[(int) sourceFile.length()]; reader.read(buffer); String source = String.valueOf(buffer); int start = source.indexOf("package"); start = source.indexOf("/*", start); int end = source.indexOf("* For a list of all"); System.out.println(source.substring(start, end - 3)); boolean skip = false; String platform = SWT.getPlatform(); if (source.contains("PocketPC")) { platform = "PocketPC"; skip = true; } else if (source.contains("OpenGL")) { platform = "OpenGL"; skip = true; } else if (source.contains("JavaXPCOM")) { platform = "JavaXPCOM"; skip = true; } else { String[] platforms = { "win32", "gtk" }; for (int p = 0; p < platforms.length; p++) { if (!platforms[p].equals(platform) && source.contains("." + platforms[p])) { platform = platforms[p]; skip = true; break; } } } if (skip) { System.out.println("...skipping " + platform + " example..."); continue; } } catch (Exception e) { } } Method method = null; String[] param = SnippetsConfig.getSnippetArguments(i); try { method = clazz.getMethod("main", param.getClass()); } catch (NoSuchMethodException e) { System.out.println(" Did not find main(String [])"); } if (method != null) { try { method.invoke(clazz, new Object[] { param }); } catch (IllegalAccessException e) { System.out.println(" Failed to launch (illegal access)"); } catch (IllegalArgumentException e) { System.out.println(" Failed to launch (illegal argument to main)"); } catch (InvocationTargetException e) { System.out.println(" Exception in Snippet: " + e.getTargetException()); } } } } }
From source file:hu.fnf.devel.wishbox.persistence.Application.java
public static void main(String[] args) throws Exception { ConfigurableApplicationContext context = new SpringApplicationBuilder(Application.class).run(args); //TODO: @Autowire? RepositoryUser repositoryUser = context.getBean(RepositoryUser.class); RepositoryItem repositoryItem = context.getBean(RepositoryItem.class); RepositoryUrl repositoryUrl = context.getBean(RepositoryUrl.class); // save a couple of customers User user = new User(String.valueOf(13L)); user.setFirstName("fname"); user.setLastName("lname"); Url url = new Url(); url.setUrl("http://"); repositoryUrl.save(url);// w ww . j a v a 2 s.c o m List<Item> items = new ArrayList<Item>(); Item item = new Item(); item.setName("item1"); item.setPattern("pattern1"); item.setFound(url); Item item2 = new Item(); item2.setName("item2"); item2.setPattern("pattern2"); item2.setFound(url); repositoryItem.save(item); repositoryItem.save(item2); items.add(item); items.add(item2); user.setItems(items); repositoryUser.save(user); }
From source file:examples.cnn.cifar.Cifar10Classification.java
public static void main(String[] args) { CifarReader.downloadAndExtract();//from www . j a v a2 s. co m int numLabels = 10; SparkConf conf = new SparkConf(); conf.setMaster(String.format("local[%d]", NUM_CORES)); conf.setAppName("Cifar-10 CNN Classification"); conf.set(SparkDl4jMultiLayer.AVERAGE_EACH_ITERATION, String.valueOf(true)); try (JavaSparkContext sc = new JavaSparkContext(conf)) { NetworkTrainer trainer = new NetworkTrainer.Builder().model(ModelLibrary.net2) .networkToSparkNetwork(net -> new SparkDl4jMultiLayer(sc, net)).numLabels(numLabels) .cores(NUM_CORES).build(); JavaPairRDD<String, PortableDataStream> files = sc.binaryFiles("data/cifar-10-batches-bin"); JavaRDD<double[]> imagesTrain = files .filter(f -> ArrayUtils.contains(CifarReader.TRAIN_DATA_FILES, extractFileName.apply(f._1))) .flatMap(f -> CifarReader.rawDouble(f._2.open())); JavaRDD<double[]> imagesTest = files .filter(f -> CifarReader.TEST_DATA_FILE.equals(extractFileName.apply(f._1))) .flatMap(f -> CifarReader.rawDouble(f._2.open())); JavaRDD<DataSet> testDataset = imagesTest.map(i -> { INDArray label = FeatureUtil.toOutcomeVector(Double.valueOf(i[0]).intValue(), numLabels); double[] arr = Arrays.stream(ArrayUtils.remove(i, 0)).boxed().map(normalize2) .mapToDouble(Double::doubleValue).toArray(); INDArray features = Nd4j.create(arr, new int[] { 1, arr.length }); return new DataSet(features, label); }).cache(); log.info("Number of test images {}", testDataset.count()); JavaPairRDD<INDArray, double[]> labelsWithDataTrain = imagesTrain.mapToPair(i -> { INDArray label = FeatureUtil.toOutcomeVector(Double.valueOf(i[0]).intValue(), numLabels); double[] arr = Arrays.stream(ArrayUtils.remove(i, 0)).boxed().map(normalize2) .mapToDouble(Double::doubleValue).toArray(); return new Tuple2<>(label, arr); }); JavaRDD<DataSet> flipped = labelsWithDataTrain.map(t -> { double[] arr = t._2; int idx = 0; double[] farr = new double[arr.length]; for (int i = 0; i < arr.length; i += trainer.getWidth()) { double[] temp = Arrays.copyOfRange(arr, i, i + trainer.getWidth()); ArrayUtils.reverse(temp); for (int j = 0; j < trainer.getHeight(); ++j) { farr[idx++] = temp[j]; } } INDArray features = Nd4j.create(farr, new int[] { 1, farr.length }); return new DataSet(features, t._1); }); JavaRDD<DataSet> trainDataset = labelsWithDataTrain.map(t -> { INDArray features = Nd4j.create(t._2, new int[] { 1, t._2.length }); return new DataSet(features, t._1); }).union(flipped).cache(); log.info("Number of train images {}", trainDataset.count()); trainer.train(trainDataset, testDataset); } }