List of usage examples for java.lang String equals
public boolean equals(Object anObject)
From source file:edu.cuhk.hccl.TripRealRatingsApp.java
public static void main(String[] args) throws IOException { File dir = new File(args[0]); File outFile = new File(args[1]); outFile.delete();// w ww.j av a 2 s .com StringBuilder buffer = new StringBuilder(); for (File file : dir.listFiles()) { List<String> lines = FileUtils.readLines(file, "UTF-8"); String hotelID = file.getName().split("_")[1]; String author = null; boolean noContent = false; for (String line : lines) { if (line.startsWith("<Author>")) { try { author = line.split(">")[1].trim(); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("[ERROR] An error occured on this line:"); System.out.println(line); continue; } } else if (line.startsWith("<Content>")) { // ignore records if they have no content String content = line.split(">")[1].trim(); if (content == null || content.equals("")) noContent = true; } else if (line.startsWith("<Rating>")) { String[] rates = line.split(">")[1].trim().split("\t"); if (noContent || rates.length != 8) continue; // Change missing rating from -1 to 0 for (int i = 0; i < rates.length; i++) { if (rates[i].equals("-1")) rates[i] = "0"; } buffer.append(author + "\t"); buffer.append(hotelID + "\t"); // overall buffer.append(rates[0] + "\t"); // location buffer.append(rates[3] + "\t"); // room buffer.append(rates[2] + "\t"); // service buffer.append(rates[6] + "\t"); // value buffer.append(rates[1] + "\t"); // cleanliness buffer.append(rates[4] + "\t"); buffer.append("\n"); } } // Write once for each file FileUtils.writeStringToFile(outFile, buffer.toString(), true); // Clear buffer buffer.setLength(0); System.out.printf("[INFO] Finished processing %s\n", file.getName()); } System.out.println("[INFO] All processinig are finished!"); }
From source file:SendMail.java
public static void main(String[] args) { try {/* w w w .j av a 2 s. co m*/ // If the user specified a mailhost, tell the system about it. if (args.length >= 1) System.getProperties().put("mail.host", args[0]); // A Reader stream to read from the console BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Ask the user for the from, to, and subject lines System.out.print("From: "); String from = in.readLine(); System.out.print("To: "); String to = in.readLine(); System.out.print("Subject: "); String subject = in.readLine(); // Establish a network connection for sending mail URL u = new URL("mailto:" + to); // Create a mailto: URL URLConnection c = u.openConnection(); // Create its URLConnection c.setDoInput(false); // Specify no input from it c.setDoOutput(true); // Specify we'll do output System.out.println("Connecting..."); // Tell the user System.out.flush(); // Tell them right now c.connect(); // Connect to mail host PrintWriter out = // Get output stream to host new PrintWriter(new OutputStreamWriter(c.getOutputStream())); // We're talking to the SMTP server now. // Write out mail headers. Don't let users fake the From address out.print("From: \"" + from + "\" <" + System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName() + ">\r\n"); out.print("To: " + to + "\r\n"); out.print("Subject: " + subject + "\r\n"); out.print("\r\n"); // blank line to end the list of headers // Now ask the user to enter the body of the message System.out.println("Enter the message. " + "End with a '.' on a line by itself."); // Read message line by line and send it out. String line; for (;;) { line = in.readLine(); if ((line == null) || line.equals(".")) break; out.print(line + "\r\n"); } // Close (and flush) the stream to terminate the message out.close(); // Tell the user it was successfully sent. System.out.println("Message sent."); } catch (Exception e) { // Handle any exceptions, print error message. System.err.println(e); System.err.println("Usage: java SendMail [<mailhost>]"); } }
From source file:com.jabyftw.StringLengthTest.java
public static void main(String[] args) { try {/*from w ww . j a v a2s . c om*/ // Make it the range of the password for (int length = 4; length <= 26; length++) { String string = RandomStringUtils.random(length, true, true); String encryptedString = Util.encryptString(string); System.out.println("Encrypting a " + length + " string resulted on a " + encryptedString.length() + " encrypted length string: " + string + " -> " + encryptedString); } // Set variables for testing String IN = "N3VIg4dv1FO0LQuauHeuC6", PRE_ENCRYPTED_OUT = "4be9cc85bf5abc7cb99019a84256e938fbc4fbafa80598b297dc8bc3e22f11dd"; // Testing if it is safe on every example String encryptionOut = Util.encryptString(IN); System.out.println("\nTesting safety: (" + encryptionOut + " == " + PRE_ENCRYPTED_OUT + " )? " + encryptionOut.equals(PRE_ENCRYPTED_OUT)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } // Test passed, every encrypted string is 64 letters length }
From source file:UseTrim.java
public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter 'stop' to quit."); System.out.println("Enter letter: "); do {/*from w w w. j a va 2 s .c o m*/ str = br.readLine(); str = str.trim(); if (str.equals("I")) System.out.println("I"); else if (str.equals("M")) System.out.println("M"); else if (str.equals("C")) System.out.println("C."); else if (str.equals("W")) System.out.println("W"); } while (!str.equals("stop")); }
From source file:BGrep.java
public static void main(String[] args) { String encodingName = "UTF-8"; // Default to UTF-8 encoding int flags = Pattern.MULTILINE; // Default regexp flags try { // Fatal exceptions are handled after this try block // First, process any options int nextarg = 0; while (args[nextarg].charAt(0) == '-') { String option = args[nextarg++]; if (option.equals("-e")) { encodingName = args[nextarg++]; } else if (option.equals("-i")) { // case-insensitive matching flags |= Pattern.CASE_INSENSITIVE; } else if (option.equals("-s")) { // Strict Unicode processing flags |= Pattern.UNICODE_CASE; // case-insensitive Unicode flags |= Pattern.CANON_EQ; // canonicalize Unicode } else { System.err.println("Unknown option: " + option); usage();//from ww w . j av a2 s . com } } // Get the Charset for converting bytes to chars Charset charset = Charset.forName(encodingName); // Next argument must be a regexp. Compile it to a Pattern object Pattern pattern = Pattern.compile(args[nextarg++], flags); // Require that at least one file is specified if (nextarg == args.length) usage(); // Loop through each of the specified filenames while (nextarg < args.length) { String filename = args[nextarg++]; CharBuffer chars; // This will hold complete text of the file try { // Handle per-file errors locally // Open a FileChannel to the named file FileInputStream stream = new FileInputStream(filename); FileChannel f = stream.getChannel(); // Memory-map the file into one big ByteBuffer. This is // easy but may be somewhat inefficient for short files. ByteBuffer bytes = f.map(FileChannel.MapMode.READ_ONLY, 0, f.size()); // We can close the file once it is is mapped into memory. // Closing the stream closes the channel, too. stream.close(); // Decode the entire ByteBuffer into one big CharBuffer chars = charset.decode(bytes); } catch (IOException e) { // File not found or other problem System.err.println(e); // Print error message continue; // and move on to the next file } // This is the basic regexp loop for finding all matches in a // CharSequence. Note that CharBuffer implements CharSequence. // A Matcher holds state for a given Pattern and text. Matcher matcher = pattern.matcher(chars); while (matcher.find()) { // While there are more matches // Print out details of the match System.out.println(filename + ":" + // file name matcher.start() + ": " + // character pos matcher.group()); // matching text } } } // These are the things that can go wrong in the code above catch (UnsupportedCharsetException e) { // Bad encoding name System.err.println("Unknown encoding: " + encodingName); } catch (PatternSyntaxException e) { // Bad pattern System.err.println("Syntax error in search pattern:\n" + e.getMessage()); } catch (ArrayIndexOutOfBoundsException e) { // Wrong number of arguments usage(); } }
From source file:de.micromata.genome.gwiki.tools.PatchVersion.java
public static void main(String[] args) { PatchVersion pv = new PatchVersion(null); for (int i = 0; i < args.length; ++i) { String s = args[i]; if (s.equals("-expected") == true) { if (args.length <= i + 1) { System.out.println("Required expected string"); System.exit(1);/* ww w .ja v a 2 s . c o m*/ } ++i; pv.expected = args[i]; continue; } if (s.equals("-test") == true) { pv.testOnly = true; continue; } if (StringUtils.isEmpty(pv.version) == false) { System.out.println("Version already set"); System.exit(1); } else { pv.version = s; } } if (StringUtils.isEmpty(pv.version) == true) { System.out.println("Missing required version"); System.exit(1); } pv.patch(); }
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();/*from w w w .jav a 2 s . co 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.switchyard.quickstarts.demo.policy.security.basic.propagate.WorkServiceMain.java
public static void main(String... args) throws Exception { Set<String> policies = new HashSet<String>(); for (String arg : args) { arg = Strings.trimToNull(arg);/*from w w w. j av a 2 s .co m*/ if (arg != null) { if (arg.equals(CONFIDENTIALITY) || arg.equals(CLIENT_AUTHENTICATION) || arg.equals(HELP)) { policies.add(arg); } else { LOGGER.error(MAVEN_USAGE); throw new Exception(MAVEN_USAGE); } } } if (policies.contains(HELP)) { LOGGER.info(MAVEN_USAGE); } else { final String scheme; final int port; if (policies.contains(CONFIDENTIALITY)) { scheme = "https"; port = 8443; SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); Scheme https = new Scheme(scheme, port, sf); SchemeRegistry sr = new SchemeRegistry(); sr.register(https); } else { scheme = "http"; port = 8080; } String[] userPass = policies.contains(CLIENT_AUTHENTICATION) ? new String[] { "kermit", "the-frog-1" } : null; invokeWorkService(scheme, port, userPass); } }
From source file:Quickstart.java
public static void main(String[] args) { //Most applications would never instantiate a SecurityManager directly - you would instead configure //JSecurity in web.xml or a container (JEE, Spring, etc). //But, since this is a quickstart, we just want you to get a feel for how the JSecurity API looks, so this //is sufficient to have a simple working example: DefaultSecurityManager securityManager = new DefaultSecurityManager(); //for this simple example quickstart, make the SecurityManager accessible across the JVM. Most //applications wouldn't do this and instead rely on their container configuration or web.xml for webapps. That //is outside the scope of this simple quickstart, so we'll just do the bare minimum so you can continue to //get a feel for things. SecurityUtils.setSecurityManager(securityManager); //now that a simple JSecurity environment is set up, let's see what you can do: //get the currently executing user: Subject currentUser = SecurityUtils.getSubject(); //Do some stuff with a Session (no need for a web or EJB container!!!) Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) { log.info("Retrieved the correct value! [" + value + "]"); }/*from w ww . ja v a 2 s . c om*/ //let's log in the current user so we can check against roles and permissions: if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); token.setRememberMe(true); try { currentUser.login(token); } catch (UnknownAccountException uae) { log.info("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { log.info("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { log.info("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); } // ... catch more exceptions here (maybe custom ones specific to your application? catch (AuthenticationException ae) { //unexpected condition? error? } } //say who they are: //print their identifying principal (in this case, a username): log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); //test a role: if (currentUser.hasRole("schwartz")) { log.info("May the Schwartz be with you!"); } else { log.info("Hello, mere mortal."); } //test a typed permission (not instance-level) if (currentUser.isPermitted("lightsaber:weild")) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); } //a (very powerful) Instance Level permission: if (currentUser.isPermitted("winnebago:drive:eagle5")) { log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } //all done - log out! currentUser.logout(); System.exit(0); }
From source file:com.bazaarvoice.jless.LessProcessor.java
public static void main(String[] args) { if (args.length == 0) { System.err.println("You must specify an input file."); System.exit(1);/*from ww w . ja va2 s .c o m*/ } LessProcessor translator = new LessProcessor(); String inputPath = null; for (String arg : args) { if (arg.equals("-c")) { translator.setCompressionEnabled(true); } else { if (inputPath != null) { System.err.println("Only one input file can be used."); System.exit(1); } inputPath = arg; } } try { System.out.println(translator.process(new FileInputStream(inputPath))); } catch (IOException e) { System.err.println("Unable to read input file."); } }