List of usage examples for java.lang String indexOf
public int indexOf(String str)
From source file:com.tonygalati.sprites.SpriteGenerator.java
public static void main(String[] args) throws IOException { // if (args.length != 3) // {/* w w w .j av a 2 s .c o m*/ // System.out.print("Usage: com.tonygalati.sprites.SpriteGenerator {path to images} {margin between images in px} {output file}\n"); // System.out.print("Note: The max height should only be around 32,767px due to Microsoft GDI using a 16bit signed integer to store dimensions\n"); // System.out.print("going beyond this dimension is possible with this tool but the generated sprite image will not work correctly with\n"); // System.out.print("most browsers.\n\n"); // return; // } // Integer margin = Integer.parseInt(args[1]); Integer margin = Integer.parseInt("1"); String spriteFile = "icons-" + RandomStringUtils.randomAlphanumeric(10) + ".png"; SpriteCSSGenerator cssGenerator = new SpriteCSSGenerator(); ClassLoader classLoader = SpriteGenerator.class.getClassLoader(); URL folderPath = classLoader.getResource(NAIC_SMALL_ICON); if (folderPath != null) { File imageFolder = new File(folderPath.getPath()); // Read images ArrayList<BufferedImage> imageList = new ArrayList<BufferedImage>(); Integer yCoordinate = null; for (File f : imageFolder.listFiles()) { if (f.isFile()) { String fileName = f.getName(); String ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); if (ext.equals("png")) { System.out.println("adding file " + fileName); BufferedImage image = ImageIO.read(f); imageList.add(image); if (yCoordinate == null) { yCoordinate = 0; } else { yCoordinate += (image.getHeight() + margin); } // add to cssGenerator cssGenerator.addSpriteCSS(fileName.substring(0, fileName.indexOf(".")), 0, yCoordinate); } } } // Find max width and total height int maxWidth = 0; int totalHeight = 0; for (BufferedImage image : imageList) { totalHeight += image.getHeight() + margin; if (image.getWidth() > maxWidth) maxWidth = image.getWidth(); } System.out.format("Number of images: %s, total height: %spx, width: %spx%n", imageList.size(), totalHeight, maxWidth); // Create the actual sprite BufferedImage sprite = new BufferedImage(maxWidth, totalHeight, BufferedImage.TYPE_INT_ARGB); int currentY = 0; Graphics g = sprite.getGraphics(); for (BufferedImage image : imageList) { g.drawImage(image, 0, currentY, null); currentY += image.getHeight() + margin; } System.out.format("Writing sprite: %s%n", spriteFile); ImageIO.write(sprite, "png", new File(spriteFile)); File cssFile = cssGenerator.getFile(spriteFile); System.out.println(cssFile.getAbsolutePath() + " created"); } else { System.err.println("Could not find folder: " + NAIC_SMALL_ICON); } }
From source file:com.jcraft.weirdx.XDMCP.java
public static void main(String[] args) { String usage = "usage: [-query|-broadcast] address -display displayname"; int op = -1;/* w w w .j a v a2 s . c o m*/ String address = null; String displayaddress = null; int displaynum = 0; if (args.length == 0) { System.err.println(usage); System.exit(-1); } for (int i = 0; i < args.length; i++) { if (args[i].equals("-query")) { op = Query; i++; address = args[i]; continue; } if (args[i].equals("-broadcast")) { op = BroadcastQuery; i++; address = args[i]; continue; } if (args[i].equals("-display")) { i++; displayaddress = args[i].substring(0, args[i].indexOf(":")); try { String foo = args[i].substring(args[i].indexOf(":") + 1, args[i].length()); foo = foo.substring(0, (foo.indexOf(".") == -1 ? foo.length() : foo.indexOf("."))); displaynum = Integer.parseInt(foo); } catch (Exception e) { } } } if (op == -1 || address == null || displayaddress == null) { System.err.println(usage); System.exit(-1); } XDMCP foo = new XDMCP(op, address, displayaddress, displaynum); foo.start(); }
From source file:modnlp.capte.AlignmentInterfaceWS.java
public static void main(String args[]) { try {// w w w . j a va2 s . c o m //set splitting action equal to true //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); doSplit = true; //default AlreadyRun to false AlreadyRun = false; //lineConvert = true; lineConvert = true; // Read config file boolean isMac = false; boolean isWin = false; boolean isUnix = false; String tmp = ""; String winsep = "\\"; String unixsep = "/"; String ostype = System.getProperty("os.name").toLowerCase(); System.out.println("Operating system type =>" + ostype); if (ostype.indexOf("win") >= 0) { isWin = true; isUnix = false; isMac = false; } else if ((ostype.indexOf("nix") >= 0) || (ostype.indexOf("nux") >= 0)) { isUnix = true; isWin = false; isMac = false; } else if (ostype.indexOf("mac") >= 0) { isWin = false; isUnix = false; isMac = true; } else { throw new UnsupportedOperationException("your OS is not supported!"); } //creating and showing this application's GUI. SwingUtilities.invokeLater(new Runnable() { public void run() { //Turn off metal's use of bold fonts UIManager.put("swing.boldMetal", Boolean.FALSE); createAndShowGUI(); } }); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.yahoo.labs.yamall.local.Yamall.java
public static void main(String[] args) { String[] remainingArgs = null; String inputFile = null;//from w ww . ja v a2 s .c o m String predsFile = null; String saveModelFile = null; String initialModelFile = null; String lossName = null; String parserName = null; String linkName = null; String invertHashName = null; double learningRate = 1; String minPredictionString = null; String maxPredictionString = null; String fmNumberFactorsString = null; int bitsHash; int numberPasses; int holdoutPeriod = 10; boolean testOnly = false; boolean exponentialProgress; double progressInterval; options.addOption("h", "help", false, "displays this help"); options.addOption("t", false, "ignore label information and just test"); options.addOption(Option.builder().hasArg(false).required(false).longOpt("binary") .desc("reports loss as binary classification with -1,1 labels").build()); options.addOption( Option.builder().hasArg(false).required(false).longOpt("solo").desc("uses SOLO optimizer").build()); options.addOption(Option.builder().hasArg(false).required(false).longOpt("pcsolo") .desc("uses Per Coordinate SOLO optimizer").build()); options.addOption(Option.builder().hasArg(false).required(false).longOpt("pistol") .desc("uses PiSTOL optimizer").build()); options.addOption(Option.builder().hasArg(false).required(false).longOpt("kt") .desc("(EXPERIMENTAL) uses KT optimizer").build()); options.addOption(Option.builder().hasArg(false).required(false).longOpt("pckt") .desc("(EXPERIMENTAL) uses Per Coordinate KT optimizer").build()); options.addOption(Option.builder().hasArg(false).required(false).longOpt("pccocob") .desc("(EXPERIMENTAL) uses Per Coordinate COCOB optimizer").build()); options.addOption(Option.builder().hasArg(false).required(false).longOpt("cocob") .desc("(EXPERIMENTAL) uses COCOB optimizer").build()); options.addOption( Option.builder().hasArg(false).required(false).longOpt("fm").desc("Factorization Machine").build()); options.addOption(Option.builder("f").hasArg(true).required(false).desc("final regressor to save") .type(String.class).longOpt("final_regressor").build()); options.addOption(Option.builder("p").hasArg(true).required(false).desc("file to output predictions to") .longOpt("predictions").type(String.class).build()); options.addOption( Option.builder("i").hasArg(true).required(false).desc("initial regressor(s) to load into memory") .longOpt("initial_regressor").type(String.class).build()); options.addOption(Option.builder().hasArg(true).required(false).desc( "specify the loss function to be used. Currently available ones are: absolute, squared (default), hinge, logistic") .longOpt("loss_function").type(String.class).build()); options.addOption(Option.builder().hasArg(true).required(false).desc( "specify the link function used in the output of the predictions. Currently available ones are: identity (default), logistic") .longOpt("link").type(String.class).build()); options.addOption(Option.builder().hasArg(true).required(false) .desc("output human-readable final regressor with feature names").longOpt("invert_hash") .type(String.class).build()); options.addOption( Option.builder("l").hasArg(true).required(false).desc("set (initial) learning Rate, default = 1.0") .longOpt("learning_rate").type(String.class).build()); options.addOption(Option.builder("b").hasArg(true).required(false) .desc("number of bits in the feature table, default = 18").longOpt("bit_precision") .type(String.class).build()); options.addOption(Option.builder("P").hasArg(true).required(false) .desc("progress update frequency, integer: additive; float: multiplicative, default = 2.0") .longOpt("progress").type(String.class).build()); options.addOption(Option.builder().hasArg(true).required(false) .desc("smallest prediction to output, before the link function, default = -50") .longOpt("min_prediction").type(String.class).build()); options.addOption(Option.builder().hasArg(true).required(false) .desc("smallest prediction to output, before the link function, default = 50") .longOpt("max_prediction").type(String.class).build()); options.addOption(Option.builder().hasArg(true).required(false) .desc("ignore namespaces beginning with the characters in <arg>").longOpt("ignore") .type(String.class).build()); options.addOption(Option.builder().hasArg(true).required(false).desc("number of training passes") .longOpt("passes").type(String.class).build()); options.addOption( Option.builder().hasArg(true).required(false).desc("holdout period for test only, default = 10") .longOpt("holdout_period").type(String.class).build()); options.addOption(Option.builder().hasArg(true).required(false) .desc("number of factors for Factorization Machines default = 8").longOpt("fmNumberFactors") .type(String.class).build()); options.addOption(Option.builder().hasArg(true).required(false) .desc("specify the parser to use. Currently available ones are: vw (default), libsvm, tsv") .longOpt("parser").type(String.class).build()); options.addOption(Option.builder().hasArg(true).required(false).desc("schema file for the TSV input") .longOpt("schema").type(String.class).build()); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println("Unrecognized option"); help(); } if (cmd.hasOption("h")) help(); if (cmd.hasOption("t")) testOnly = true; if (cmd.hasOption("binary")) { binary = true; System.out.println("Reporting binary loss"); } initialModelFile = cmd.getOptionValue("i"); predsFile = cmd.getOptionValue("p"); lossName = cmd.getOptionValue("loss_function", "squared"); linkName = cmd.getOptionValue("link", "identity"); saveModelFile = cmd.getOptionValue("f"); learningRate = Double.parseDouble(cmd.getOptionValue("l", "1.0")); bitsHash = Integer.parseInt(cmd.getOptionValue("b", "18")); invertHashName = cmd.getOptionValue("invert_hash"); minPredictionString = cmd.getOptionValue("min_prediction", "-50"); maxPredictionString = cmd.getOptionValue("max_prediction", "50"); fmNumberFactorsString = cmd.getOptionValue("fmNumberFactors", "8"); parserName = cmd.getOptionValue("parser", "vw"); numberPasses = Integer.parseInt(cmd.getOptionValue("passes", "1")); System.out.println("Number of passes = " + numberPasses); if (numberPasses > 1) { holdoutPeriod = Integer.parseInt(cmd.getOptionValue("holdout_period", "10")); System.out.println("Holdout period = " + holdoutPeriod); } remainingArgs = cmd.getArgs(); if (remainingArgs.length == 1) inputFile = remainingArgs[0]; InstanceParser instanceParser = null; if (parserName.equals("vw")) instanceParser = new VWParser(bitsHash, cmd.getOptionValue("ignore"), (invertHashName != null)); else if (parserName.equals("libsvm")) instanceParser = new LIBSVMParser(bitsHash, (invertHashName != null)); else if (parserName.equals("tsv")) { String schema = cmd.getOptionValue("schema"); if (schema == null) { System.out.println("TSV parser requires a schema file."); System.exit(0); } else { String spec = null; try { spec = new String(Files.readAllBytes(Paths.get(schema))); } catch (IOException e) { System.out.println("Error reading the TSV schema file."); e.printStackTrace(); System.exit(0); } instanceParser = new TSVParser(bitsHash, cmd.getOptionValue("ignore"), (invertHashName != null), spec); } } else { System.out.println("Unknown parser."); System.exit(0); } System.out.println("Num weight bits = " + bitsHash); // setup progress String progress = cmd.getOptionValue("P", "2.0"); if (progress.indexOf('.') >= 0) { exponentialProgress = true; progressInterval = (double) Double.parseDouble(progress); } else { exponentialProgress = false; progressInterval = (double) Integer.parseInt(progress); } // min and max predictions minPrediction = (double) Double.parseDouble(minPredictionString); maxPrediction = (double) Double.parseDouble(maxPredictionString); // number of factors for Factorization Machines fmNumberFactors = (int) Integer.parseInt(fmNumberFactorsString); // configure the learner Loss lossFnc = null; LinkFunction link = null; if (initialModelFile == null) { if (cmd.hasOption("kt")) { learner = new KT(bitsHash); } else if (cmd.hasOption("pckt")) { learner = new PerCoordinateKT(bitsHash); } else if (cmd.hasOption("pcsolo")) { learner = new PerCoordinateSOLO(bitsHash); } else if (cmd.hasOption("solo")) { learner = new SOLO(bitsHash); } else if (cmd.hasOption("pccocob")) { learner = new PerCoordinateCOCOB(bitsHash); } else if (cmd.hasOption("cocob")) { learner = new COCOB(bitsHash); } else if (cmd.hasOption("pistol")) { learner = new PerCoordinatePiSTOL(bitsHash); } else if (cmd.hasOption("fm")) { learner = new SGD_FM(bitsHash, fmNumberFactors); } else learner = new SGD_VW(bitsHash); } else { learner = IOLearner.loadLearner(initialModelFile); } // setup link function if (linkName.equals("identity")) { link = new IdentityLinkFunction(); } else if (linkName.equals("logistic")) { link = new LogisticLinkFunction(); } else { System.out.println("Unknown link function."); System.exit(0); } // setup loss function if (lossName.equals("squared")) { lossFnc = new SquareLoss(); } else if (lossName.equals("hinge")) { lossFnc = new HingeLoss(); } else if (lossName.equals("logistic")) { lossFnc = new LogisticLoss(); } else if (lossName.equals("absolute")) { lossFnc = new AbsLoss(); } else { System.out.println("Unknown loss function."); System.exit(0); } learner.setLoss(lossFnc); learner.setLearningRate(learningRate); // maximum range predictions System.out.println("Max prediction = " + maxPrediction + ", Min Prediction = " + minPrediction); // print information about the learner System.out.println(learner.toString()); // print information about the link function System.out.println(link.toString()); // print information about the parser System.out.println(instanceParser.toString()); // print information about ignored namespaces System.out.println("Ignored namespaces = " + cmd.getOptionValue("ignore", "")); long start = System.nanoTime(); FileInputStream fstream; try { BufferedReader br = null; if (inputFile != null) { fstream = new FileInputStream(inputFile); System.out.println("Reading datafile = " + inputFile); br = new BufferedReader(new InputStreamReader(fstream)); } else { System.out.println("Reading from console"); br = new BufferedReader(new InputStreamReader(System.in)); } File fout = null; FileOutputStream fos = null; BufferedWriter bw = null; if (predsFile != null) { fout = new File(predsFile); fos = new FileOutputStream(fout); bw = new BufferedWriter(new OutputStreamWriter(fos)); } try { System.out.println("average example current current current"); System.out.println("loss counter label predict features"); int iter = 0; double cumLoss = 0; double weightedSampleSum = 0; double sPlus = 0; double sMinus = 0; Instance sample = null; boolean justPrinted = false; int pass = 0; ObjectOutputStream ooutTr = null; ObjectOutputStream ooutHO = null; ObjectInputStream oinTr = null; double pred = 0; int limit = 1; double hError = Double.MAX_VALUE; double lastHError = Double.MAX_VALUE; int numTestSample = 0; int numTrainingSample = 0; int idx = 0; if (numberPasses > 1) { ooutTr = new ObjectOutputStream(new FileOutputStream("cache_training.bin")); ooutHO = new ObjectOutputStream(new FileOutputStream("cache_holdout.bin")); oinTr = new ObjectInputStream(new FileInputStream("cache_training.bin")); } do { while (true) { double score; if (pass > 0 && numberPasses > 1) { Instance tmp = (Instance) oinTr.readObject(); if (tmp != null) sample = tmp; else break; } else { String strLine = br.readLine(); if (strLine != null) sample = instanceParser.parse(strLine); else break; } justPrinted = false; idx++; if (numberPasses > 1 && pass == 0 && idx % holdoutPeriod == 0) { // store the current sample for the holdout set ooutHO.writeObject(sample); ooutHO.reset(); numTestSample++; } else { if (numberPasses > 1 && pass == 0) { ooutTr.writeObject(sample); ooutTr.reset(); numTrainingSample++; } iter++; if (testOnly) { // predict the sample score = learner.predict(sample); } else { // predict the sample and update the classifier using the sample score = learner.update(sample); } score = Math.min(Math.max(score, minPrediction), maxPrediction); pred = link.apply(score); if (!binary) cumLoss += learner.getLoss().lossValue(score, sample.getLabel()) * sample.getWeight(); else if (Math.signum(score) != sample.getLabel()) cumLoss += sample.getWeight(); weightedSampleSum += sample.getWeight(); if (sample.getLabel() > 0) sPlus = sPlus + sample.getWeight(); else sMinus = sMinus + sample.getWeight(); // output predictions to file if (predsFile != null) { bw.write(String.format("%.6f %s", pred, sample.getTag())); bw.newLine(); } // print statistics to screen if (iter == limit) { justPrinted = true; System.out.printf("%.6f %12d % .4f % .4f %d\n", cumLoss / weightedSampleSum, iter, sample.getLabel(), pred, sample.getVector().size()); if (exponentialProgress) limit *= progressInterval; else limit += progressInterval; } } } if (numberPasses > 1) { if (pass == 0) { // finished first pass of many // write a null at the end of the files ooutTr.writeObject(null); ooutHO.writeObject(null); ooutTr.flush(); ooutHO.flush(); ooutTr.close(); ooutHO.close(); System.out.println("finished first epoch"); System.out.println(numTrainingSample + " training samples"); System.out.println(numTestSample + " holdout samples saved"); } lastHError = hError; hError = evalHoldoutError(); } if (numberPasses > 1) { System.out.printf("Weighted loss on holdout on epoch %d = %.6f\n", pass + 1, hError); oinTr.close(); oinTr = new ObjectInputStream(new FileInputStream("cache_training.bin")); if (hError > lastHError) { System.out.println("Early stopping"); break; } } pass++; } while (pass < numberPasses); if (justPrinted == false) { System.out.printf("%.6f %12d % .4f % .4f %d\n", cumLoss / weightedSampleSum, iter, sample.getLabel(), pred, sample.getVector().size()); } System.out.println("finished run"); System.out.println(String.format("average loss best constant predictor: %.6f", lossFnc.lossConstantBinaryLabels(sPlus, sMinus))); if (saveModelFile != null) IOLearner.saveLearner(learner, saveModelFile); if (invertHashName != null) IOLearner.saveInvertHash(learner.getWeights(), instanceParser.getInvertHashMap(), invertHashName); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // close the input stream try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // close the output stream if (predsFile != null) { try { bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } long millis = System.nanoTime() - start; System.out.printf("Elapsed time: %d min, %d sec\n", TimeUnit.NANOSECONDS.toMinutes(millis), TimeUnit.NANOSECONDS.toSeconds(millis) - 60 * TimeUnit.NANOSECONDS.toMinutes(millis)); } catch ( FileNotFoundException e) { System.out.println("Error opening the input file"); e.printStackTrace(); } }
From source file:net.sf.firemox.Magic.java
/** * @param args//from w w w . j ava 2 s.c o m * the command line arguments * @throws Exception */ public static void main(String[] args) throws Exception { Log.init(); Log.debug("MP v" + IdConst.VERSION + ", jre:" + System.getProperty("java.runtime.version") + ", jvm:" + System.getProperty("java.vm.version") + ",os:" + System.getProperty("os.name") + ", res:" + Toolkit.getDefaultToolkit().getScreenSize().width + "x" + Toolkit.getDefaultToolkit().getScreenSize().height + ", root:" + MToolKit.getRootDir()); System.setProperty("swing.aatext", "true"); System.setProperty(SubstanceLookAndFeel.WATERMARK_IMAGE_PROPERTY, MToolKit.getIconPath(Play.ZONE_NAME + "/hardwoodfloor.png")); final File substancelafFile = MToolKit.getFile(FILE_SUBSTANCE_PROPERTIES); if (substancelafFile == null) { Log.warn("Unable to locate '" + FILE_SUBSTANCE_PROPERTIES + "' file, you are using the command line with wrong configuration. See http://www.firemox.org/dev/project.html documentation"); } else { System.getProperties().load(new FileInputStream(substancelafFile)); } MToolKit.defaultFont = new Font("Arial", 0, 11); try { if (args.length > 0) { final String[] args2 = new String[args.length - 1]; System.arraycopy(args, 1, args2, 0, args.length - 1); if ("-rebuild".equals(args[0])) { XmlConfiguration.main(args2); } else if ("-oracle2xml".equals(args[0])) { Oracle2Xml.main(args2); } else if ("-batch".equals(args[0])) { if ("-server".equals(args[1])) { batchMode = BATCH_SERVER; } else if ("-client".equals(args[1])) { batchMode = BATCH_CLIENT; } } else { Log.error("Unknown options '" + Arrays.toString(args) + "'\nUsage : java -jar starter.jar <options>, where options are :\n" + "\t-rebuild -game <tbs name> [-x] [-d] [-v] [-h] [-f] [-n]\n" + "\t-oracle2xml -f <oracle file> -d <output directory> [-v] [-h]"); } System.exit(0); return; } if (batchMode == -1 && !"Mac OS X".equals(System.getProperty("os.name"))) { splash = new SplashScreen(MToolKit.getIconPath("splash.jpg"), null, 2000); } // language settings LanguageManager.initLanguageManager(Configuration.getString("language", "auto")); } catch (Throwable t) { Log.error("START-ERROR : \n\t" + t.getMessage()); System.exit(1); return; } Log.debug("MP Language : " + LanguageManager.getLanguage().getName()); speparateAvatar = Toolkit.getDefaultToolkit().getScreenSize().height > 768; // verify the java version, minimal is 1.5 if (new JavaVersion().compareTo(new JavaVersion(IdConst.MINIMAL_JRE)) == -1) { Log.error(LanguageManager.getString("wrongjava") + IdConst.MINIMAL_JRE); } // load look and feel settings lookAndFeelName = Configuration.getString("preferred", MUIManager.LF_SUBSTANCE_CLASSNAME); // try { // FileInputStream in= new FileInputStream("MAGIC.TTF"); // MToolKit.defaultFont= Font.createFont(Font.TRUETYPE_FONT, in); // in.close(); // MToolKit.defaultFont= MToolKit.defaultFont.deriveFont(Font.BOLD, 11); // } // catch (FileNotFoundException e) { // System.out.println("editorfont.ttf not found, using default."); // } // catch (Exception ex) { // ex.printStackTrace(); // } // Read available L&F final LinkedList<Pair<String, String>> lfList = new LinkedList<Pair<String, String>>(); try { BufferedReader buffReader = new BufferedReader( new InputStreamReader(MToolKit.getResourceAsStream(IdConst.FILE_THEME_SETTINGS))); String line; while ((line = buffReader.readLine()) != null) { line = line.trim(); if (!line.startsWith("#")) { final int index = line.indexOf(';'); if (index != -1) { lfList.add(new Pair<String, String>(line.substring(0, index), line.substring(index + 1))); } } } IOUtils.closeQuietly(buffReader); } catch (Throwable e) { // no place for resolve this problem Log.debug("Error reading L&F properties : " + e.getMessage()); } for (Pair<String, String> pair : lfList) { UIManager.installLookAndFeel(pair.key, pair.value); } // install L&F if (SkinLF.isSkinLF(lookAndFeelName)) { // is a SkinLF Look & Feel /* * Make sure we have a nice window decoration. */ SkinLF.installSkinLF(lookAndFeelName); } else { // is Metal Look & Feel if (!MToolKit.isAvailableLookAndFeel(lookAndFeelName)) { // preferred look&feel is not available JOptionPane.showMessageDialog(magicForm, LanguageManager.getString("preferredlfpb", lookAndFeelName), LanguageManager.getString("error"), JOptionPane.INFORMATION_MESSAGE); setDefaultUI(); } // Install the preferred LookAndFeel newLAF = MToolKit.geLookAndFeel(lookAndFeelName); frameDecorated = newLAF.getSupportsWindowDecorations(); /* * Make sure we have a nice window decoration. */ JFrame.setDefaultLookAndFeelDecorated(frameDecorated); JDialog.setDefaultLookAndFeelDecorated(frameDecorated); UIManager.setLookAndFeel(MToolKit.geLookAndFeel(lookAndFeelName)); } // Start main thread try { new Magic(); SwingUtilities.invokeLater(SkinLF.REFRESH_RUNNER); } catch (Throwable e) { Log.fatal("In main thread, occurred exception : ", e); ConnectionManager.closeConnexions(); return; } }
From source file:net.yacy.yacy.java
/** * Main-method which is started by java. Checks for special arguments or * starts up the application.//from w w w .j a v a 2 s.com * * @param args * Given arguments from the command line. */ public static void main(String args[]) { try { // check assertion status //ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true); boolean assertionenabled = false; assert (assertionenabled = true) == true; // compare to true to remove warning: "Possible accidental assignement" if (assertionenabled) System.out.println("Asserts are enabled"); // check memory amount System.gc(); final long startupMemFree = MemoryControl.free(); final long startupMemTotal = MemoryControl.total(); // maybe go into headless awt mode: we have three cases depending on OS and one exception: // windows : better do not go into headless mode // mac : go into headless mode because an application is shown in gui which may not be wanted // linux : go into headless mode because this does not need any head operation // exception : if the -gui option is used then do not go into headless mode since that uses a gui boolean headless = true; if (OS.isWindows) headless = false; if (args.length >= 1 && args[0].toLowerCase(Locale.ROOT).equals("-gui")) headless = false; System.setProperty("java.awt.headless", headless ? "true" : "false"); String s = ""; for (final String a : args) s += a + " "; yacyRelease.startParameter = s.trim(); File applicationRoot = new File(System.getProperty("user.dir").replace('\\', '/')); File dataRoot = applicationRoot; //System.out.println("args.length=" + args.length); //System.out.print("args=["); for (int i = 0; i < args.length; i++) System.out.print(args[i] + ", "); System.out.println("]"); if ((args.length >= 1) && (args[0].toLowerCase(Locale.ROOT).equals("-startup") || args[0].equals("-start"))) { // normal start-up of yacy if (args.length > 1) { if (args[1].startsWith(File.separator)) { /* data root folder provided as an absolute path */ dataRoot = new File(args[1]); } else { /* data root folder provided as a path relative to the user home folder */ dataRoot = new File(System.getProperty("user.home").replace('\\', '/'), args[1]); } } preReadSavedConfigandInit(dataRoot); startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, false); } else if (args.length >= 1 && args[0].toLowerCase(Locale.ROOT).equals("-gui")) { // start-up of yacy with gui if (args.length > 1) { if (args[1].startsWith(File.separator)) { /* data root folder provided as an absolute path */ dataRoot = new File(args[1]); } else { /* data root folder provided as a path relative to the user home folder */ dataRoot = new File(System.getProperty("user.home").replace('\\', '/'), args[1]); } } preReadSavedConfigandInit(dataRoot); startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, true); } else if ((args.length >= 1) && ((args[0].toLowerCase(Locale.ROOT).equals("-shutdown")) || (args[0].equals("-stop")))) { // normal shutdown of yacy if (args.length == 2) applicationRoot = new File(args[1]); shutdown(applicationRoot); } else if ((args.length >= 1) && (args[0].toLowerCase(Locale.ROOT).equals("-update"))) { // aut-update yacy if (args.length == 2) applicationRoot = new File(args[1]); update(applicationRoot); } else if ((args.length >= 1) && (args[0].toLowerCase(Locale.ROOT).equals("-version"))) { // show yacy version System.out.println(copyright); } else if ((args.length > 1) && (args[0].toLowerCase(Locale.ROOT).equals("-config"))) { // set config parameter. Special handling of adminAccount=user:pwd (generates md5 encoded password) // on Windows parameter should be enclosed in doublequotes to accept = sign (e.g. -config "port=8090" "port.ssl=8043") File f = new File(dataRoot, "DATA/SETTINGS/"); if (!f.exists()) { mkdirsIfNeseccary(f); } else { if (new File(dataRoot, "DATA/yacy.running").exists()) { System.out.println("please restart YaCy"); } } // use serverSwitch to read config properties (including init values from yacy.init serverSwitch ss = new serverSwitch(dataRoot, applicationRoot, "defaults/yacy.init", "DATA/SETTINGS/yacy.conf"); for (int icnt = 1; icnt < args.length; icnt++) { String cfg = args[icnt]; int pos = cfg.indexOf('='); if (pos > 0) { String cmd = cfg.substring(0, pos); String val = cfg.substring(pos + 1); if (!val.isEmpty()) { if (cmd.equalsIgnoreCase(SwitchboardConstants.ADMIN_ACCOUNT)) { // special command to set adminusername and md5-pwd int cpos = val.indexOf(':'); //format adminAccount=adminname:adminpwd if (cpos >= 0) { String username = val.substring(0, cpos); String pwdtxt = val.substring(cpos + 1); if (!username.isEmpty()) { ss.setConfig(SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME, username); System.out.println("Set property " + SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME + " = " + username); } else { username = ss.getConfig(SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME, "admin"); } ss.setConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, "MD5:" + Digest.encodeMD5Hex(username + ":" + ss.getConfig(SwitchboardConstants.ADMIN_REALM, "YaCy") + ":" + pwdtxt)); System.out.println("Set property " + SwitchboardConstants.ADMIN_ACCOUNT_B64MD5 + " = " + ss.getConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, "")); } } else { ss.setConfig(cmd, val); System.out.println("Set property " + cmd + " = " + val); } } } else { System.out.println( "skip parameter " + cfg + " (equal sign missing, put parameter in doublequotes)"); } System.out.println(); } } else { if (args.length == 1) { applicationRoot = new File(args[0]); } preReadSavedConfigandInit(dataRoot); startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, false); } } finally { ConcurrentLog.shutdown(); } }
From source file:herddb.server.ServerMain.java
public static void main(String... args) { try {/*from w w w . jav a 2 s . c o m*/ LOG.log(Level.INFO, "Starting HerdDB version {0}", herddb.utils.Version.getVERSION()); Properties configuration = new Properties(); boolean configFileFromParameter = false; for (int i = 0; i < args.length; i++) { String arg = args[i]; if (!arg.startsWith("-")) { File configFile = new File(args[i]).getAbsoluteFile(); LOG.log(Level.INFO, "Reading configuration from {0}", configFile); try (InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile), StandardCharsets.UTF_8)) { configuration.load(reader); } configFileFromParameter = true; } else if (arg.equals("--use-env")) { System.getenv().forEach((key, value) -> { System.out.println("Considering env as system property " + key + " -> " + value); System.setProperty(key, value); }); } else if (arg.startsWith("-D")) { int equals = arg.indexOf('='); if (equals > 0) { String key = arg.substring(2, equals); String value = arg.substring(equals + 1); System.setProperty(key, value); } } } if (!configFileFromParameter) { File configFile = new File("conf/server.properties").getAbsoluteFile(); LOG.log(Level.INFO, "Reading configuration from {0}", configFile); if (configFile.isFile()) { try (InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile), StandardCharsets.UTF_8)) { configuration.load(reader); } } } System.getProperties().forEach((k, v) -> { String key = k + ""; if (!key.startsWith("java") && !key.startsWith("user")) { configuration.put(k, v); } }); LogManager.getLogManager().readConfiguration(); Runtime.getRuntime().addShutdownHook(new Thread("ctrlc-hook") { @Override public void run() { System.out.println("Ctrl-C trapped. Shutting down"); ServerMain _brokerMain = runningInstance; if (_brokerMain != null) { _brokerMain.close(); } } }); runningInstance = new ServerMain(configuration); runningInstance.start(); runningInstance.join(); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } }
From source file:eu.annocultor.converters.geonames.GeonamesDumpToRdf.java
public static void main(String[] args) throws Exception { File root = new File("input_source"); // load country-continent match countryToContinent// ww w . j a va 2 s. c o m .load((new GeonamesDumpToRdf()).getClass().getResourceAsStream("/country-to-continent.properties")); // creating files Map<String, BufferedWriter> files = new HashMap<String, BufferedWriter>(); Map<String, Boolean> started = new HashMap<String, Boolean>(); for (Object string : countryToContinent.keySet()) { String continent = countryToContinent.getProperty(string.toString()); File dir = new File(root, continent); if (!dir.exists()) { dir.mkdir(); } files.put(string.toString(), new BufferedWriter(new OutputStreamWriter( new FileOutputStream(new File(root, continent + "/" + string + ".rdf")), "UTF-8"))); System.out.println(continent + "/" + string + ".rdf"); started.put(string.toString(), false); } System.out.println(started); Pattern countryPattern = Pattern .compile("<inCountry rdf\\:resource\\=\"http\\://www\\.geonames\\.org/countries/\\#(\\w\\w)\"/>"); long counter = 0; LineIterator it = FileUtils.lineIterator(new File(root, "all-geonames-rdf.txt"), "UTF-8"); try { while (it.hasNext()) { String text = it.nextLine(); if (text.startsWith("http://sws.geonames")) continue; // progress counter++; if (counter % 100000 == 0) { System.out.print("*"); } // System.out.println(counter); // get country String country = null; Matcher matcher = countryPattern.matcher(text); if (matcher.find()) { country = matcher.group(1); } // System.out.println(country); if (country == null) country = "null"; text = text.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><rdf:RDF", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><rdf:RDF"); if (started.get(country) == null) throw new Exception("Unknow country " + country); if (started.get(country).booleanValue()) { // remove RDF opening text = text.substring(text.indexOf("<rdf:RDF ")); text = text.substring(text.indexOf(">") + 1); } // remove RDF ending text = text.substring(0, text.indexOf("</rdf:RDF>")); files.get(country).append(text + "\n"); if (!started.get(country).booleanValue()) { // System.out.println("Started with country " + country); } started.put(country, true); } } finally { LineIterator.closeQuietly(it); } for (Object string : countryToContinent.keySet()) { boolean hasStarted = started.get(string.toString()).booleanValue(); if (hasStarted) { BufferedWriter bf = files.get(string.toString()); bf.append("</rdf:RDF>"); bf.flush(); bf.close(); } } return; }
From source file:com.mycompany.myelasticsearch.MainClass.java
/** * @param args the command line arguments *//*from w ww.j a v a 2 s . com*/ public static void main(String[] args) { // TODO code application logic here Tika tika = new Tika(); String fileEntry = "C:\\Contract\\Contract1.pdf"; String filetype = tika.detect(fileEntry); System.out.println("FileType " + filetype); BodyContentHandler handler = new BodyContentHandler(-1); String text = ""; Metadata metadata = new Metadata(); FileInputStream inputstream = null; try { inputstream = new FileInputStream(fileEntry); } catch (FileNotFoundException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } ParseContext pcontext = new ParseContext(); //parsing the document using PDF parser PDFParser pdfparser = new PDFParser(); try { pdfparser.parse(inputstream, handler, metadata, pcontext); } catch (IOException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } catch (TikaException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } String docText = ""; String outputArray[]; String out[]; //getting the content of the document docText = handler.toString().replaceAll("(/[^\\da-zA-Z.]/)", ""); // PhraseDetection.getPhrases(docText); try { Node node = nodeBuilder().node(); Client client = node.client(); DocumentReader.parseString(docText, client); //"Borrowing should be replaced by the user input key" Elastic.getDefinedTerm(client, "definedterms", "term", "1", "Borrowing"); node.close(); } catch (FileNotFoundException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } Stanford.getSentence(docText); int definedTermsEnd = docText.indexOf("SCHEDULES"); String toc = docText.substring(0, definedTermsEnd); String c = docText.substring(definedTermsEnd); System.out.println("Table of content" + toc); System.out.println("--------------------------------"); System.out.println("content" + c); out = toc.split("Article|article|ARTICLE"); int count = 0; String outputArrayString = ""; int s = 0; StringBuffer tocOutput = new StringBuffer(); for (String o : out) { if (count != 0) { s = Integer.parseInt(String.valueOf(o.charAt(1))); if (s == count) { tocOutput.append(o); tocOutput.append("JigarAnkitNeeraj"); System.out.println(s); } } outputArrayString += "Count" + count + o; count++; System.out.println(); } System.out.println("---------------------------------------------------Content---------"); count = 1; StringBuffer contentOutput = new StringBuffer(); String splitContent[] = c.split("ARTICLE|Article"); Node node = nodeBuilder().node(); Client client = node.client(); for (String o : splitContent) { o = o.replaceAll("[^a-zA-Z0-9.,\\/#!$%\\^&\\*;:{}=\\-_`~()?\\s]+", ""); o = o.replaceAll("\n", " "); char input = o.charAt(1); if (input >= '0' && input <= '9') { s = Integer.parseInt(String.valueOf(o.charAt(1))); if (s == count) { //System.out.println(s); JSONObject articleJSONObject = new JSONObject(); contentOutput.append(" \n MyArticlesSeparated \n "); articleJSONObject.put("Article" + count, o.toString()); try { try { JSONObject articleJSONObject1 = new JSONObject(); articleJSONObject1.put("hi", "j"); client.prepareIndex("contract", "article", String.valueOf(count)) .setSource(articleJSONObject.toString()).execute().actionGet(); } catch (Exception e) { System.out.println(e.getMessage()); } //"Borrowing should be replaced by the user input key" } catch (Exception ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(s); count++; } //outputArrayString += "Count" + count + o; contentOutput.append(o); } } Elastic.getDocument(client, "contract", "article", "1"); Elastic.searchDocument(client, "contract", "article", "Lenders"); Elastic.searchDocument(client, "contract", "article", "Negative Covenants"); Elastic.searchDocument(client, "contract", "article", "Change in Law"); String tableOfContent[]; tableOfContent = tocOutput.toString().split("JigarAnkitNeeraj"); String splitContectsAccordingToArticles[]; splitContectsAccordingToArticles = contentOutput.toString().split("MyArticlesSeparated"); int numberOfArticle = splitContectsAccordingToArticles.length; int countArticle = 1; Double toBeTruncated = new Double("" + countArticle + ".00"); String section = "Section"; toBeTruncated += 0.01; System.out.println(toBeTruncated); String sectionEnd; StringBuffer sectionOutput = new StringBuffer(); int skipFirstArtcile = 0; JSONObject obj = new JSONObject(); for (String article : splitContectsAccordingToArticles) { if (skipFirstArtcile != 0) { DecimalFormat f = new DecimalFormat("##.00"); String sectionStart = section + " " + f.format(toBeTruncated); int start = article.indexOf(sectionStart); toBeTruncated += 0.01; System.out.println(); sectionEnd = section + " " + f.format(toBeTruncated); int end = article.indexOf(sectionEnd); while (end != -1) { sectionStart = section + " " + f.format(toBeTruncated - 0.01); sectionOutput.append(" \n Key:" + sectionStart); if (start < end) { sectionOutput.append("\n Value:" + article.substring(start, end)); obj.put(sectionStart, article.substring(start, end).replaceAll("\\r\\n|\\r|\\n", " ")); try { try { JSONObject articleJSONObject1 = new JSONObject(); articleJSONObject1.put("hi", "j"); client.prepareIndex("contract", "section", String.valueOf(count)) .setSource(obj.toString()).execute().actionGet(); } catch (Exception e) { System.out.println(e.getMessage()); } //"Borrowing should be replaced by the user input key" } catch (Exception ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } } start = end; toBeTruncated += 0.01; sectionEnd = section + " " + f.format(toBeTruncated); System.out.println("SectionEnd " + sectionEnd); try { end = article.indexOf(sectionEnd); } catch (Exception e) { System.out.print(e.getMessage()); } System.out.println("End section index " + end); } end = article.length() - 1; sectionOutput.append(" \n Key:" + sectionStart); try { sectionOutput.append(" \n Value:" + article.substring(start, end)); obj.put(sectionStart, article.substring(start, end).replaceAll("\\r\\n|\\r|\\n", " ")); } catch (Exception e) { //What if Article has No Sections String numberOnly = article.replaceAll("[^0-9]", "").substring(0, 1); String sectionArticle = "ARTICLE " + numberOnly; sectionOutput.append(" \n Value:" + article); obj.put(sectionArticle, article); System.out.println(e.getMessage()); } DecimalFormat ff = new DecimalFormat("##"); toBeTruncated = Double.valueOf(ff.format(toBeTruncated)) + 1.01; } skipFirstArtcile++; } for (String article : splitContectsAccordingToArticles) { if (skipFirstArtcile != 0) { DecimalFormat f = new DecimalFormat("##.00"); String sectionStart = section + " " + f.format(toBeTruncated); int start = article.indexOf(sectionStart); toBeTruncated += 0.01; System.out.println(); sectionEnd = section + " " + f.format(toBeTruncated); int end = article.indexOf(sectionEnd); while (end != -1) { sectionStart = section + " " + f.format(toBeTruncated - 0.01); sectionOutput.append(" \n Key:" + sectionStart); if (start < end) { sectionOutput.append("\n Value:" + article.substring(start, end)); System.out.println(sectionOutput); String patternStr = "\\n\\n+[(]"; String paragraphSubstringArray[] = article.substring(start, end).split(patternStr); JSONObject paragraphObject = new JSONObject(); int counter = 0; for (String paragraphSubstring : paragraphSubstringArray) { counter++; paragraphObject.put("Paragraph " + counter, paragraphSubstring); } obj.put(sectionStart, paragraphObject); } start = end; toBeTruncated += 0.01; sectionEnd = section + " " + f.format(toBeTruncated); System.out.println("SectionEnd " + sectionEnd); try { end = article.indexOf(sectionEnd); } catch (Exception e) { System.out.print(e.getMessage()); } System.out.println("End section index " + end); } end = article.length() - 1; sectionOutput.append(" \n Key:" + sectionStart); try { sectionOutput.append(" \n Value:" + article.substring(start, end)); obj.put(sectionStart, article.substring(start, end)); PhraseDetection.getPhrases(docText); } catch (Exception e) { //What if Article has No Sections String sectionArticle = "ARTICLE"; System.out.println(e.getMessage()); } DecimalFormat ff = new DecimalFormat("##"); toBeTruncated = Double.valueOf(ff.format(toBeTruncated)) + 1.01; } skipFirstArtcile++; } Elastic.getDocument(client, "contract", "section", "1"); Elastic.searchDocument(client, "contract", "section", "Lenders"); Elastic.searchDocument(client, "contract", "section", "Negative Covenants"); try { FileWriter file = new FileWriter("TableOfIndex.txt"); file.write(tocOutput.toString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } try { FileWriter file = new FileWriter("Contract3_JSONFile.txt"); file.write(obj.toString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } try { FileWriter file = new FileWriter("Contract1_KeyValueSections.txt"); file.write(sectionOutput.toString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.servoy.extensions.plugins.http.HttpProvider.java
public static void main(String[] args) throws Exception { if (args.length != 3) { System.out.println("Use: ContentFetcher mainurl contenturl destdir"); //$NON-NLS-1$ System.out.println(/* www. j a v a 2 s.co m*/ "Example: ContentFetcher http://site.com http://site.com/dir[0-2]/image_A[001-040].jpg c:/temp"); //$NON-NLS-1$ System.out.println( "Result: accessing http://site.com for cookie, reading http://site.com/dir1/image_A004.jpg writing c:/temp/dir_1_image_A004.jpg"); //$NON-NLS-1$ } else { String url = args[1]; String destdir = args[2]; List parts = new ArrayList(); int dir_from = 0; int dir_to = 0; int dir_fill = 0; int from = 0; int to = 0; int fill = 0; StringTokenizer tk = new StringTokenizer(url, "[]", true); //$NON-NLS-1$ boolean hasDir = (tk.countTokens() > 5); boolean inDir = hasDir; System.out.println("hasDir " + hasDir); //$NON-NLS-1$ boolean inTag = false; while (tk.hasMoreTokens()) { String token = tk.nextToken(); if (token.equals("[")) //$NON-NLS-1$ { inTag = true; continue; } if (token.equals("]")) //$NON-NLS-1$ { inTag = false; if (inDir) inDir = false; continue; } if (inTag) { int idx = token.indexOf('-'); String s_from = token.substring(0, idx); int a_from = new Integer(s_from).intValue(); int a_fill = s_from.length(); int a_to = new Integer(token.substring(idx + 1)).intValue(); if (inDir) { dir_from = a_from; dir_to = a_to; dir_fill = a_fill; } else { from = a_from; to = a_to; fill = a_fill; } } else { parts.add(token); } } DefaultHttpClient client = new DefaultHttpClient(); client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); HttpGet main = new HttpGet(args[0]); HttpResponse res = client.execute(main); ; int main_rs = res.getStatusLine().getStatusCode(); if (main_rs != 200) { System.out.println("main page retrieval failed " + main_rs); //$NON-NLS-1$ return; } for (int d = dir_from; d <= dir_to; d++) { String dir_number = "" + d; //$NON-NLS-1$ if (dir_fill > 1) { dir_number = "000000" + d; //$NON-NLS-1$ int dir_digits = (int) (Math.log(fill) / Math.log(10)); System.out.println("dir_digits " + dir_digits); //$NON-NLS-1$ dir_number = dir_number.substring(dir_number.length() - (dir_fill - dir_digits), dir_number.length()); } for (int i = from; i <= to; i++) { try { String number = "" + i; //$NON-NLS-1$ if (fill > 1) { number = "000000" + i; //$NON-NLS-1$ int digits = (int) (Math.log(fill) / Math.log(10)); System.out.println("digits " + digits); //$NON-NLS-1$ number = number.substring(number.length() - (fill - digits), number.length()); } int part = 0; StringBuffer surl = new StringBuffer((String) parts.get(part++)); if (hasDir) { surl.append(dir_number); surl.append(parts.get(part++)); } surl.append(number); surl.append(parts.get(part++)); System.out.println("reading url " + surl); //$NON-NLS-1$ int indx = surl.toString().lastIndexOf('/'); StringBuffer sfile = new StringBuffer(destdir); sfile.append("\\"); //$NON-NLS-1$ if (hasDir) { sfile.append("dir_"); //$NON-NLS-1$ sfile.append(dir_number); sfile.append("_"); //$NON-NLS-1$ } sfile.append(surl.toString().substring(indx + 1)); File file = new File(sfile.toString()); if (file.exists()) { file = new File("" + System.currentTimeMillis() + sfile.toString()); } System.out.println("write file " + file.getAbsolutePath()); //$NON-NLS-1$ // URL iurl = createURLFromString(surl.toString()); HttpGet get = new HttpGet(surl.toString()); HttpResponse response = client.execute(get); int result = response.getStatusLine().getStatusCode(); System.out.println("page http result " + result); //$NON-NLS-1$ if (result == 200) { InputStream is = response.getEntity().getContent(); FileOutputStream fos = new FileOutputStream(file); Utils.streamCopy(is, fos); fos.close(); } } catch (Exception e) { System.err.println(e); } } } } }