List of usage examples for java.lang String String
public String()
From source file:GetMethod.java
public static void main(String[] args) { Method[] ms = String.class.getMethods(); for (int i = 0; i < ms.length; i++) { // System.out.println(ms[i].getName()); }/*from w w w. ja v a 2 s . com*/ Method[] ims = XMLReader.class.getMethods(); for (int i = 0; i < ims.length; i++) { // System.out.println(ims[i].getName()); } Method[] sms = Size.class.getMethods(); for (int i = 0; i < sms.length; i++) { // System.out.println(sms[i].getName()); } String pc = new String(); try { Method setCpu = String.class.getMethod("toString", String.class); setCpu.invoke(pc, "Intel 3.0"); System.out.println(pc.toString()); } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
static public void main(String args[]) throws Exception { URL myurl[] = { new URL("file:///C:/CH3/ClassLoader/web/"), new URL("http://www.java2s.edu/~xyx/test/") }; URLClassLoader x = new URLClassLoader(myurl); Class c = x.loadClass("TestURL"); Class getArg1[] = { (new String[1]).getClass() }; Method m = c.getMethod("main", getArg1); String[] my1 = { "arg1 passed", "arg2 passed" }; Object myarg1[] = { my1 };/*from www . ja va 2 s. c o m*/ m.invoke(null, myarg1); Object ob = c.newInstance(); Class arg2[] = {}; Method m2 = c.getMethod("tt", arg2); m2.invoke(ob, null); Class arg3[] = { (new String()).getClass(), int.class }; Method m3 = c.getMethod("tt", arg3); Object myarg2[] = { "Arg1", new Integer(100) }; m3.invoke(ob, myarg2); }
From source file:SampleModifier.java
public static void main(String[] args) { String s = new String(); printModifiers(s); }
From source file:implementation.java
public static void main(String[] args) throws IOException { // Network Variables KUSOCKET ClientSocket = new KUSOCKET(); ENDPOINT ClientAddress = new ENDPOINT("0.0.0.0", 0); ENDPOINT BroadcastAddress = new ENDPOINT("255.255.255.255", TokenAccess.SERVER_PORT_NUMBER); ENDPOINT AnyAddress = new ENDPOINT("0.0.0.0", 0); ENDPOINT ServerAddress = new ENDPOINT(); MESSAGE OutgoingMessage = new MESSAGE(); MESSAGE IncomingMessage = new MESSAGE(); // Output variables int CommentLength = TokenAccess.COMMENT_LENGTH; String Comment = new String(); // Protocol variables Timer firstnode = new Timer(); Timer tokentimer = new Timer(); Timer tokenlost = new Timer(); Timer exit = new Timer(); int DialogueNumber = 0; int numRetries = 0; Integer addressIP[] = new Integer[2]; int trigger = 0; String lanAddress = "192.168.1.67"; // Create socket and await connection /////////////////////////////////////// // -------------------------------------------------------------------------- // FINITE STATE MACHINE // -------------------------------------------------------------------------- System.err.println("FSM Started ===================" + '\n'); // FSM variables TokenAccess.STATES state = TokenAccess.STATES.STATE_INITIAL; // Initial STATE TokenAccess.STATES lastState = state; // Last STATE boolean bContinueEventWait = false; boolean bContinueStateLoop = true; String last = null;//from ww w . j a v a2 s. c om ClientSocket.CreateUDPSocket(ClientAddress); while (bContinueStateLoop) { switch (state) { case STATE_INITIAL: firstnode.Start(TokenAccess.firstnode); state = TokenAccess.STATES.STATE_STARTED; bContinueEventWait = false; // Stop Events loop break; case STATE_STARTED: ClientSocket.MakeConnection(AnyAddress); if (firstnode.isExpired()) { tokentimer.Start(TokenAccess.tokentimer); System.out.println("implementation.main()"); // adding local host ip to array String t = InetAddress.getLocalHost().getHostAddress(); String[] split = t.split("\\."); addressIP[0] = Integer.parseInt(split[3]); System.out.println(split[3]); state = TokenAccess.STATES.STATE_TOKENED; bContinueEventWait = false;// Stop Events loop } boolean isMessageQueued = false; isMessageQueued = ClientSocket.RetrieveQueuedMessage(TokenAccess.READ_INTERVAL, IncomingMessage, ServerAddress); if (isMessageQueued && (IncomingMessage.Type == TokenAccess.PDU_CONNECT)) { System.out.println("ring exists"); //pdu_connect used instead of ring exisits state = TokenAccess.STATES.STATE_tokenLess; bContinueEventWait = false; } case STATE_tokenLess: ClientSocket.MakeConnection(AnyAddress); while (state == TokenAccess.STATES.STATE_tokenLess) { // Instructs the socket to accept // building ip address message OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_CONNECT, InetAddress.getLocalHost().getHostAddress(), InetAddress.getLocalHost().getHostAddress().length()); //broadcasting ip address ClientSocket.DeliverMessage(OutgoingMessage, BroadcastAddress); // System.out.println("broadcasting address"); isMessageQueued = ClientSocket.RetrieveQueuedMessage(TokenAccess.READ_INTERVAL, IncomingMessage, ServerAddress); //will trigger if used on a 192 network i didnt know how to use regex for any number and a dot if (isMessageQueued == true && (IncomingMessage.Type == TokenAccess.PDU_CLOSE)) { System.out.println("pdu close"); String ipaddress = IncomingMessage.Buffer; for (int n : addressIP) { if (addressIP[n] == Integer.parseInt(ipaddress)) { String a; a = Integer.toString(addressIP[n]); OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_ACK, InetAddress.getLocalHost().getHostAddress(), InetAddress.getLocalHost().getHostAddress().length()); ENDPOINT exitAddress = new ENDPOINT(a, TokenAccess.SERVER_PORT_NUMBER); ClientSocket.DeliverMessage(OutgoingMessage, exitAddress); addressIP = ArrayUtils.removeElement(addressIP, n); } } } if (last != null && tokenlost.bRunning == false) { tokenlost.Start(TokenAccess.tokenlost); last = null; System.out.println("token lost timer started"); } if (isMessageQueued == true && (IncomingMessage.Type == TokenAccess.CMD_CONNECT)) { System.out.println("token lost timer stopped"); tokenlost.Stop(); } if (tokenlost.isExpired()) { System.out.println("token lost"); for (int n = 0; n < addressIP.length; n++) { String ipaddress = InetAddress.getLocalHost().toString(); int lastdot = ipaddress.lastIndexOf(".") + 1; ipaddress = ipaddress.substring(lastdot, ipaddress.length()); System.out.println(n); if (addressIP[n] == null) { } else { if (addressIP[n] == Integer.parseInt(ipaddress)) { String a; a = Integer.toString(addressIP[n]); System.out.println("variable a " + a); OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_ACK, InetAddress.getLocalHost().getHostAddress(), InetAddress.getLocalHost().getHostAddress().length()); ENDPOINT exitAddress = new ENDPOINT(lanAddress, TokenAccess.SERVER_PORT_NUMBER); ClientSocket.DeliverMessage(OutgoingMessage, exitAddress); OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_TOKEN, InetAddress.getLocalHost().getHostAddress(), InetAddress.getLocalHost().getHostAddress().length()); String b = Integer.toString(addressIP[n]); b = lanAddress; System.out.println(b); ENDPOINT exitAddresss = new ENDPOINT(b, TokenAccess.SERVER_PORT_NUMBER); ClientSocket.DeliverMessage(OutgoingMessage, exitAddresss); } } } } if (exit.isExpired()) { OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_CLOSE, InetAddress.getLocalHost().getHostAddress(), InetAddress.getLocalHost().getHostAddress().length()); exit.Start(30); } if (isMessageQueued && (IncomingMessage.Type == TokenAccess.PDU_TOKEN)) { tokenlost.Stop(); System.out.println(IncomingMessage.Type); state = TokenAccess.STATES.STATE_TOKENED; tokentimer.Start(TokenAccess.tokentimer); break; } } case STATE_TOKENED: while (state == TokenAccess.STATES.STATE_TOKENED) { //send data OutgoingMessage.BuildMessage(0, 0, "ALIVE", CommentLength); ClientSocket.DeliverMessage(OutgoingMessage, BroadcastAddress); tokenlost.Stop(); while (trigger == 0) { System.out.println("TOKENED"); trigger++; } if (tokentimer.isExpired()) { trigger = 0; System.out.println("token expired"); String ipaddress = InetAddress.getLocalHost().toString(); // System.out.println( "System name : "+ipaddress); for (int n = 0; n < addressIP.length; n++) { // System.out.println(n); int lastdot = ipaddress.lastIndexOf(".") + 1; ipaddress = ipaddress.substring(lastdot, ipaddress.length()); // System.out.println("IP address: "+ipaddress); int address1 = Integer.parseInt(ipaddress); System.out.println("made it to line 214"); System.out.println(n); System.out.println(addressIP[0]); if (addressIP[n] == address1) { String a; a = Integer.toString(addressIP[n]); System.out.println("variable a = " + a); String ip = InetAddress.getLocalHost().getHostAddress(); System.out.println("line 226"); System.out.println(ip); OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_TOKEN, InetAddress.getLocalHost().getHostAddress(), InetAddress.getLocalHost().getHostAddress().length()); String b; System.out.println("line 222"); if (n + 1 >= addressIP.length) { b = (ip); // System.out.println(b); } else { b = ip; } System.out.println(b); //b = InetAddress.getLocalHost().toString().substring(0, lastdot); // int slash = b.indexOf("/"); System.out.println(b); ENDPOINT exitAddresss = new ENDPOINT(b, TokenAccess.SERVER_PORT_NUMBER); ClientSocket.DeliverMessage(OutgoingMessage, exitAddresss); System.out.println("exiting tokened state"); state = TokenAccess.STATES.STATE_tokenLess; last = "1"; } break; } } } case STATE_EXIT: while (state == TokenAccess.STATES.STATE_EXIT) { System.exit(0); } } } }
From source file:com.opengsn.controller.client.ControllerClient.java
/** * @param args//from ww w . j av a2s .com */ public static void main(String[] args) { ControllerClient client = new ControllerClient(); String arguments = new String(); for (int i = 0; i < args.length; i++) { arguments = args[i] + " "; } System.out.println("Arguments: " + arguments); if (args.length < 1) { client.usage(null); System.exit(1); } client.process(args); }
From source file:guardar.en.base.de.datos.MainServidor.java
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException { Mongo mongo = new Mongo("localhost", 27017); // nombre de la base de datos DB database = mongo.getDB("paginas"); // coleccion de la db DBCollection collection = database.getCollection("indice"); DBCollection collection_textos = database.getCollection("tabla"); ArrayList<String> lista_textos = new ArrayList(); try {/*from ww w . j a v a 2 s . c o m*/ ServerSocket servidor = new ServerSocket(4545); // Crear un servidor en pausa hasta que un cliente llegue. while (true) { String aux = new String(); lista_textos.clear(); Socket clienteNuevo = servidor.accept();// Si llega se acepta. // Queda en pausa otra vez hasta que un objeto llegue. ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream()); JSONObject request = (JSONObject) entrada.readObject(); String b = (String) request.get("id"); //hacer una query a la base de datos con la palabra que se quiere obtener BasicDBObject query = new BasicDBObject("palabra", b); DBCursor cursor = collection.find(query); ArrayList<DocumentosDB> lista_doc = new ArrayList<>(); // de la query tomo el campo documentos y los agrego a una lista try { while (cursor.hasNext()) { //System.out.println(cursor.next()); BasicDBList campo_documentos = (BasicDBList) cursor.next().get("documentos"); // en el for voy tomando uno por uno los elementos en el campo documentos for (Iterator<Object> it = campo_documentos.iterator(); it.hasNext();) { BasicDBObject dbo = (BasicDBObject) it.next(); //DOC tiene id y frecuencia DocumentosDB doc = new DocumentosDB(); doc.makefn2(dbo); //int id = (int)doc.getId_documento(); //int f = (int)doc.getFrecuencia(); lista_doc.add(doc); //******************************************* //******************************************** //QUERY A LA COLECCION DE TEXTOS /* BasicDBObject query_textos = new BasicDBObject("id", doc.getId_documento());//query DBCursor cursor_textos = collection_textos.find(query_textos); try { while (cursor_textos.hasNext()) { DBObject obj = cursor_textos.next(); String titulo = (String) obj.get("titulo"); titulo = titulo + "\n\n"; String texto = (String) obj.get("texto"); String texto_final = titulo + texto; aux = texto_final; lista_textos.add(texto_final); } } finally { cursor_textos.close(); }*/ //System.out.println(doc.getId_documento()); //System.out.println(doc.getFrecuencia()); } // end for } //end while query } finally { cursor.close(); } // ordeno la lista de menor a mayor Collections.sort(lista_doc, new Comparator<DocumentosDB>() { @Override public int compare(DocumentosDB o1, DocumentosDB o2) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. return o1.getFrecuencia().compareTo(o2.getFrecuencia()); } }); int tam = lista_doc.size() - 1; for (int j = tam; j >= 0; j--) { BasicDBObject query_textos = new BasicDBObject("id", (int) lista_doc.get(j).getId_documento().intValue());//query DBCursor cursor_textos = collection_textos.find(query_textos);// lo busco try { while (cursor_textos.hasNext()) { DBObject obj = cursor_textos.next(); String titulo = "*******************************"; titulo += (String) obj.get("titulo"); int f = (int) lista_doc.get(j).getFrecuencia().intValue(); String strinf = Integer.toString(f); titulo += "******************************* frecuencia:" + strinf; titulo = titulo + "\n\n"; String texto = (String) obj.get("texto"); String texto_final = titulo + texto + "\n\n"; aux = aux + texto_final; //lista_textos.add(texto_final); } } finally { cursor_textos.close(); } } //actualizar el cache try { Socket cliente_cache = new Socket("localhost", 4500); // nos conectamos con el servidor ObjectOutputStream mensaje_cache = new ObjectOutputStream(cliente_cache.getOutputStream()); // get al output del servidor, que es cliente : socket del cliente q se conecto al server JSONObject actualizacion_cache = new JSONObject(); actualizacion_cache.put("actualizacion", 1); actualizacion_cache.put("busqueda", b); actualizacion_cache.put("respuesta", aux); mensaje_cache.writeObject(actualizacion_cache); // envio el msj al servidor } catch (Exception ex) { } //RESPONDER DESDE EL SERVIDORIndex al FRONT ObjectOutputStream resp = new ObjectOutputStream(clienteNuevo.getOutputStream());// obtengo el output del cliente para mandarle un msj resp.writeObject(aux); System.out.println("msj enviado desde el servidor"); } } catch (IOException ex) { Logger.getLogger(MainServidor.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:edu.usc.pgroup.floe.client.commands.SwitchAlternate.java
/** * Entry point for Scale command.//from www. j av a 2s .c o m * @param args command line arguments sent by the floe.py script. */ public static void main(final String[] args) { Options options = new Options(); Option appOption = OptionBuilder.withArgName("name").hasArg().isRequired() .withDescription("Application Name").create("app"); Option pelletNameOption = OptionBuilder.withArgName("name").hasArg().isRequired() .withDescription("Pellet Name").create("pellet"); Option alternateOption = OptionBuilder.withArgName("alternate").hasArg().withType(new String()) .withDescription("The new alternate to switch to.").create("alternate"); options.addOption(appOption); options.addOption(pelletNameOption); options.addOption(alternateOption); CommandLineParser parser = new BasicParser(); CommandLine line; try { line = parser.parse(options, args); } catch (ParseException e) { LOGGER.error("Invalid command: " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("scale options", options); return; } String app = line.getOptionValue("app"); String pellet = line.getOptionValue("pellet"); String alternate = line.getOptionValue("alternate"); LOGGER.info("Application: {}", app); LOGGER.info("Pellet: {}", pellet); LOGGER.info("alternate: {}", alternate); try { FloeClient.getInstance().getClient().switchAlternate(app, pellet, alternate); } catch (TException e) { LOGGER.error("Error while connecting to the coordinator: {}", e); } }
From source file:edu.usc.pgroup.floe.client.commands.Signal.java
/** * Entry point for Scale command.//ww w .ja va 2 s .c o m * @param args command line arguments sent by the floe.py script. */ public static void main(final String[] args) { Options options = new Options(); Option appOption = OptionBuilder.withArgName("name").hasArg().isRequired() .withDescription("Application Name").create("app"); Option pelletNameOption = OptionBuilder.withArgName("name").hasArg().isRequired() .withDescription("Pellet Name").create("pellet"); Option signalOption = OptionBuilder.withArgName("data").hasArg().withType(new String()) .withDescription("signal data to send to the pellet").create("data"); options.addOption(appOption); options.addOption(pelletNameOption); options.addOption(signalOption); CommandLineParser parser = new BasicParser(); CommandLine line; try { line = parser.parse(options, args); } catch (ParseException e) { LOGGER.error("Invalid command: " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("scale options", options); return; } String app = line.getOptionValue("app"); String pellet = line.getOptionValue("pellet"); String data = line.getOptionValue("data"); LOGGER.info("Application: {}", app); LOGGER.info("Pellet: {}", pellet); LOGGER.info("data: {}", data); byte[] datab = Utils.serialize(data); try { TSignal signal = new TSignal(); signal.set_destApp(app); signal.set_destPellet(pellet); signal.set_data(datab); FloeClient.getInstance().getClient().signal(signal); } catch (TException e) { LOGGER.error("Error while connecting to the coordinator: {}", e); } }
From source file:edu.usc.pgroup.floe.client.commands.Scale.java
/** * Entry point for Scale command./* w w w . j a v a2 s.c o m*/ * @param args command line arguments sent by the floe.py script. */ public static void main(final String[] args) { Options options = new Options(); Option dirOption = OptionBuilder.withArgName("direction").hasArg().isRequired() .withDescription("Scale Direction.").create("dir"); Option appOption = OptionBuilder.withArgName("name").hasArg().isRequired() .withDescription("Application Name").create("app"); Option pelletNameOption = OptionBuilder.withArgName("name").hasArg().isRequired() .withDescription("Pellet Name").create("pellet"); Option cntOption = OptionBuilder.withArgName("num").hasArg().withType(new String()) .withDescription("Number of instances to scale up/down").create("cnt"); options.addOption(dirOption); options.addOption(appOption); options.addOption(pelletNameOption); options.addOption(cntOption); CommandLineParser parser = new BasicParser(); CommandLine line; try { line = parser.parse(options, args); } catch (ParseException e) { LOGGER.error("Invalid command: " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("scale options", options); return; } String dir = line.getOptionValue("dir"); String app = line.getOptionValue("app"); String pellet = line.getOptionValue("pellet"); String cnt = line.getOptionValue("cnt"); LOGGER.info("direction: {}", dir); LOGGER.info("Application: {}", app); LOGGER.info("Pellet: {}", pellet); LOGGER.info("count: {}", cnt); ScaleDirection direction = Enum.valueOf(ScaleDirection.class, dir); int count = Integer.parseInt(cnt); try { FloeClient.getInstance().getClient().scale(direction, app, pellet, count); } catch (TException e) { LOGGER.error("Error while connecting to the coordinator: {}", e); } }
From source file:com.github.codingtogenomic.CodingToGenomic.java
public static void main(String[] args) throws Exception { //parse commandline Options options = new Options(); CommandLineParser parser = new PosixParser(); String gene = new String(); String transcript = new String(); String species = "human"; boolean mapCdna = false; String coordinate = new String(); StringBuilder errorMsg = new StringBuilder(); try {//from www . j ava 2 s.co m options = getOptions(args); } catch (org.apache.commons.cli.ParseException ex) { System.err.println("Parsing failed. Reason: " + ex.getMessage()); System.exit(1); } CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { showHelp(options); } if (line.hasOption("gene")) { gene = line.getOptionValue("gene"); } else { if (!line.hasOption("transcript")) { errorMsg.append("Either --gene or --transcript argument is required\n"); } } if (line.hasOption("transcript")) { if (line.hasOption("gene")) { errorMsg.append("Please specify only one of " + "--gene or --transcript arguments, not both\n"); } else { transcript = line.getOptionValue("transcript"); if (line.hasOption("species")) { System.out.println("Ignoring --species option when using --transcript argument"); } } } if (line.hasOption("coordinate")) { coordinate = line.getOptionValue("coordinate"); } else { errorMsg.append("--coordinate argument is required\n"); } if (line.hasOption("species")) { species = line.getOptionValue("species").replaceAll("\\s+", "_"); } if (line.hasOption("b37")) { if (species.equalsIgnoreCase("human") || species.equalsIgnoreCase("homo sapiens")) { SERVER = GRCh37Server; } else { System.out.println("--b37 argument will be ignored - it can only be " + "used when human is the species of interest. Current species" + " is " + species + ".\n"); } } if (line.hasOption("noncoding")) { mapCdna = true; } if (errorMsg.length() > 0) { showHelp(options, errorMsg.toString(), 2); } int c = 0; boolean threePrimeUtr = false; String prefix = "c."; if (mapCdna) { prefix = "n."; try { c = Integer.parseInt(coordinate); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer", 2); } } else if (coordinate.startsWith("*")) { threePrimeUtr = true; prefix = "c.*"; String coord = coordinate.replaceFirst("\\*", ""); try { c = Integer.parseInt(coord); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer or UTR coordinate", 2); } } else { try { c = Integer.parseInt(coordinate); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer", 2); } } //got arguments String result; String header = "Input\tSymbol\tEnsemblGene\tEnsemblTranscript\tGenomicCoordinate"; if (!gene.isEmpty()) { IdParser idParser = new IdParser(gene); System.out.println("Interpretting " + gene + " as of type " + idParser.getIdentifierType()); if (idParser.isEnsemblId()) { if (line.hasOption("species")) { System.out.println("Ignoring --species option when searching Ensembl ID."); } if (idParser.isTranscript()) { result = codingToGenomicTranscript(gene, c, threePrimeUtr, mapCdna); } else if (idParser.isEnsp()) { result = codingToGenomicEnsp(gene, c, threePrimeUtr, mapCdna); } else { result = codingToGenomicId(gene, c, threePrimeUtr, mapCdna); } } else { if (idParser.isTranscript()) { //append user input to beginning result = codingToGenomicXrefTranscript(species, gene, c, threePrimeUtr, mapCdna); } else { result = codingToGenomicXref(species, gene, c, threePrimeUtr, mapCdna); } } if (idParser.isTranscript() || idParser.isEnsp()) { result = gene + ":" + prefix + c + "\t" + result; } else { result = convertGeneResult(result, gene, c, prefix); } } else { System.out.println("Searching for " + transcript + " as Ensembl transcript ID"); result = codingToGenomicTranscript(transcript, c, threePrimeUtr, mapCdna); //append user input to beginning result = transcript + ":" + prefix + c + "\t" + result; } System.out.println(header); System.out.println(result); }