List of usage examples for java.util Arrays toString
public static String toString(Object[] a)
From source file:com.netscape.cmstools.CMCSharedToken.java
public static void main(String args[]) throws Exception { boolean isVerificationMode = false; // developer debugging only Options options = createOptions();//from w w w . j a v a2 s . com CommandLine cmd = null; try { CommandLineParser parser = new PosixParser(); cmd = parser.parse(options, args); } catch (Exception e) { printError(e.getMessage()); System.exit(1); } if (cmd.hasOption("help")) { printHelp(); System.exit(0); } boolean verbose = cmd.hasOption("v"); String databaseDir = cmd.getOptionValue("d", "."); String passphrase = cmd.getOptionValue("s"); if (passphrase == null) { printError("Missing passphrase"); System.exit(1); } if (verbose) { System.out.println("passphrase String = " + passphrase); System.out.println("passphrase UTF-8 bytes = "); System.out.println(Arrays.toString(passphrase.getBytes("UTF-8"))); } String tokenName = cmd.getOptionValue("h"); String tokenPassword = cmd.getOptionValue("p"); String issuanceProtCertFilename = cmd.getOptionValue("b"); String issuanceProtCertNick = cmd.getOptionValue("n"); String output = cmd.getOptionValue("o"); try { CryptoManager.initialize(databaseDir); CryptoManager manager = CryptoManager.getInstance(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); tokenName = token.getName(); manager.setThreadToken(token); Password password = new Password(tokenPassword.toCharArray()); token.login(password); X509Certificate issuanceProtCert = null; if (issuanceProtCertFilename != null) { if (verbose) System.out.println("Loading issuance protection certificate"); String encoded = new String(Files.readAllBytes(Paths.get(issuanceProtCertFilename))); byte[] issuanceProtCertData = Cert.parseCertificate(encoded); issuanceProtCert = manager.importCACertPackage(issuanceProtCertData); if (verbose) System.out.println("issuance protection certificate imported"); } else { // must have issuance protection cert nickname if file not provided if (verbose) System.out.println("Getting cert by nickname: " + issuanceProtCertNick); if (issuanceProtCertNick == null) { System.out.println( "Invallid command: either nickname or PEM file must be provided for Issuance Protection Certificate"); System.exit(1); } issuanceProtCert = getCertificate(tokenName, issuanceProtCertNick); } EncryptionAlgorithm encryptAlgorithm = EncryptionAlgorithm.AES_128_CBC_PAD; KeyWrapAlgorithm wrapAlgorithm = KeyWrapAlgorithm.RSA; if (verbose) System.out.println("Generating session key"); SymmetricKey sessionKey = CryptoUtil.generateKey(token, KeyGenAlgorithm.AES, 128, null, true); if (verbose) System.out.println("Encrypting passphrase"); byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 }; byte[] secret_data = CryptoUtil.encryptUsingSymmetricKey(token, sessionKey, passphrase.getBytes("UTF-8"), encryptAlgorithm, new IVParameterSpec(iv)); if (verbose) System.out.println("Wrapping session key with issuance protection cert"); byte[] issuanceProtWrappedSessionKey = CryptoUtil.wrapUsingPublicKey(token, issuanceProtCert.getPublicKey(), sessionKey, wrapAlgorithm); // final_data takes this format: // SEQUENCE { // encryptedSession OCTET STRING, // encryptedPrivate OCTET STRING // } DerOutputStream tmp = new DerOutputStream(); tmp.putOctetString(issuanceProtWrappedSessionKey); tmp.putOctetString(secret_data); DerOutputStream out = new DerOutputStream(); out.write(DerValue.tag_Sequence, tmp); byte[] final_data = out.toByteArray(); String final_data_b64 = Utils.base64encode(final_data, true); if (final_data_b64 != null) { System.out.println("\nEncrypted Secret Data:"); System.out.println(final_data_b64); } else System.out.println("Failed to produce final data"); if (output != null) { System.out.println("\nStoring Base64 secret data into " + output); try (FileWriter fout = new FileWriter(output)) { fout.write(final_data_b64); } } if (isVerificationMode) { // developer use only PrivateKey wrappingKey = null; if (issuanceProtCertNick != null) wrappingKey = (org.mozilla.jss.crypto.PrivateKey) getPrivateKey(tokenName, issuanceProtCertNick); else wrappingKey = CryptoManager.getInstance().findPrivKeyByCert(issuanceProtCert); System.out.println("\nVerification begins..."); byte[] wrapped_secret_data = Utils.base64decode(final_data_b64); DerValue wrapped_val = new DerValue(wrapped_secret_data); // val.tag == DerValue.tag_Sequence DerInputStream wrapped_in = wrapped_val.data; DerValue wrapped_dSession = wrapped_in.getDerValue(); byte wrapped_session[] = wrapped_dSession.getOctetString(); System.out.println("wrapped session key retrieved"); DerValue wrapped_dPassphrase = wrapped_in.getDerValue(); byte wrapped_passphrase[] = wrapped_dPassphrase.getOctetString(); System.out.println("wrapped passphrase retrieved"); SymmetricKey ver_session = CryptoUtil.unwrap(token, SymmetricKey.AES, 128, SymmetricKey.Usage.UNWRAP, wrappingKey, wrapped_session, wrapAlgorithm); byte[] ver_passphrase = CryptoUtil.decryptUsingSymmetricKey(token, new IVParameterSpec(iv), wrapped_passphrase, ver_session, encryptAlgorithm); String ver_spassphrase = new String(ver_passphrase, "UTF-8"); CryptoUtil.obscureBytes(ver_passphrase, "random"); System.out.println("ver_passphrase String = " + ver_spassphrase); System.out.println("ver_passphrase UTF-8 bytes = "); System.out.println(Arrays.toString(ver_spassphrase.getBytes("UTF-8"))); if (ver_spassphrase.equals(passphrase)) System.out.println("Verification success!"); else System.out.println("Verification failure! ver_spassphrase=" + ver_spassphrase); } } catch (Exception e) { if (verbose) e.printStackTrace(); printError(e.getMessage()); System.exit(1); } }
From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosGraphCreator.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input file"); inputOpt.setArgs(1);/*www. j a v a 2s.co m*/ inputOpt.setRequired(true); Option outputOpt = OptionBuilder.create(OUT); outputOpt.setArgName("OUTPUT"); outputOpt.setDescription("Output directory"); outputOpt.setArgs(1); outputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); Option optFileOpt = OptionBuilder.create(OPTIONS_FILE); optFileOpt.setArgName("FILE"); optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource"); optFileOpt.setArgs(1); options.addOption(inputOpt); options.addOption(outputOpt); options.addOption(inClassOpt); options.addOption(optFileOpt); CommandLineParser parser = new PosixParser(); try { PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, new BlueprintsPersistenceBackendFactory()); CommandLine commandLine = parser.parse(options, args); URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN)); URI targetUri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(OUT))); Class<?> inClazz = KyanosGraphCreator.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi", new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap() .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE); Resource sourceResource = resourceSet.createResource(sourceUri); Map<String, Object> loadOpts = new HashMap<String, Object>(); if ("zxmi".equals(sourceUri.fileExtension())) { loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE); } Runtime.getRuntime().gc(); long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}", MessageUtil.byteCountToDisplaySize(initialUsedMemory))); LOG.log(Level.INFO, "Loading source resource"); sourceResource.load(loadOpts); LOG.log(Level.INFO, "Source resource loaded"); Runtime.getRuntime().gc(); long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory))); LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory))); Resource targetResource = resourceSet.createResource(targetUri); Map<String, Object> saveOpts = new HashMap<String, Object>(); if (commandLine.hasOption(OPTIONS_FILE)) { Properties properties = new Properties(); properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE)))); for (final Entry<Object, Object> entry : properties.entrySet()) { saveOpts.put((String) entry.getKey(), (String) entry.getValue()); } } List<StoreOption> storeOptions = new ArrayList<StoreOption>(); storeOptions.add(BlueprintsResourceOptions.EStoreGraphOption.AUTOCOMMIT); saveOpts.put(BlueprintsResourceOptions.STORE_OPTIONS, storeOptions); targetResource.save(saveOpts); LOG.log(Level.INFO, "Start moving elements"); targetResource.getContents().clear(); targetResource.getContents().addAll(sourceResource.getContents()); LOG.log(Level.INFO, "End moving elements"); LOG.log(Level.INFO, "Start saving"); targetResource.save(saveOpts); LOG.log(Level.INFO, "Saved"); if (targetResource instanceof PersistentResourceImpl) { PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) targetResource); } else { targetResource.unload(); } } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }
From source file:edu.oregonstate.eecs.mcplan.domains.inventory.InventorySimulator.java
public static void main(final String[] argv) throws IOException { final RandomGenerator rng = new MersenneTwister(42); final int Nproducts = 2; final int max_inventory = 10; final double warehouse_cost = 1; final int min_order = 1; final int max_order = 2; final double delivery_probability = 0.5; final int max_demand = 5; final int[] price = new int[] { 1, 2 }; final InventoryProblem problem = InventoryProblem.TwoProducts(); // Nproducts, price, max_inventory, warehouse_cost, min_order, max_order, delivery_probability, max_demand ); while (true) { final InventoryState s = new InventoryState(rng, problem); final InventorySimulator sim = new InventorySimulator(s); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (!s.isTerminal()) { System.out.println(sim.state()); final String cmd = reader.readLine(); final String[] tokens = cmd.split(","); final InventoryAction a; if ("n".equals(tokens[0])) { a = new InventoryNothingAction(); } else { final int product = Integer.parseInt(tokens[0]); final int quantity = Integer.parseInt(tokens[1]); a = new InventoryOrderAction(product, quantity, s.problem.cost[product]); }//from ww w .ja v a 2s. c om sim.takeAction(new JointAction<InventoryAction>(a)); System.out.println("r = " + Arrays.toString(sim.reward())); } // System.out.print( "Hand: " ); // System.out.print( sim.state().player_hand ); // System.out.print( " (" ); // final ArrayList<int[]> values = sim.state().player_hand.values(); // for( int i = 0; i < values.size(); ++i ) { // if( i > 0 ) { // System.out.print( ", " ); // } // System.out.print( Arrays.toString( values.get( i ) ) ); // } // System.out.println( ")" ); // // System.out.print( "Reward: " ); // System.out.println( Arrays.toString( sim.reward() ) ); // System.out.print( "Dealer hand: " ); // System.out.print( sim.state().dealerHand().toString() ); // System.out.print( " (" ); // System.out.print( SpBjHand.handValue( sim.state().dealerHand() )[0] ); // System.out.println( ")" ); // System.out.println( "----------------------------------------" ); } }
From source file:edu.umd.cloud9.collection.trec.CountTrecDocuments.java
/** * Dispatches command-line arguments to the tool via the {@code ToolRunner}. *//*from ww w .j a va 2s .c om*/ public static void main(String[] args) throws Exception { LOG.info("Running " + CountTrecDocuments.class.getCanonicalName() + " with args " + Arrays.toString(args)); ToolRunner.run(new CountTrecDocuments(), args); }
From source file:io.tempra.AppServer.java
public static void main(String[] args) throws Exception { try {/*from www. j a va2 s . c o m*/ // String dir = getProperty("storageLocal");// // System.getProperty("user.home"); String arch = "Win" + System.getProperty("sun.arch.data.model"); System.out.println("sun.arch.data.model " + arch); // Sample to force java load dll or so on a filesystem // InputStream in = AppServer.class.getResourceAsStream("/dll/" + // arch + "/RechargeRPC.dll"); // // File jCliSiTefI = new File(dir + "/" + "RechargeRPC.dll"); // System.out.println("Writing dll to: " + // jCliSiTefI.getAbsolutePath()); // OutputStream os = new FileOutputStream(jCliSiTefI); // byte[] buffer = new byte[4096]; // int length; // while ((length = in.read(buffer)) > 0) { // os.write(buffer, 0, length); // } // os.close(); // in.close(); // System.load(jCliSiTefI.toString()); // addLibraryPath(dir); } catch (Exception e) { e.printStackTrace(); } ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); Server jettyServer = new Server(Integer.parseInt(getProperty("localport"))); // security configuration // FilterHolder holder = new FilterHolder(CrossOriginFilter.class); // holder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, // "*"); // holder.setInitParameter("allowCredentials", "true"); // holder.setInitParameter( // CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); // holder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, // "GET,POST,HEAD"); // holder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, // "X-Requested-With,Content-Type,Accept,Origin"); // holder.setName("cross-origin"); // context.addFilter(holder, fm); ResourceHandler resource_handler = new ResourceHandler(); // add application on embedded server boolean servApp = true; boolean quioskMode = false; // if (System.getProperty("noServApp") != null ) // if (System.getProperty("noServApp").equalsIgnoreCase("true")) // servApp = false; if (servApp) { // ProtectionDomain domain = AppServer.class.getProtectionDomain(); String webDir = AppServer.class.getResource("/webapp").toExternalForm(); System.out.println("Jetty WEB DIR >>>>" + webDir); resource_handler.setDirectoriesListed(true); resource_handler.setWelcomeFiles(new String[] { "index.html" }); resource_handler.setResourceBase(webDir); // // "C:/git/tsAgenciaVirtual/www/"); // resource_handler.setResourceBase("C:/git/tsAgenciaVirtual/www/"); // copyJarResourceToFolder((JarURLConnection) AppServer.class // .getResource("/app").openConnection(), createTempDir("app")); // resource_handler.setResourceBase(System // .getProperty("java.io.tmpdir") + "/app"); } // sample to add rest services on container context.addServlet(FileUploadServlet.class, "/upload"); ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/services/*"); jerseyServlet.setInitOrder(0); jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", RestServices.class.getCanonicalName() + "," + RestServices.class.getCanonicalName()); HandlerList handlers = new HandlerList(); // context.addFilter(holder, "/*", EnumSet.of(DispatcherType.REQUEST)); handlers.setHandlers(new Handler[] { resource_handler, context, // wscontext, new DefaultHandler() }); jettyServer.setHandler(handlers); try { // Initialize javax.websocket layer ServerContainer wscontainer = WebSocketServerContainerInitializer.configureContext(context); wscontainer.setDefaultMaxSessionIdleTimeout(TimeUnit.HOURS.toMillis(1000)); // Add WebSocket endpoint to javax.websocket layer wscontainer.addEndpoint(FileUpload.class); } catch (Throwable t) { t.printStackTrace(System.err); } // try { jettyServer.start(); jettyServer.dump(System.err); if (servApp && quioskMode) { try { Process process = new ProcessBuilder( "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "--kiosk", "--kiosk-printing", "--auto", "--disable-pinch", "--incognito", "--disable-session-crashed-bubble", "--overscroll-history-navigation=0", "http://localhost:" + getProperty("localport")).start(); // Process process = // Runtime.getRuntime().exec(" -kiosk http://localhost:8080"); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; System.out.printf("Output of running %s is:", Arrays.toString(args)); while ((line = br.readLine()) != null) { System.out.println(line); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } // } finally { // jettyServer.destroy(); // }//} jettyServer.join(); }
From source file:com.hortonworks.historian.model.HistorianModelGenerator.java
public static void main(String[] args) throws Exception { HistorianModelGenerator HistorianDataModelGenerator = new HistorianModelGenerator(); System.out.println("HistorianDataModelAsJSON = " + HistorianDataModelGenerator.getModelAsJson()); TypesDef typesDef = HistorianDataModelGenerator.getTypesDef(); for (EnumTypeDefinition enumType : typesDef.enumTypesAsJavaList()) { System.out.println(String.format("%s(%s) - values %s", enumType.name, EnumType.class.getSimpleName(), Arrays.toString(enumType.enumValues))); }/*from ww w . j ava2s.c o m*/ for (StructTypeDefinition structType : typesDef.structTypesAsJavaList()) { System.out.println(String.format("%s(%s) - attributes %s", structType.typeName, StructType.class.getSimpleName(), Arrays.toString(structType.attributeDefinitions))); } for (HierarchicalTypeDefinition<ClassType> classType : typesDef.classTypesAsJavaList()) { System.out.println(String.format("%s(%s) - super types [%s] - attributes %s", classType.typeName, ClassType.class.getSimpleName(), StringUtils.join(classType.superTypes, ","), Arrays.toString(classType.attributeDefinitions))); } for (HierarchicalTypeDefinition<TraitType> traitType : typesDef.traitTypesAsJavaList()) { System.out.println(String.format("%s(%s) - %s", traitType.typeName, TraitType.class.getSimpleName(), Arrays.toString(traitType.attributeDefinitions))); } }
From source file:edu.umd.cloud9.collection.clue.ClueWarcForwardIndexBuilder.java
/** * Dispatches command-line arguments to the tool via the {@code ToolRunner}. */// ww w . j ava2s . c o m public static void main(String[] args) throws Exception { LOG.info("Running " + ClueWarcForwardIndexBuilder.class.getCanonicalName() + " with args " + Arrays.toString(args)); ToolRunner.run(new ClueWarcForwardIndexBuilder(), args); }
From source file:alluxio.yarn.ApplicationMaster.java
/** * @param args Command line arguments to launch application master *///w ww . j a v a 2 s . c o m public static void main(String[] args) { Options options = new Options(); options.addOption("num_workers", true, "Number of Alluxio workers to launch. Default 1"); options.addOption("master_address", true, "(Required) Address to run Alluxio master"); options.addOption("resource_path", true, "(Required) HDFS path containing the Application Master"); try { LOG.info("Starting Application Master with args {}", Arrays.toString(args)); final CommandLine cliParser = new GnuParser().parse(options, args); YarnConfiguration conf = new YarnConfiguration(); UserGroupInformation.setConfiguration(conf); if (UserGroupInformation.isSecurityEnabled()) { String user = System.getenv("ALLUXIO_USER"); UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user); for (Token token : UserGroupInformation.getCurrentUser().getTokens()) { ugi.addToken(token); } LOG.info("UserGroupInformation: " + ugi); ugi.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { runApplicationMaster(cliParser); return null; } }); } else { runApplicationMaster(cliParser); } } catch (Exception e) { LOG.error("Error running Application Master", e); System.exit(1); } }
From source file:com.splout.db.dnode.TCPStreamer.java
/** * This main method can be used for testing the TCP interface directly to a * local DNode. Will ask for protocol input from Stdin and print output to * Stdout//from ww w . j a v a 2 s . c o m */ public static void main(String[] args) throws UnknownHostException, IOException, SerializationException { SploutConfiguration config = SploutConfiguration.get(); Socket clientSocket = new Socket("localhost", config.getInt(DNodeProperties.STREAMING_PORT)); DataInputStream inFromServer = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream())); DataOutputStream outToServer = new DataOutputStream( new BufferedOutputStream(clientSocket.getOutputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter tablespace: "); String tablespace = reader.readLine(); System.out.println("Enter version number: "); long versionNumber = Long.parseLong(reader.readLine()); System.out.println("Enter partition: "); int partition = Integer.parseInt(reader.readLine()); System.out.println("Enter query: "); String query = reader.readLine(); outToServer.writeUTF(tablespace); outToServer.writeLong(versionNumber); outToServer.writeInt(partition); outToServer.writeUTF(query); outToServer.flush(); byte[] buffer = new byte[0]; boolean read; do { read = false; int nBytes = inFromServer.readInt(); if (nBytes > 0) { buffer = new byte[nBytes]; int inRead = inFromServer.read(buffer); if (inRead > 0) { Object[] res = ResultSerializer.deserialize(ByteBuffer.wrap(buffer), Object[].class); read = true; System.out.println(Arrays.toString(res)); } } } while (read); clientSocket.close(); }
From source file:io.bfscan.clueweb12.DumpWarcRecordsToTermIds.java
/** * Dispatches command-line arguments to the tool via the <code>ToolRunner</code>. *//*from w w w .j av a 2 s. c o m*/ public static void main(String[] args) throws Exception { LOG.info("Running " + DumpWarcRecordsToTermIds.class.getCanonicalName() + " with args " + Arrays.toString(args)); ToolRunner.run(new DumpWarcRecordsToTermIds(), args); }