label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public InputStream getEntry(String entryPath) throws IOException { if (!entries.contains(entryPath)) { return null; } JarInputStream jis = new JarInputStream(new BufferedInputStream(url.openStream())); do { ZipEntry ze = jis.getNextEntry(); if (ze == null) { break; } if (ze.getName().equals(entryPath)) { return jis; } } while (true); assert (false); return null; } Code Sample 2: public static void copy(String sourceName, String destName, StatusWindow status) throws IOException { File src = new File(sourceName); File dest = new File(destName); BufferedInputStream source = null; BufferedOutputStream destination = null; byte[] buffer; int bytes_read; long byteCount = 0; if (!src.exists()) throw new IOException("Source not found: " + src); if (!src.canRead()) throw new IOException("Source is unreadable: " + src); if (src.isFile()) { if (!dest.exists()) { File parentdir = Utils.parent(dest); if (!parentdir.exists()) parentdir.mkdir(); } else if (dest.isDirectory()) { if (src.isDirectory()) dest = new File(dest + File.separator + src); else dest = new File(dest + File.separator + src.getName()); } } else if (src.isDirectory()) { if (dest.isFile()) throw new IOException("Cannot copy directory " + src + " to file " + dest); if (!dest.exists()) dest.mkdir(); } if ((!dest.canWrite()) && (dest.exists())) throw new IOException("Destination is unwriteable: " + dest); if (src.isFile()) { try { if (status != null) { status.setMaximum(100); status.setMessage(Utils.trimFileName(src.toString(), 40), 50); } source = new BufferedInputStream(new FileInputStream(src)); destination = new BufferedOutputStream(new FileOutputStream(dest)); buffer = new byte[4096]; byteCount = 0; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (status != null) { status.setMessage(Utils.trimFileName(src.toString(), 40), 100); } if (source != null) source.close(); if (destination != null) destination.close(); } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); if (status != null) { status.setMaximum(files.length); } for (int i = 0; i < files.length; i++) { if (status != null) { status.setMessage(Utils.trimFileName(src.toString(), 40), i); } targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target).getCanonicalPath(), new File(targetdest).getCanonicalPath(), status); } else { try { byteCount = 0; source = new BufferedInputStream(new FileInputStream(target)); destination = new BufferedOutputStream(new FileOutputStream(targetdest)); buffer = new byte[4096]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } } } }
11
Code Sample 1: private void backupOriginalFile(String myFile) { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_S"); String datePortion = format.format(date); try { FileInputStream fis = new FileInputStream(myFile); FileOutputStream fos = new FileOutputStream(myFile + "-" + datePortion + "_UserID" + ".html"); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); fis.close(); fos.close(); System.out.println("**** Backup of file made."); } catch (Exception e) { System.out.println(e); } } Code Sample 2: public long copyDirAllFilesToDirectory(String baseDirStr, String destDirStr) throws Exception { long plussQuotaSize = 0; if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(destDirStr); BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if (!baseDir.exists()) { createDirectory(baseDirStr); } if ((baseDir.exists()) && (baseDir.isDirectory())) { String[] entryList = baseDir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String oldPathFileName = baseDirStr + sep + entryName; File entryFile = new File(oldPathFileName); if (entryFile.isFile()) { String newPathFileName = destDirStr + sep + entryName; File newFile = new File(newPathFileName); if (newFile.exists()) { plussQuotaSize -= newFile.length(); newFile.delete(); } in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } } } } else { throw new Exception("Base dir not exist ! baseDirStr = (" + baseDirStr + ")"); } return plussQuotaSize; }
00
Code Sample 1: public static void copyFile(String inputFile, String outputFile) throws IOException { FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); for (int b = fis.read(); b != -1; b = fis.read()) fos.write(b); fos.close(); fis.close(); } Code Sample 2: protected String getPostRequestContent(String urlText, String postParam) throws Exception { URL url = new URL(urlText); HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); String line = null; try { urlcon.setRequestMethod("POST"); urlcon.setUseCaches(false); urlcon.setDoOutput(true); PrintStream ps = new PrintStream(urlcon.getOutputStream()); ps.print(postParam); ps.close(); urlcon.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream())); line = reader.readLine(); reader.close(); } finally { urlcon.disconnect(); } return line; }
00
Code Sample 1: public void testJTLM_publish911() throws Exception { EXISchema corpus = EXISchemaFactoryTestUtil.getEXISchema("/JTLM/schemas/TLMComposite.xsd", getClass(), m_compilerErrors); Assert.assertEquals(0, m_compilerErrors.getTotalCount()); GrammarCache grammarCache = new GrammarCache(corpus, GrammarOptions.STRICT_OPTIONS); AlignmentType alignment = AlignmentType.compress; Transmogrifier encoder = new Transmogrifier(); EXIDecoder decoder = new EXIDecoder(); Scanner scanner; InputSource inputSource; encoder.setAlignmentType(alignment); decoder.setAlignmentType(alignment); encoder.setEXISchema(grammarCache); ByteArrayOutputStream baos = new ByteArrayOutputStream(); encoder.setOutputStream(baos); URL url = resolveSystemIdAsURL("/JTLM/publish911.xml"); inputSource = new InputSource(url.toString()); inputSource.setByteStream(url.openStream()); byte[] bts; int n_events, n_texts; encoder.encode(inputSource); bts = baos.toByteArray(); decoder.setEXISchema(grammarCache); decoder.setInputStream(new ByteArrayInputStream(bts)); scanner = decoder.processHeader(); ArrayList<EXIEvent> exiEventList = new ArrayList<EXIEvent>(); EXIEvent exiEvent; n_events = 0; n_texts = 0; while ((exiEvent = scanner.nextEvent()) != null) { ++n_events; if (exiEvent.getEventVariety() == EXIEvent.EVENT_CH) { if (exiEvent.getCharacters().length() == 0) { --n_events; continue; } if (n_texts % 100 == 0) { final int n = n_texts / 100; Assert.assertEquals(JTLMTest.publish911_centennials[n], exiEvent.getCharacters().makeString()); } ++n_texts; } exiEventList.add(exiEvent); } Assert.assertEquals(96576, n_events); } Code Sample 2: public static void main(String[] args) { try { Transaction transaction = session.beginTransaction(); URL url1 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/keren.jpg"); HttpURLConnection conn1 = (HttpURLConnection) url1.openConnection(); conn1.connect(); Users keren = new Users("kerenhaas@gmail.com", "123456", "keren", null, "sokolov 14 Raanana", Hibernate.createBlob(conn1.getInputStream(), conn1.getContentLength()), "about keren", "admin", false); session.save(keren); session.flush(); session.refresh(keren); URL url2 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/alex.jpg"); HttpURLConnection conn2 = (HttpURLConnection) url2.openConnection(); Users alex = new Users("alex.uretsky@mail.huji.ac.il", "123456", "alex", null, null, Hibernate.createBlob(conn2.getInputStream(), conn2.getContentLength()), null, "admin", false); session.save(alex); session.flush(); session.refresh(alex); URL url3 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/julia.jpg"); HttpURLConnection conn3 = (HttpURLConnection) url3.openConnection(); conn3.connect(); Users julia = new Users("juliasht@gmail.com", "123456", "julia", null, null, Hibernate.createBlob(conn3.getInputStream(), conn3.getContentLength()), null, "admin", false); session.save(julia); session.flush(); session.refresh(julia); URL url4 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/meir.jpg"); HttpURLConnection conn4 = (HttpURLConnection) url4.openConnection(); conn4.connect(); Users meir = new Users("meir.spielrein@mail.huji.ac.il", "123456", "meir", null, null, Hibernate.createBlob(conn4.getInputStream(), conn4.getContentLength()), null, "admin", false); session.save(meir); session.flush(); session.refresh(meir); URL url5 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/miki.jpg"); HttpURLConnection conn5 = (HttpURLConnection) url5.openConnection(); conn5.connect(); Users miki = new Users("miki.shifman@mail.huji.ac.il", "123456", "miki", null, null, Hibernate.createBlob(conn5.getInputStream(), conn5.getContentLength()), null, "admin", false); session.save(miki); session.flush(); session.refresh(miki); URL url6 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/tamar.jpg"); HttpURLConnection conn6 = (HttpURLConnection) url6.openConnection(); conn6.connect(); Users tami = new Users("taamar@gmail.com", "123456", "tami", null, null, Hibernate.createBlob(conn6.getInputStream(), conn6.getContentLength()), null, "admin", false); session.save(tami); session.flush(); session.refresh(tami); Lists basicComplexity = new Lists("Complexity", "Basic"); session.save(basicComplexity); Lists mediumComplexity = new Lists("Complexity", "Medium"); session.save(mediumComplexity); Lists highComplexity = new Lists("Complexity", "High"); session.save(highComplexity); Lists chefComplexity = new Lists("Complexity", "Chef"); session.save(chefComplexity); Lists appetizers = new Lists("DishType", "Appetizers"); session.save(appetizers); Lists firstCourse = new Lists("DishType", "First Course"); session.save(firstCourse); Lists mainCourse = new Lists("DishType", "Main Course"); session.save(mainCourse); Lists dessert = new Lists("DishType", "Dessert"); session.save(dessert); Lists cocktails = new Lists("DishType", "Cocktails"); session.save(cocktails); System.out.println("2 : " + session.isOpen()); Lists italian = new Lists("Cuisine", "Italian"); session.save(italian); Lists chinese = new Lists("Cuisine", "Chinese"); session.save(chinese); Lists indian = new Lists("Cuisine", "Indian"); session.save(indian); Lists french = new Lists("Cuisine", "French"); session.save(french); Lists thai = new Lists("Cuisine", "Thai"); session.save(thai); Lists arabic = new Lists("Cuisine", "Arabic"); session.save(arabic); Lists israeli = new Lists("Cuisine", "Israeli"); session.save(israeli); Lists other = new Lists("Cuisine", "Other"); session.save(other); Ingredients flour = new Ingredients("flour"); session.save(flour); Ingredients sugar = new Ingredients("white sugar"); session.save(sugar); Ingredients bakingPower = new Ingredients("baking powder"); session.save(bakingPower); Ingredients groundNutmeg = new Ingredients("ground nutmeg"); session.save(groundNutmeg); Ingredients salt = new Ingredients("salt"); session.save(salt); Ingredients pepper = new Ingredients("pepper"); session.save(pepper); Ingredients egg = new Ingredients("egg"); session.save(egg); Ingredients milk = new Ingredients("milk"); session.save(milk); Ingredients butter = new Ingredients("butter"); session.save(butter); Ingredients groundCinnamon = new Ingredients("ground cinnamon"); session.save(groundCinnamon); Ingredients strawberries = new Ingredients("strawberries"); session.save(strawberries); Ingredients bisquick = new Ingredients("bisquick"); session.save(bisquick); Ingredients whippedCream = new Ingredients("Whipped Cream"); session.save(whippedCream); Ingredients potato = new Ingredients("potato"); session.save(potato); Ingredients carrot = new Ingredients("carrot"); session.save(carrot); Ingredients onion = new Ingredients("onion"); session.save(onion); Ingredients ketchup = new Ingredients("ketchup"); session.save(ketchup); Ingredients mustard = new Ingredients("mustard"); session.save(mustard); Ingredients cookingCream = new Ingredients("Cooking Cream"); session.save(cookingCream); Ingredients bread = new Ingredients("bread"); session.save(bread); Ingredients caviar = new Ingredients("caviar"); session.save(caviar); Ingredients foigra = new Ingredients("foigra"); session.save(foigra); Ingredients vodka = new Ingredients("vodka"); session.save(vodka); Ingredients orangeJuice = new Ingredients("orangeJuice"); session.save(orangeJuice); Ingredients ribs = new Ingredients("ribs"); session.save(ribs); Ingredients tomato = new Ingredients("tomato"); session.save(tomato); Ingredients cucumber = new Ingredients("cucumber"); session.save(cucumber); Ingredients oliveoil = new Ingredients("olive oil"); session.save(oliveoil); Ingredients chickenBreast = new Ingredients("chicken Breast"); session.save(chickenBreast); Ingredients apple = new Ingredients("apple"); session.save(apple); Ingredients vanilla = new Ingredients("vanilla"); session.save(vanilla); String description; description = "These muffins are delicious! The cinnamon sugar topping flavors them perfectly. This is my 10 year old brother's favorite recipe"; Recipes rec1 = addRecipe(basicComplexity, description, "French Breakfast Muffins", keren, 10, 25, 12, dessert, "http://www.cs.huji.ac.il/~keren_ha/J2EE/muffins.jpg", Arrays.asList("Preheat oven to 350 degrees F (175 degrees C). Grease muffin cups or line with paper muffin liners.", "In a medium mixing bowl, stir together flour, 1/2 cup sugar, baking powder, nutmeg and salt. Make a well in the center of the mixture. Stir together egg, milk and 1/3 cup melted butter. Add egg mixture to flour mixture; stir until just moistened (batter may be lumpy). Spoon batter into prepared muffin cups.", "Bake in preheated oven for 20 to 25 minutes. Meanwhile, combine 1/4 cup sugar, cinnamon When muffins are finished baking, dip tops of muffins in the melted butter, and then in the cinnamon sugar mixture. Serve warm.")); createRecipeIngredients(rec1, flour, 1.5, "cups"); createRecipeIngredients(rec1, sugar, 0.5, "cups"); createRecipeIngredients(rec1, bakingPower, 1.5, "teaspoons"); createRecipeIngredients(rec1, groundNutmeg, 0.25, "teaspoons"); createRecipeIngredients(rec1, salt, 0.125, "teaspoons"); createRecipeIngredients(rec1, egg, 1, "lightly beaten"); createRecipeIngredients(rec1, milk, 0.5, "cups"); createRecipeIngredients(rec1, butter, 0.33, "cups"); createRecipeIngredients(rec1, groundCinnamon, 0.25, "cups"); createRecipeIngredients(rec1, groundCinnamon, 0.5, "teaspoon"); createRecipeIngredients(rec1, sugar, 0.33, "cups"); session.flush(); session.refresh(rec1); description = "This dish leaves even the biggest pasta lover satisfied. Fresh vegetables make this dish wonderful and it's easy to add meat to if you wish."; Recipes rec2 = addRecipe(mediumComplexity, description, "Veggie Pasta Minus the Pasta", alex, 30, 40, 6, mainCourse, "http://2.bp.blogspot.com/_wAVccjOeYzc/R4KYRa5MkLI/AAAAAAAAGz8/WeosqyuyjoQ/s400/vegetarian-tofu-curry-recipe+(13).JPG", Arrays.asList("Preheat an oven to 350 degrees F (175 degrees C). Arrange the tomatoes on a baking sheet with the cut sides facing up. ", "Roast the tomatoes in the preheated oven until cooked through and slightly browned on the underside, about 15 minutes. ", "Place squash halves face down in glass baking dish with the water; cover with plastic wrap. Microwave on High for 8 minutes. Leave covered and set aside. Once the squash is cool enough to handle, scrape in strands into a large bowl with a fork; season with salt and pepper and toss with 1 tablespoon olive oil. ", "Heat the remaining 2 tablespoons olive oil in a large skillet over medium-low heat; cook and stir the garlic, basil, and Italian seasoning in the oil until the garlic is softened, about 10 minutes. Add the onion, green bell pepper, eggplant, and carrot to the garlic; increase heat to medium. Continue cooking and stirring until the vegetables are nearly tender, 10 to 15 minutes. Mix the tomatoes and white wine into the vegetable mixture; cook another 2 to 3 minutes. Transfer the vegetables to the bowl with the spaghetti squash; gently toss together.")); createRecipeIngredients(rec2, flour, 1.5, "cups"); createRecipeIngredients(rec2, sugar, 0.5, "cups"); createRecipeIngredients(rec2, bakingPower, 1.5, "teaspoons"); createRecipeIngredients(rec2, groundNutmeg, 0.25, "teaspoons"); createRecipeIngredients(rec2, salt, 0.125, "teaspoons"); createRecipeIngredients(rec2, egg, 1, "lightly beaten"); createRecipeIngredients(rec2, milk, 0.5, "cups"); createRecipeIngredients(rec2, butter, 0.33, "cups"); createRecipeIngredients(rec2, groundCinnamon, 0.25, "cups"); createRecipeIngredients(rec2, groundCinnamon, 0.5, "teaspoon"); createRecipeIngredients(rec2, sugar, 0.33, "cups"); createComment(rec2, 1, julia, "This dish was extremely disappointing. I was very optimistic looking at the ingredient list, but after putting it all together, there was a profound lack of flavor. We eat a good deal of vegetable dishes, but this is not one we will be repeating."); createComment(rec2, 4, alex, "Very good, I also think to use less butter."); session.flush(); session.refresh(rec2); description = "A finger licking good strawberry cake!"; Recipes rec3 = addRecipe(basicComplexity, description, "Strawberry short cake", alex, 60, 70, 12, dessert, "http://static.open.salon.com/files/coconut_strawberry_cake1226877577.jpg", Arrays.asList("Sprinkle strawberries with 2/3 cups sugar. Let stand 1 hour ", "Heat over to 425 degrees.", "Mix all ingredients and place in the over", "Slice it and eat up!")); createRecipeIngredients(rec3, strawberries, 1.5, "cups"); createRecipeIngredients(rec3, sugar, 0.66, "cups"); createRecipeIngredients(rec3, bisquick, 2, "boxese"); createRecipeIngredients(rec3, sugar, 3, "tablespoons"); createRecipeIngredients(rec3, milk, 0.5, "cups"); createRecipeIngredients(rec3, whippedCream, 0.75, "cups"); createComment(rec3, 5, julia, "Best cake I ever had!!! Kudos!!"); session.flush(); session.refresh(rec3); description = "My secret Barbecue Beef Short Ribs recipe revealed!"; Recipes rec4 = addRecipe(highComplexity, description, "Short Ribs", meir, 70, 500, 6, mainCourse, "http://farm2.static.flickr.com/1310/1237575824_9068241a81.jpg", Arrays.asList("Put the potatoes and carrots in a large slow cooker", "Top with the onion wedges then the beef", "Combine the ketchup, , mustrard and salt", "Put ofver the beef", "Cook on LOW for 8 to 10 hours")); createRecipeIngredients(rec4, potato, 10, "pieces"); createRecipeIngredients(rec4, carrot, 1, "cups"); createRecipeIngredients(rec4, onion, 2, "units"); createRecipeIngredients(rec4, ribs, 3.5, "pounds"); createRecipeIngredients(rec4, ketchup, 1, "cups"); createRecipeIngredients(rec4, mustard, 0.5, "teaspoon"); createComment(rec4, 4, keren, "My whole family loved it!"); createComment(rec4, 5, alex, "This was outstanding, will definitely use this recipe often. I used chicken legs as that was what I had and it worked great. thanks!!!!"); session.flush(); session.refresh(rec4); description = "a simple, yet yasty, Salad"; Recipes rec5 = addRecipe(basicComplexity, description, "Garden Salad", alex, 10, 15, 6, firstCourse, "http://ww-recipes.net/wp-content/uploads/2008/09/weight-watchers-arabic-salad-recipe.jpg", Arrays.asList("Slice the tomatoes to cubes", "Slice the cucumbers to julian strips", "add a pinch salt and pepper", "top with olive oil")); createRecipeIngredients(rec5, tomato, 3, "pieces"); createRecipeIngredients(rec5, cucumber, 3, "pieces"); createRecipeIngredients(rec5, oliveoil, 2, "tablespoons"); createRecipeIngredients(rec5, salt, 1, "pinch"); createRecipeIngredients(rec5, pepper, 1, "pinch"); createComment(rec5, 5, julia, "Delicious and so easy to make!"); session.flush(); session.refresh(rec5); description = "Creme Brule - the full recipe! no shortcuts ;) "; Recipes rec7 = addRecipe(highComplexity, description, "Creme brule", miki, 30, 200, 6, dessert, "http://www.cookingforengineers.com/hello/259/958/640/IMG_3335_sharp.jpg", Arrays.asList("bring the cooking cream to boiling temperature", "insert vanilla stick", "whisk eggs with sugar", "add cream to eggs CAREFULLY", "put in over for 30 minutes, then to the fridge for 4 hours")); createRecipeIngredients(rec7, cookingCream, 2, "cartons"); createRecipeIngredients(rec7, egg, 3, "yolks"); createRecipeIngredients(rec7, sugar, 2, "tablespoons"); createRecipeIngredients(rec7, vanilla, 1, "stick"); createComment(rec7, 4, julia, "Delicious and so easy to make!"); session.flush(); session.refresh(rec7); description = "some toasts with foigra to get the meal started"; Recipes rec8 = addRecipe(basicComplexity, description, "foigra on toast", alex, 15, 15, 6, appetizers, "http://www.italiq-expos.com/news/images/Gastronomie/Foie-gras/assiette-foie-gras.jpg", Arrays.asList("cut bread into oval slices", "place in toaster until a golden brown color in formed", "speard some foigra pate on the toasts", "optional - add some baluga caviar on top")); createRecipeIngredients(rec8, bread, 6, "slices"); createRecipeIngredients(rec8, foigra, 1, "can"); createRecipeIngredients(rec8, caviar, 1, "minijar"); createComment(rec8, 5, julia, "Delicious and so easy to make!"); session.flush(); session.refresh(rec8); description = "delicious diatetic chicken steak"; Recipes rec9 = addRecipe(mediumComplexity, description, "chicken steak", meir, 15, 20, 2, mainCourse, "http://4.bp.blogspot.com/_jhlSdMizhlU/RdOVtm-0QAI/AAAAAAAAABg/81W-JvXOACI/s400/Chicken_Steak.jpg", Arrays.asList("Heat a frying pan with some (preferably olive) oil", "when the oil is hot, place the chicken and onions in the middle", "fry on both sides on medium flame until it starts to turn golden", "season with salt and pepper")); createRecipeIngredients(rec9, chickenBreast, 2, "pieces"); createRecipeIngredients(rec9, onion, 1, "piece"); createRecipeIngredients(rec9, salt, 1, "pinch"); createRecipeIngredients(rec9, pepper, 1, "pinch"); createComment(rec9, 5, julia, "Delicious and so easy to make!"); session.flush(); session.refresh(rec9); Favorites fav1 = new Favorites(keren, rec1, null); session.save(fav1); Favorites fav2 = new Favorites(keren, rec2, null); session.save(fav2); Favorites fav3 = new Favorites(keren, rec3, null); session.save(fav3); Favorites fav4 = new Favorites(keren, rec4, null); session.save(fav4); Favorites fav5 = new Favorites(alex, rec4, null); session.save(fav5); Favorites fav6 = new Favorites(alex, rec2, null); session.save(fav6); RecentlyViewed recViewed1 = new RecentlyViewed(keren, rec1, new Date()); session.save(recViewed1); RecentlyViewed recViewed2 = new RecentlyViewed(keren, rec2, new Date()); session.save(recViewed2); Friends friend1 = new Friends(keren, alex, true); session.save(friend1); Friends friend2 = new Friends(alex, keren, true); session.save(friend2); Friends friend3 = new Friends(keren, julia, false); session.save(friend3); Friends friend4 = new Friends(keren, meir, true); session.save(friend4); Friends friend5 = new Friends(meir, keren, true); session.save(friend5); Friends friend6 = new Friends(tami, keren, false); session.save(friend6); transaction.commit(); } catch (Exception e) { e.printStackTrace(); } finally { session.flush(); session.close(); } }
00
Code Sample 1: public void addEntry(InputStream jis, JarEntry entry) throws IOException, URISyntaxException { File target = new File(this.target.getPath() + entry.getName()).getAbsoluteFile(); if (!target.exists()) { target.createNewFile(); } if ((new File(this.source.toURI())).isDirectory()) { File sourceEntry = new File(this.source.getPath() + entry.getName()); FileInputStream fis = new FileInputStream(sourceEntry); byte[] classBytes = new byte[fis.available()]; fis.read(classBytes); (new FileOutputStream(target)).write(classBytes); } else { readwriteStreams(jis, (new FileOutputStream(target))); } } Code Sample 2: public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { InputStream urlStream = url.openStream(); AudioFileFormat fileFormat = null; try { fileFormat = getFMT(urlStream, false); } finally { if (fileFormat == null) { urlStream.close(); } } return new AudioInputStream(urlStream, fileFormat.getFormat(), fileFormat.getFrameLength()); }
00
Code Sample 1: public void testSetRequestProperty() throws Exception { MockHTTPServer httpServer = new MockHTTPServer("HTTP Server for User-Specified Request Property", 2); httpServer.start(); synchronized (bound) { if (!httpServer.started) { bound.wait(5000); } } HttpURLConnection urlConnection = (HttpURLConnection) new URL("http://localhost:" + httpServer.port()).openConnection(); assertEquals(0, urlConnection.getRequestProperties().size()); final String PROPERTY1 = "Accept"; final String PROPERTY2 = "Connection"; urlConnection.setRequestProperty(PROPERTY1, null); urlConnection.setRequestProperty(PROPERTY1, null); urlConnection.setRequestProperty(PROPERTY2, "keep-alive"); assertEquals(2, urlConnection.getRequestProperties().size()); assertNull(urlConnection.getRequestProperty(PROPERTY1)); assertEquals("keep-alive", urlConnection.getRequestProperty(PROPERTY2)); urlConnection.setRequestProperty(PROPERTY1, "/"); urlConnection.setRequestProperty(PROPERTY2, null); assertEquals("/", urlConnection.getRequestProperty(PROPERTY1)); assertNull(urlConnection.getRequestProperty(PROPERTY2)); } Code Sample 2: public static void main(String[] args) { if (args.length == 0) { System.out.println("Usage: java JMEImpl inputfile"); System.exit(0); } JME jme = null; try { URL url = new URL(Util.makeAbsoluteURL(args[0])); BufferedReader bReader = new BufferedReader(new InputStreamReader(url.openStream())); int idx = args[0].indexOf("."); String id = (idx == -1) ? args[0] : args[0].substring(0, idx); idx = id.lastIndexOf("\\"); if (idx != -1) id = id.substring(idx + 1); jme = new JMEImpl(bReader, id); CMLMolecule mol = jme.getMolecule(); StringWriter sw = new StringWriter(); mol.debug(sw); System.out.println(sw.toString()); SpanningTree sTree = new SpanningTreeImpl(mol); System.out.println(sTree.toSMILES()); Writer w = new OutputStreamWriter(new FileOutputStream(id + ".xml")); PMRDelegate.outputEventStream(mol, w, PMRNode.PRETTY, 0); w.close(); w = new OutputStreamWriter(new FileOutputStream(id + "-new.mol")); jme.setOutputCMLMolecule(mol); jme.output(w); w.close(); } catch (Exception e) { System.out.println("JME failed: " + e); e.printStackTrace(); System.exit(0); } }
00
Code Sample 1: private void extractByParsingHtml(String refererURL, String requestURL) throws MalformedURLException, IOException { URL url = new URL(refererURL); InputStream is = url.openStream(); mRefererURL = refererURL; if (requestURL.startsWith("http://www.")) { mRequestURLWWW = requestURL; mRequestURL = "http://" + mRequestURLWWW.substring(11); } else { mRequestURL = requestURL; mRequestURLWWW = "http://www." + mRequestURL.substring(7); } Parser parser = (new HTMLEditorKit() { public Parser getParser() { return super.getParser(); } }).getParser(); StringBuffer sb = new StringBuffer(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); try { String line = null; while ((line = br.readLine()) != null) { sb.append(line); } } finally { br.close(); } StringReader sr = new StringReader(sb.toString()); parser.parse(sr, new LinkbackCallback(), true); if (mStart != 0 && mEnd != 0 && mEnd > mStart) { mExcerpt = sb.toString().substring(mStart, mEnd); mExcerpt = Utilities.removeHTML(mExcerpt); if (mExcerpt.length() > mMaxExcerpt) { mExcerpt = mExcerpt.substring(0, mMaxExcerpt) + "..."; } } if (mTitle.startsWith(">") && mTitle.length() > 1) { mTitle = mTitle.substring(1); } } Code Sample 2: @Test public void shouldSetAlias() throws Exception { HttpResponse response = executePost("/yum/alias/snapshots/testAlias", new StringEntity(VERSION_1)); assertEquals(VERSION_1, EntityUtils.toString(response.getEntity())); assertEquals(VERSION_1, executeGet("/yum/alias/snapshots/testAlias")); response = executePost("/yum/alias/snapshots/testAlias", new StringEntity(VERSION_2)); assertEquals(VERSION_2, EntityUtils.toString(response.getEntity())); assertEquals(VERSION_2, executeGet("/yum/alias/snapshots/testAlias")); }
00
Code Sample 1: public static String getMD5(String in) { if (in == null) { return null; } try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(in.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xFF & hash[i]); if (hex.length() == 1) { hex = "0" + hex; } hexString.append(hex); } return hexString.toString(); } catch (Exception e) { Debug.logException(e); } return null; } Code Sample 2: protected String getPostRequestContent(String urlText, String postParam) throws Exception { URL url = new URL(urlText); HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); urlcon.setRequestMethod("POST"); urlcon.setUseCaches(false); urlcon.setDoOutput(true); PrintStream ps = new PrintStream(urlcon.getOutputStream()); ps.print(postParam); ps.close(); urlcon.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream())); String line = reader.readLine(); reader.close(); urlcon.disconnect(); return line; }
11
Code Sample 1: public void copy(File aSource, File aDestDir) throws IOException { FileInputStream myInFile = new FileInputStream(aSource); FileOutputStream myOutFile = new FileOutputStream(new File(aDestDir, aSource.getName())); FileChannel myIn = myInFile.getChannel(); FileChannel myOut = myOutFile.getChannel(); boolean end = false; while (true) { int myBytes = myIn.read(theBuffer); if (myBytes != -1) { theBuffer.flip(); myOut.write(theBuffer); theBuffer.clear(); } else break; } myIn.close(); myOut.close(); myInFile.close(); myOutFile.close(); long myEnd = System.currentTimeMillis(); } Code Sample 2: public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception { String attachmentName = request.getParameter("attachment"); String virtualWiki = getVirtualWiki(request); File uploadPath = getEnvironment().uploadPath(virtualWiki, attachmentName); response.reset(); response.setHeader("Content-Disposition", getEnvironment().getStringSetting(Environment.PROPERTY_ATTACHMENT_TYPE) + ";filename=" + attachmentName + ";"); int dotIndex = attachmentName.indexOf('.'); if (dotIndex >= 0 && dotIndex < attachmentName.length() - 1) { String extension = attachmentName.substring(attachmentName.lastIndexOf('.') + 1); logger.fine("Extension: " + extension); String mimetype = (String) getMimeByExtension().get(extension.toLowerCase()); logger.fine("MIME: " + mimetype); if (mimetype != null) { logger.fine("Setting content type to: " + mimetype); response.setContentType(mimetype); } } FileInputStream in = null; ServletOutputStream out = null; try { in = new FileInputStream(uploadPath); out = response.getOutputStream(); IOUtils.copy(in, out); out.flush(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
00
Code Sample 1: private static void compressZip(String source, String dest) throws Exception { File baseFolder = new File(source); if (baseFolder.exists()) { if (baseFolder.isDirectory()) { List<File> fileList = getSubFiles(new File(source)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest)); zos.setEncoding("GBK"); ZipEntry entry = null; byte[] buf = new byte[2048]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { File file = fileList.get(i); if (file.isDirectory()) { entry = new ZipEntry(getAbsFileName(source, file) + "/"); } else { entry = new ZipEntry(getAbsFileName(source, file)); } entry.setSize(file.length()); entry.setTime(file.lastModified()); zos.putNextEntry(entry); if (file.isFile()) { InputStream in = new BufferedInputStream(new FileInputStream(file)); while ((readLen = in.read(buf, 0, 1024)) != -1) { zos.write(buf, 0, readLen); } in.close(); } } zos.close(); } else { throw new Exception("Can not do this operation!."); } } else { baseFolder.mkdirs(); compressZip(source, dest); } } Code Sample 2: void testFileObject(JavaFileObject fo) throws Exception { URI uri = fo.toUri(); System.err.println("uri: " + uri); URLConnection urlconn = uri.toURL().openConnection(); if (urlconn instanceof JarURLConnection) { JarURLConnection jarconn = (JarURLConnection) urlconn; File f = new File(jarconn.getJarFile().getName()); foundJars.add(f.getName()); } try { byte[] uriData = read(urlconn.getInputStream()); byte[] foData = read(fo.openInputStream()); if (!Arrays.equals(uriData, foData)) { if (uriData.length != foData.length) throw new Exception("data size differs: uri data " + uriData.length + " bytes, fo data " + foData.length + " bytes"); for (int i = 0; i < uriData.length; i++) { if (uriData[i] != foData[i]) throw new Exception("unexpected data returned at offset " + i + ", uri data " + uriData[i] + ", fo data " + foData[i]); } throw new AssertionError("cannot find difference"); } } finally { if (urlconn instanceof JarURLConnection) { JarURLConnection jarconn = (JarURLConnection) urlconn; jarconn.getJarFile().close(); } } }
00
Code Sample 1: private static byte[] Md5f(String plainText) { byte[] ab = new byte[16]; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); ab = b; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ab; } Code Sample 2: public String retrieve(String url) { HttpGet getRequest = new HttpGet(url); try { HttpResponse getResponse = client.execute(getRequest); final int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url); return null; } HttpEntity getResponseEntity = getResponse.getEntity(); if (getResponseEntity != null) { return EntityUtils.toString(getResponseEntity); } } catch (IOException e) { getRequest.abort(); Log.w(getClass().getSimpleName(), "Error for URL " + url, e); } return null; }
00
Code Sample 1: private ArrayList<IdLocation> doGet(String identifier) throws IdLocatorException { String openurl = baseurl.toString() + "?url_ver=Z39.88-2004&rft_id=" + identifier; URL url; SRUSearchRetrieveResponse sru; try { url = new URL(openurl); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); int code = huc.getResponseCode(); if (code == 200) { sru = SRUSearchRetrieveResponse.read(huc.getInputStream()); } else throw new IdLocatorException("cannot get " + url.toString()); } catch (MalformedURLException e) { throw new IdLocatorException("A MalformedURLException occurred for " + openurl); } catch (IOException e) { throw new IdLocatorException("An IOException occurred attempting to connect to " + openurl); } catch (SRUException e) { throw new IdLocatorException("An SRUException occurred attempting to parse the response"); } ArrayList<IdLocation> ids = new ArrayList<IdLocation>(); for (SRUDC dc : sru.getRecords()) { IdLocation id = new IdLocation(); id.setId(dc.getKeys(SRUDC.Key.IDENTIFIER).firstElement()); id.setRepo(dc.getKeys(SRUDC.Key.SOURCE).firstElement()); id.setDate(dc.getKeys(SRUDC.Key.DATE).firstElement()); ids.add(id); } Collections.sort(ids); return ids; } Code Sample 2: public void openFtpConnection(String workingDirectory) throws RQLException { try { ftpClient = new FTPClient(); ftpClient.connect(server); ftpClient.login(user, password); ftpClient.changeWorkingDirectory(workingDirectory); } catch (IOException ioex) { throw new RQLException("FTP client could not be created. Please check attributes given in constructor.", ioex); } }
00
Code Sample 1: public void sortPlayersTurn() { Token tempT = new Token(); Player tempP = new Player("test name", tempT); int tempN = 0; boolean exchangeMade = true; for (int i = 0; i < playerNum - 1 && exchangeMade; i++) { exchangeMade = false; for (int j = 0; j < playerNum - 1 - i; j++) { if (diceSum[j] < diceSum[j + 1]) { tempP = players[j]; tempN = diceSum[j]; players[j] = players[j + 1]; diceSum[j] = diceSum[j + 1]; players[j + 1] = tempP; diceSum[j + 1] = tempN; exchangeMade = true; } } } } Code Sample 2: static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: private boolean verifyAppId(String appid) { try { String urlstr = "http://" + appid + ".appspot.com"; URL url = new URL(urlstr); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { buf.append(line); } reader.close(); return buf.toString().contains("hyk-proxy"); } catch (Exception e) { } return false; } Code Sample 2: public static void fileCopy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: public static void shakeSort(int[] a) { if (a == null) { throw new IllegalArgumentException("Null-pointed array"); } int k = 0; int left = 0; int right = a.length - 1; while (right - left > 0) { k = 0; for (int i = 0; i <= right - 1; i++) { if (a[i] > a[i + 1]) { k = i; int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } right = k; k = a.length - 1; for (int i = left; i <= right - 1; i++) { if (a[i] > a[i + 1]) { k = i; int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } left = k; } } Code Sample 2: public void insertArchiveEntries(ArchiveEntry entries[]) throws WeatherMonitorException { String sql = null; try { Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rslt = null; con.setAutoCommit(false); for (int i = 0; i < entries.length; i++) { if (!sanityCheck(entries[i])) { } else { sql = getSelectSql(entries[i]); rslt = stmt.executeQuery(sql); if (rslt.next()) { if (rslt.getInt(1) == 0) { sql = getInsertSql(entries[i]); if (stmt.executeUpdate(sql) != 1) { con.rollback(); System.out.println("rolling back sql"); throw new WeatherMonitorException("exception on insert"); } } } } } con.commit(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new WeatherMonitorException(e.getMessage()); } }
00
Code Sample 1: @Override public void alterar(QuestaoMultiplaEscolha q) throws Exception { PreparedStatement stmt = null; String sql = "UPDATE questao SET id_disciplina=?, enunciado=?, grau_dificuldade=? WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getDisciplina().getIdDisciplina()); stmt.setString(2, q.getEnunciado()); stmt.setString(3, q.getDificuldade().name()); stmt.setInt(4, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); alterarQuestaoMultiplaEscolha(q); } catch (SQLException e) { conexao.rollback(); throw e; } } Code Sample 2: public static void copy(File from, File to, CopyMode mode) throws IOException { if (!from.exists()) { IllegalArgumentException e = new IllegalArgumentException("Source doesn't exist: " + from.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (from.isFile()) { if (!to.canWrite()) { IllegalArgumentException e = new IllegalArgumentException("Cannot write to target location: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } } if (to.exists()) { if ((mode.val & CopyMode.OverwriteFile.val) != CopyMode.OverwriteFile.val) { IllegalArgumentException e = new IllegalArgumentException("Target already exists: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (to.isDirectory()) { if ((mode.val & CopyMode.OverwriteFolder.val) != CopyMode.OverwriteFolder.val) { IllegalArgumentException e = new IllegalArgumentException("Target is a folder: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } else to.delete(); } } if (from.isFile()) { FileChannel in = new FileInputStream(from).getChannel(); FileLock inLock = in.lock(); FileChannel out = new FileOutputStream(to).getChannel(); FileLock outLock = out.lock(); try { in.transferTo(0, (int) in.size(), out); } finally { inLock.release(); outLock.release(); in.close(); out.close(); } } else { to.mkdirs(); File[] contents = to.listFiles(); for (File file : contents) { File newTo = new File(to.getCanonicalPath() + "/" + file.getName()); copy(file, newTo, mode); } } }
00
Code Sample 1: public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadFileForm vo = (UploadFileForm) form; String review = request.getParameter("review"); String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String inforId = request.getParameter("inforId"); request.setAttribute("id", inforId); String str_postFIX = ""; int i_p = 0; if (null == review) { FormFile file = vo.getFile(); if (file != null) { String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); String strAppend = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); if (file.getFileSize() != 0) { file.getInputStream(); String name = file.getFileName(); i_p = file.getFileName().lastIndexOf("."); str_postFIX = file.getFileName().substring(i_p, file.getFileName().length()); String fullPath = realpath + "attach/" + strAppend + str_postFIX; t_attach attach = new t_attach(); attach.setAttach_fullname(fullPath); attach.setAttach_name(name); attach.setInfor_id(Integer.parseInt(inforId)); attach.setInsert_day(new Date()); attach.setUpdate_day(new Date()); t_attach_EditMap attachEdit = new t_attach_EditMap(); attachEdit.add(attach); File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(file.getInputStream(), out); out.close(); } } request.setAttribute("operating-status", "�����ɹ�! ��ӭ����ʹ�á�"); return "editsave"; } else { String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); FormFile file = vo.getFile(); FormFile file2 = vo.getFile2(); FormFile file3 = vo.getFile3(); t_infor_review newreview = new t_infor_review(); String content = request.getParameter("content"); newreview.setContent(content); if (null != inforId) newreview.setInfor_id(Integer.parseInt(inforId)); newreview.setInsert_day(new Date()); UserDetails user = LoginUtils.getLoginUser(request); newreview.setCreate_name(user.getUsercode()); if (null != file.getFileName() && !"".equals(file.getFileName())) { newreview.setAttachname1(file.getFileName()); String strAppend1 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); i_p = file.getFileName().lastIndexOf("."); str_postFIX = file.getFileName().substring(i_p, file.getFileName().length()); newreview.setAttachfullname1(realpath + "attach/" + strAppend1 + str_postFIX); saveFile(file.getInputStream(), realpath + "attach/" + strAppend1 + str_postFIX); } if (null != file2.getFileName() && !"".equals(file2.getFileName())) { newreview.setAttachname2(file2.getFileName()); String strAppend2 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); i_p = file2.getFileName().lastIndexOf("."); str_postFIX = file2.getFileName().substring(i_p, file2.getFileName().length()); newreview.setAttachfullname2(realpath + "attach/" + strAppend2 + str_postFIX); saveFile(file2.getInputStream(), realpath + "attach/" + strAppend2 + str_postFIX); } if (null != file3.getFileName() && !"".equals(file3.getFileName())) { newreview.setAttachname3(file3.getFileName()); String strAppend3 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); i_p = file3.getFileName().lastIndexOf("."); str_postFIX = file3.getFileName().substring(i_p, file3.getFileName().length()); newreview.setAttachfullname3(realpath + "attach/" + strAppend3 + str_postFIX); saveFile(file3.getInputStream(), realpath + "attach/" + strAppend3 + str_postFIX); } t_infor_review_EditMap reviewEdit = new t_infor_review_EditMap(); reviewEdit.add(newreview); request.setAttribute("review", "1"); return "aftersave"; } } Code Sample 2: public static String SHA1(String text) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes()); byte byteData[] = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } StringBuilder hexString = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
00
Code Sample 1: public void testCopyFolderContents() throws IOException { log.info("Running: testCopyFolderContents()"); IOUtils.copyFolderContents(srcFolderName, destFolderName); Assert.assertTrue(destFile1.exists() && destFile1.isFile()); Assert.assertTrue(destFile2.exists() && destFile2.isFile()); Assert.assertTrue(destFile3.exists() && destFile3.isFile()); } Code Sample 2: protected boolean createFile(final IProject project, final IProgressMonitor monitor, final Template templ, final String sourceUrl, final String destFile, final boolean isBinary) throws IOException, CoreException { URL url; url = new URL(sourceUrl); final URLConnection con = url.openConnection(); final IFile f = project.getFile(replaceVariables(templ.getVariables(), destFile)); createParents(f, monitor); if (isBinary) { f.create(con.getInputStream(), true, monitor); } else { final StringWriter sw = new StringWriter(); final InputStream in = con.getInputStream(); for (; ; ) { final int c = in.read(); if (-1 == c) { break; } sw.write(c); } sw.close(); final String fileText = replaceVariables(templ.getVariables(), sw.toString()); f.create(new ByteArrayInputStream(fileText.getBytes()), true, monitor); } return true; }
11
Code Sample 1: public void copyFile(String oldPath, String newPath) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } inStream.close(); fs.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static File copyFile(File srcFile, File destFolder, FileCopyListener copyListener) { File dest = new File(destFolder, srcFile.getName()); try { FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; long totalCopiedSize = 0; long totalSize = srcFile.length(); boolean canceled = false; if (copyListener == null) { while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } } else { while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); if (!copyListener.updateCheck(readLength, totalSize)) { canceled = true; break; } } } in.close(); out.close(); if (canceled) { dest.delete(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
00
Code Sample 1: public File extractID3v2TagDataIntoFile(File outputFile) throws TagNotFoundException, IOException { int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte(); if (startByte >= 0) { FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer bb = ByteBuffer.allocate(startByte); fc.read(bb); FileOutputStream out = new FileOutputStream(outputFile); out.write(bb.array()); out.close(); fc.close(); fis.close(); return outputFile; } throw new TagNotFoundException("There is no ID3v2Tag data in this file"); } Code Sample 2: public void callUpdate() { LOGGER.debug("Checking for Updates"); new Thread() { @Override public void run() { String lastVersion = null; try { URL projectSite = new URL("http://code.google.com/p/g15lastfm/"); URLConnection urlC = projectSite.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlC.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("<strong>Current version:")) { lastVersion = inputLine; break; } } in.close(); if (lastVersion != null && lastVersion.length() > 0) { lastVersion = lastVersion.substring(lastVersion.indexOf("Current version:") + 16); lastVersion = lastVersion.substring(0, lastVersion.indexOf("</strong>")).trim(); LOGGER.debug("last Version=" + lastVersion); } if (!lastVersion.equals(G15LastfmPlayer.getVersion())) LOGGER.debug("Not necessary to update"); else { LOGGER.debug("New update found!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (JOptionPane.showConfirmDialog(null, "New version of G15Lastfm is available to download!", "New Update for G15Lastfm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { LOGGER.debug("User choose to update, opening browser."); Desktop desktop = Desktop.getDesktop(); try { desktop.browse(new URI("http://code.google.com/p/g15lastfm/")); } catch (IOException e) { LOGGER.debug(e); } catch (URISyntaxException e) { LOGGER.debug(e); } } else { LOGGER.debug("User choose to not update."); } } }); } } catch (Exception e) { LOGGER.debug(e); } } }.start(); }
00
Code Sample 1: public static void refresh() { URL[] urls = Constants.Wiki2xhtml.getUpdateURLs(); content.setLength(0); InputStream is = null; BufferedReader br = null; for (int i = 0; i < urls.length; i++) { try { is = urls[i].openStream(); br = new BufferedReader(new InputStreamReader(is)); String s; while ((s = br.readLine()) != null) { if (s.length() == 0) continue; if (s.startsWith("--")) break; content.append(s + '\n'); } is.close(); break; } catch (FileNotFoundException e) { System.err.println("File not found: " + urls[i].getHost() + urls[i].getPath()); } catch (IOException e) { System.err.println("Error: " + e.getMessage()); } } } Code Sample 2: private void readFromObjectInput(String filename) { try { URL url = new URL(getCodeBase(), filename); InputStream stream = url.openStream(); ObjectInput input = new ObjectInputStream(stream); fDrawing.release(); fDrawing = (Drawing) input.readObject(); view().setDrawing(fDrawing); } catch (IOException e) { initDrawing(); showStatus("Error: " + e); } catch (ClassNotFoundException e) { initDrawing(); showStatus("Class not found: " + e); } }
11
Code Sample 1: private void handleFile(File file, HttpServletRequest request, HttpServletResponse response) throws Exception { String filename = file.getName(); long filesize = file.length(); String mimeType = getMimeType(filename); response.setContentType(mimeType); if (filesize > getDownloadThreshhold()) { response.setHeader("Content-Disposition", "attachment; filename=" + filename); } response.setContentLength((int) filesize); ServletOutputStream out = response.getOutputStream(); IOUtils.copy(new FileInputStream(file), out); out.flush(); } Code Sample 2: public void convert(CSVReader reader, Writer writer, int nbTotalRows) throws IOException, InterruptedException { Validate.notNull(reader, "CSVReader"); Validate.notNull(writer, "Writer"); Writer bufferedWriter = new BufferedWriter(writer); File fileForColsDef = createTempFileForCss(); BufferedWriter colsDefWriter = new BufferedWriter(new FileWriter(fileForColsDef)); File fileForTable = createTempFileForTable(); BufferedWriter tableWriter = new BufferedWriter(new FileWriter(fileForTable)); try { int currentRow = 0; String[] nextLine = reader.readNext(); if (nextLine != null) { int[] colsCharCount = new int[nextLine.length]; writeTableRowHeader(tableWriter, nextLine); while ((nextLine = reader.readNext()) != null) { currentRow++; if (progress != null) { float percent = ((float) currentRow / (float) nbTotalRows) * 100f; progress.updateProgress(ConvertionStepEnum.PROCESSING_ROWS, percent); } writeTableRow(tableWriter, nextLine, colsCharCount); } writeTableStart(colsDefWriter, colsCharCount); writeColsDefinitions(colsDefWriter, colsCharCount); } writeConverterInfos(bufferedWriter); writeTableEnd(tableWriter); flushAndClose(tableWriter); flushAndClose(colsDefWriter); BufferedReader colsDefReader = new BufferedReader(new FileReader(fileForColsDef)); BufferedReader tableReader = new BufferedReader(new FileReader(fileForTable)); mergeFiles(bufferedWriter, colsDefReader, tableReader); } finally { closeQuietly(tableWriter); closeQuietly(colsDefWriter); fileForTable.delete(); fileForColsDef.delete(); } }
11
Code Sample 1: public long add(T t) throws BaseException { Connection conn = null; PreparedStatement pstmt = null; long result = -1L; boolean flag = false; try { conn = getConnection(); if (conn != null) { flag = true; } else { conn = ConnectionManager.getConn(getStrConnection()); conn.setAutoCommit(false); } pstmt = getAdd(conn, t, this.getTableName()); pstmt.executeUpdate(); result = t.getId(); } catch (SQLException e) { try { if (!flag) { conn.rollback(); } } catch (Exception ex) { log.error("add(T " + t.toString() + ")回滚出错,错误信息:" + ex.getMessage()); } log.error("add(T " + t.toString() + ")方法出错:" + e.getMessage()); } catch (BaseException e) { throw e; } finally { try { if (!flag) { conn.setAutoCommit(true); } } catch (Exception e) { log.error("add(T " + t.toString() + ")方法设置自动提交出错,信息为:" + e.getMessage()); } ConnectionManager.closePreparedStatement(pstmt); if (!flag) { ConnectionManager.closeConn(conn); } } return result; } Code Sample 2: public int create(BusinessObject o) throws DAOException { int insert = 0; int id = 0; Contact contact = (Contact) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_CONTACT")); pst.setString(1, contact.getName()); pst.setString(2, contact.getFirstname()); pst.setString(3, contact.getPhone()); pst.setString(4, contact.getEmail()); if (contact.getAccount() == 0) { pst.setNull(5, java.sql.Types.INTEGER); } else { pst.setInt(5, contact.getAccount()); } insert = pst.executeUpdate(); if (insert <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (insert > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select max(id) from contact"); rs.next(); id = rs.getInt(1); connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return id; }
11
Code Sample 1: private void copy(File from, File to) throws IOException { InputStream in = new FileInputStream(from); OutputStream out = new FileOutputStream(to); byte[] line = new byte[16384]; int bytes = -1; while ((bytes = in.read(line)) != -1) out.write(line, 0, bytes); in.close(); out.close(); } Code Sample 2: public void setTableBraille(String tableBraille, boolean sys) { fiConf.setProperty(OptNames.fi_braille_table, tableBraille); fiConf.setProperty(OptNames.fi_is_sys_braille_table, Boolean.toString(sys)); FileChannel in = null; FileChannel out = null; try { String fichTable; if (!(tableBraille.endsWith(".ent"))) { tableBraille = tableBraille + ".ent"; } if (sys) { fichTable = ConfigNat.getInstallFolder() + "xsl/tablesBraille/" + tableBraille; } else { fichTable = ConfigNat.getUserBrailleTableFolder() + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(getUserBrailleTableFolder() + "Brltab.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } try { String fichTable; if (sys) { fichTable = ConfigNat.getInstallFolder() + "/xsl/tablesEmbosseuse/" + tableBraille; } else { fichTable = ConfigNat.getUserEmbossTableFolder() + "/" + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(ConfigNat.getUserTempFolder() + "Table_pour_chaines.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static void downloadFile(HttpServletResponse response, String file) throws IOException { response.setContentType(FileUtils.getContentType(file)); response.setContentLength(FileUtils.getContentLength(file)); response.setHeader("Content-type", ResponseUtils.DOWNLOAD_CONTENT_TYPE); response.setHeader("Content-Disposition", "attachment; filename=\"" + FileUtils.getFileName(file) + "\""); response.setHeader("Content-Length", Integer.toString(FileUtils.getContentLength(file))); InputStream input = new FileInputStream(file); OutputStream output = response.getOutputStream(); IOUtils.copy(input, output, true); } Code Sample 2: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } long time = System.currentTimeMillis(); FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size && continueWriting(pos, size)) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); } } finally { output.close(); IOUtils.closeQuietly(fos); input.close(); IOUtils.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { if (DiskManager.isLocked()) throw new IOException("Copy stopped since VtM was working"); else throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } else { time = System.currentTimeMillis() - time; long speed = (destFile.length() / time) / 1000; DiskManager.addDiskSpeed(speed); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
11
Code Sample 1: public synchronized String encrypt(final String pPassword) throws NoSuchAlgorithmException, UnsupportedEncodingException { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(pPassword.getBytes("UTF-8")); final byte raw[] = md.digest(); return BASE64Encoder.encodeBuffer(raw); } Code Sample 2: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { System.err.println("Failed to load the SHA-1 MessageDigest. " + "Jive will be unable to function normally."); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); }
00
Code Sample 1: private String getSearchResults(String id) { try { final URL url = new URL("http://www.jaap.nl/api/jaapAPI.do?clientId=iPhone&limit=5&request=details&id=" + id + "&format=JSON&field=street_nr&field=zip&field=city&field=price&field=thumb&field=since&field=houseType&field=area&field=rooms&field=id"); final StringBuilder builder = new StringBuilder(); final BufferedReader rd = new BufferedReader(new InputStreamReader(url.openStream())); String s = ""; while ((s = rd.readLine()) != null) { builder.append(s); } rd.close(); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } Code Sample 2: protected String getLibJSCode() throws IOException { if (cachedLibJSCode == null) { InputStream is = getClass().getResourceAsStream(JS_LIB_FILE); StringWriter output = new StringWriter(); IOUtils.copy(is, output); cachedLibJSCode = output.toString(); } return cachedLibJSCode; }
00
Code Sample 1: public void doRecurringPayment(Subscription subscription) { int amount = Math.round(subscription.getTotalCostWithDiscounts() * 100.0f); String currency = subscription.getCurrency(); String aliasCC = subscription.getAliasCC(); String expm = subscription.getLastCardExpm(); String expy = subscription.getLastCardExpy(); String subscriptionId = String.valueOf(subscription.getSubscriptionId()); StringBuffer xmlSB = new StringBuffer(""); xmlSB.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); xmlSB.append("<authorizationService version=\"1\">\n"); xmlSB.append(" <body merchantId=\"" + getMerchantId() + "\" testOnly=\"" + getTestOnly() + "\">\n"); xmlSB.append(" <transaction refno=\"" + REF_NO + "\">\n"); xmlSB.append(" <request>\n"); xmlSB.append(" <amount>" + amount + "</amount>\n"); xmlSB.append(" <currency>" + currency + "</currency>\n"); xmlSB.append(" <aliasCC>" + aliasCC + "</aliasCC>\n"); xmlSB.append(" <expm>" + expm + "</expm>\n"); xmlSB.append(" <expy>" + expy + "</expy>\n"); xmlSB.append(" <subscriptionId>" + subscriptionId + "</subscriptionId>\n"); xmlSB.append(" </request>\n"); xmlSB.append(" </transaction>\n"); xmlSB.append(" </body>\n"); xmlSB.append("</authorizationService>\n"); String xmlS = xmlSB.toString(); try { java.net.URL murl = new java.net.URL(getRecurringPaymentUrl()); java.net.HttpURLConnection mcon = (java.net.HttpURLConnection) murl.openConnection(); mcon.setRequestMethod("POST"); mcon.setRequestProperty("encoding", "UTF-8"); mcon.setRequestProperty("Content-Type", "text/xml"); mcon.setRequestProperty("Content-length", String.valueOf(xmlS.length())); mcon.setDoOutput(true); java.io.OutputStream outs = mcon.getOutputStream(); outs.write(xmlS.getBytes("UTF-8")); outs.close(); java.io.BufferedReader inps = new java.io.BufferedReader(new java.io.InputStreamReader(mcon.getInputStream())); StringBuffer respSB = new StringBuffer(""); String s = null; while ((s = inps.readLine()) != null) { respSB.append(s); } inps.close(); String respXML = respSB.toString(); processReccurentPaymentResponce(respXML); } catch (Exception ex) { throw new SecurusException(ex); } } Code Sample 2: public Object construct() { Object result; try { if (getParameter("data") != null && getParameter("data").length() > 0) { NanoXMLDOMInput domi = new NanoXMLDOMInput(new UMLFigureFactory(), new StringReader(getParameter("data"))); result = domi.readObject(0); } else if (getParameter("datafile") != null) { InputStream in = null; try { URL url = new URL(getDocumentBase(), getParameter("datafile")); in = url.openConnection().getInputStream(); NanoXMLDOMInput domi = new NanoXMLDOMInput(new UMLFigureFactory(), in); result = domi.readObject(0); } finally { if (in != null) in.close(); } } else { result = null; } } catch (Throwable t) { result = t; } return result; }
00
Code Sample 1: protected URLConnection openURLConnection() throws IOException { final String locator = getMediaLocator(); if (locator == null) { return null; } final URL url; try { url = new URL(locator); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } final URLConnection connection = url.openConnection(); connection.connect(); return connection; } Code Sample 2: @Override public DaeScene loadScene(URL url) throws IOException, IncorrectFormatException, ParsingErrorException { NullArgumentException.check(url); boolean baseURLWasNull = setBaseURLFromModelURL(url); DaeScene scene = loadScene(url.openStream()); if (baseURLWasNull) { popBaseURL(); } return (scene); }
00
Code Sample 1: public void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public void calculate() throws FormatException, java.io.IOException { if (input == null) throw new IllegalStateException("FastaChecksummer input not set"); contigHashes = new HashMap<String, ChecksumEntry>(); String currentContig = null; java.security.MessageDigest hasher = null; try { hasher = java.security.MessageDigest.getInstance(checksumAlgorithm); } catch (java.security.NoSuchAlgorithmException e) { throw new RuntimeException("Unexpected NoSuchAlgorithmException when asking for " + checksumAlgorithm + " algorithm"); } String line = input.readLine(); if (line == null) throw new FormatException("empty Fasta"); try { while (line != null) { if (line.startsWith(">")) { if (currentContig != null) { String cs = new String(Hex.encodeHex(hasher.digest())); contigHashes.put(currentContig, new ChecksumEntry(currentContig, cs)); } Matcher m = ContigNamePattern.matcher(line); if (m.matches()) { currentContig = m.group(1); hasher.reset(); } else throw new FormatException("Unexpected contig name format: " + line); } else { if (currentContig == null) throw new FormatException("Sequence outside any fasta record (header is missing). Line: " + line); else hasher.update(line.getBytes("US-ASCII")); } line = input.readLine(); } if (currentContig != null) { String cs = new String(Hex.encodeHex(hasher.digest())); contigHashes.put(currentContig, new ChecksumEntry(currentContig, cs)); } } catch (java.io.UnsupportedEncodingException e) { throw new RuntimeException("Unexpected UnsupportedEncodingException! Line: " + line); } }
00
Code Sample 1: public static void readProperties() throws IOException { URL url1 = cl.getResource("conf/soapuddi.config"); Properties props = new Properties(); if (url1 == null) throw new IOException("soapuddi.config not found"); props.load(url1.openStream()); className = props.getProperty("Class"); url = props.getProperty("URL"); user = props.getProperty("user"); password = props.getProperty("passwd"); operatorName = props.getProperty("operator"); authorisedName = props.getProperty("authorisedName"); isUpdated = true; } Code Sample 2: public static void readDefault() { ClassLoader l = Skeleton.class.getClassLoader(); URL url; if (l != null) { url = l.getResource(DEFAULT_LOC); } else { url = ClassLoader.getSystemResource(DEFAULT_LOC); } if (url == null) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } try { InputStreamReader reader = new InputStreamReader(url.openStream()); readSkel(new BufferedReader(reader)); } catch (IOException e) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } }
00
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static String getMD5(String s) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(s.getBytes(), 0, s.length()); String result = new BigInteger(1, m.digest()).toString(16); while (result.length() < 32) { result = '0' + result; } return result; } catch (NoSuchAlgorithmException ex) { return null; } }
11
Code Sample 1: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private InputStream getStreamFromUrl(URL url, String notFoundMessage) throws ApolloAdapterException { InputStream stream = null; if (url == null) { String message = "Couldn't find url for " + filename; logger.error(message); throw new ApolloAdapterException(message); } if (url != null) { try { stream = url.openStream(); } catch (IOException e) { logger.error(e.getMessage(), e); stream = null; throw new ApolloAdapterException(e); } } return stream; } Code Sample 2: public static void zipFile(String file, String entry) throws IOException { FileInputStream in = new FileInputStream(file); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file + ".zip")); out.putNextEntry(new ZipEntry(entry)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.closeEntry(); out.close(); File fin = new File(file); fin.delete(); }
00
Code Sample 1: void search(String query, String display) { try { String safeUrl; try { safeUrl = baseUrl + URLEncoder.encode(query, "UTF-8"); } catch (UnsupportedEncodingException ex) { safeUrl = baseUrl + query; Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } URL url_connection = new URL(safeUrl); url_connection.openConnection(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(url_connection.openStream()); Vector<SoundEntry> entries = new Vector<SoundEntry>(); Vector<String> path = new Vector<String>(); path.add("Results"); for (Hashtable<String, String> field : DocumentManager.getSubTable(document, path, "Entry")) { entries.add(new SoundEntry(field)); } int index; ButtonTabComponent btc = new ButtonTabComponent(tpnResults); btc.setInheritsPopupMenu(true); if (entries.isEmpty()) { JLabel msg = new JLabel("No results found"); tpnResults.add(display, msg); index = tpnResults.indexOfComponent(msg); } else { Enumeration<String> iter = entries.firstElement().fields.keys(); while (iter.hasMoreElements()) { String field = iter.nextElement(); if (!header.contains(field)) { header.addDefaultField(field); } } JTable result = new JTable(); Vector<String> fieldNames = header.getShownNames(); DefaultTableModel model = new DefaultTableModel(fieldNames, 0); for (SoundEntry entry : entries) { model.addRow(entry.getShownFields(header.getShownNames())); } result.setModel(model); result.setColumnSelectionAllowed(false); result.setSelectionMode(0); result.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { ((JTable) e.getSource()).getComponentAt(e.getPoint()); int row = ((JTable) e.getSource()).rowAtPoint(e.getPoint()); SoundEntry entry = ((ButtonTabComponent) tpnResults.getTabComponentAt(tpnResults.getSelectedIndex())).records.get(row); String file = entry.fields.get("FileName"); String title = entry.fields.get("Title"); if (file != null && !file.isEmpty()) { try { AudioSource src = new AudioSource(new URL(file), title); src.attachAudioStateListener(new AudioStateListener() { public void AudioStateReceived(AudioStateEvent event) { if (event.getAudioState() != AudioStateEvent.AudioState.CLOSED && event.getAudioState() != AudioStateEvent.AudioState.CLOSING) { llblStatus.setText(event.getAudioState() + ": " + ((AudioSource) event.getSource()).getTitle().toString()); } } }); audioPlayer.open(src); } catch (Exception j) { } } } }); JScrollPane scrollPane = new JScrollPane(result); tpnResults.add(display, scrollPane); index = tpnResults.indexOfComponent(scrollPane); btc.records = entries; } tpnResults.setTabComponentAt(index, btc); tpnResults.setSelectedIndex(index); } catch (SAXException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } catch (MalformedURLException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } } Code Sample 2: public ProgramSymbol deleteProgramSymbol(int id) throws AdaptationException { ProgramSymbol programSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramSymbols " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete program symbol failed."; log.error(msg); throw new AdaptationException(msg); } programSymbol = getProgramSymbol(resultSet); query = "DELETE FROM ProgramSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProgramSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return programSymbol; }
11
Code Sample 1: private void copy(File source, File target) throws IOException { FileChannel in = (new FileInputStream(source)).getChannel(); FileChannel out = (new FileOutputStream(target)).getChannel(); in.transferTo(0, source.length(), out); in.close(); out.close(); } Code Sample 2: public static String sendScripts(Session session) { Channel channel = null; String tempDirectory = ""; Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "Start sendScripts."); try { { channel = session.openChannel("exec"); final String command = "mktemp -d /tmp/scipionXXXXXXXX"; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); tempDirectory = result[1]; tempDirectory = tempDirectory.replaceAll("\n", ""); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + tempDirectory); IOUtils.closeQuietly(in); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream rsyncHelperContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_HELPER_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(rsyncHelperContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream askPassContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_ASKPASS_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(askPassContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } } catch (IOException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } catch (JSchException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "End sendScripts."); return tempDirectory; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private File Gzip(File f) throws IOException { if (f == null || !f.exists()) return null; File dest_dir = f.getParentFile(); String dest_filename = f.getName() + ".gz"; File zipfile = new File(dest_dir, dest_filename); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(zipfile)); FileInputStream in = new FileInputStream(f); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.finish(); try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } try { f.delete(); } catch (Exception e) { } return zipfile; }
11
Code Sample 1: public static String getSHADigest(String input) { if (input == null) return null; MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (java.security.NoSuchAlgorithmException nsae) { throw new RuntimeException(nsae); } if (sha == null) throw new RuntimeException("No message digest"); sha.update(input.getBytes()); byte[] data = sha.digest(); StringBuffer buf = new StringBuffer(data.length * 2); for (int i = 0; i < data.length; i++) { int value = data[i] & 0xff; buf.append(hexDigit(value >> 4)); buf.append(hexDigit(value)); } return buf.toString(); } Code Sample 2: public static byte[] hash(final byte[] saltBefore, final String content, final byte[] saltAfter, final int repeatedHashingCount) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (content == null) return null; final MessageDigest digest = MessageDigest.getInstance(DIGEST); if (digestLength == -1) digestLength = digest.getDigestLength(); for (int i = 0; i < repeatedHashingCount; i++) { if (i > 0) digest.update(digest.digest()); digest.update(saltBefore); digest.update(content.getBytes(WebCastellumParameter.DEFAULT_CHARACTER_ENCODING.getValue())); digest.update(saltAfter); } return digest.digest(); }
00
Code Sample 1: public static void main(String[] args) { FTPClient client = new FTPClient(); FileInputStream fis = null; try { client.connect("192.168.1.10"); client.login("a", "123456"); String filename = "D:\\DHTH5CLT\\HK3\\Ung dung phan tan\\FTP_JAVA\\FTP_DETAI\\FTP\\src\\DemoFTP\\filename\\5s.txt"; fis = new FileInputStream(filename); client.storeFile(filename, fis); client.logout(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } Code Sample 2: private static synchronized void find(String name) throws SAXException, IOException { if (c_cache.containsKey(name)) return; CustomHandler handler = null; URL url = null; String validatorFiles = (String) Config.getProperty(Config.PROP_RULES_ENGINE_VALIDATORS_URL_LIST, XML_FILE); for (StringTokenizer strtknzr = new StringTokenizer(validatorFiles, ","); strtknzr.hasMoreTokens(); ) { String validatorFile = strtknzr.nextToken(); try { url = URLHelper.newExtendedURL(validatorFile); } catch (MalformedURLException e) { url = null; } if (url == null) throw new FileNotFoundException("File not found - " + validatorFile); try { handler = new CustomHandler(name); XMLReader reader = XMLReaderFactory.createXMLReader(PARSER_NAME); reader.setContentHandler(handler); reader.setEntityResolver(new DefaultEntityResolver()); reader.setErrorHandler(new DefaultErrorHandler()); reader.parse(new InputSource(url.openStream())); } catch (SAXException e) { if (SUCCESS_MESSAGE.equals(e.getMessage()) && handler != null) break; else throw e; } catch (IOException e) { throw e; } if (handler.getFieldValidatorMetaData() != null) break; } c_cache.put(name, handler != null ? handler.getFieldValidatorMetaData() : null); }
11
Code Sample 1: public void readPersistentProperties() { try { String file = System.getProperty("user.home") + System.getProperty("file.separator") + ".das2rc"; File f = new File(file); if (f.canRead()) { try { InputStream in = new FileInputStream(f); load(in); in.close(); } catch (IOException e) { e.printStackTrace(); org.das2.util.DasExceptionHandler.handle(e); } } else { if (!f.exists() && f.canWrite()) { try { OutputStream out = new FileOutputStream(f); store(out, ""); out.close(); } catch (IOException e) { e.printStackTrace(); org.das2.util.DasExceptionHandler.handle(e); } } else { System.err.println("Unable to read or write " + file + ". Using defaults."); } } } catch (SecurityException ex) { ex.printStackTrace(); } } Code Sample 2: private void createWar() throws IOException, XMLStreamException { String appName = this.fileout.getName(); int i = appName.indexOf("."); if (i != -1) appName = appName.substring(0, i); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(this.fileout)); { ZipEntry entry = new ZipEntry("WEB-INF/web.xml"); zout.putNextEntry(entry); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter w = factory.createXMLStreamWriter(zout, "ASCII"); w.writeStartDocument("ASCII", "1.0"); w.writeStartElement("web-app"); w.writeAttribute("xsi", XSI, "schemaLocation", "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml /ns/javaee/web-app_2_5.xsd"); w.writeAttribute("version", "2.5"); w.writeAttribute("xmlns", J2EE); w.writeAttribute("xmlns:xsi", XSI); w.writeStartElement("description"); w.writeCharacters("Site maintenance for " + appName); w.writeEndElement(); w.writeStartElement("display-name"); w.writeCharacters(appName); w.writeEndElement(); w.writeStartElement("servlet"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("jsp-file"); w.writeCharacters("/WEB-INF/jsp/down.jsp"); w.writeEndElement(); w.writeEndElement(); w.writeStartElement("servlet-mapping"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("url-pattern"); w.writeCharacters("/*"); w.writeEndElement(); w.writeEndElement(); w.writeEndElement(); w.writeEndDocument(); w.flush(); zout.closeEntry(); } { ZipEntry entry = new ZipEntry("WEB-INF/jsp/down.jsp"); zout.putNextEntry(entry); PrintWriter w = new PrintWriter(zout); if (this.messageFile != null) { IOUtils.copyTo(new FileReader(this.messageFile), w); } else if (this.messageString != null) { w.print("<html><body>" + this.messageString + "</body></html>"); } else { w.print("<html><body><div style='text-align:center;font-size:500%;'>Oh No !<br/><b>" + appName + "</b><br/>is down for maintenance!</div></body></html>"); } w.flush(); zout.closeEntry(); } zout.finish(); zout.flush(); zout.close(); }
00
Code Sample 1: public static void bubbleSort(int[] a) { for (int i = a.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (a[j] > a[j + 1]) { int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } } Code Sample 2: private String choosePivotVertex() throws ProcessorExecutionException { String result = null; Graph src; Graph dest; Path tmpDir; System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex"); src = new Graph(Graph.defaultGraph()); src.setPath(_curr_path); dest = new Graph(Graph.defaultGraph()); try { tmpDir = _dirMgr.getTempDir(); } catch (IOException e) { throw new ProcessorExecutionException(e); } dest.setPath(tmpDir); GraphAlgorithm choose_pivot = new PivotChoose(); choose_pivot.setConf(context); choose_pivot.setSource(src); choose_pivot.setDestination(dest); choose_pivot.setMapperNum(getMapperNum()); choose_pivot.setReducerNum(getReducerNum()); choose_pivot.execute(); try { Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("##########> Chosen pivot id = " + result); } catch (IOException e) { throw new ProcessorExecutionException(e); } return result; }
00
Code Sample 1: public static boolean copy(File source, File dest) { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } Code Sample 2: public static String generateHashSE(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException, DigestException { MessageDigest md; md = MessageDigest.getInstance("SHA-256"); byte[] hashSHA256 = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md.digest(hashSHA256, 0, text.length()); return convertToHex(hashSHA256); }
00
Code Sample 1: public static void replaceEntry(File file, String entryName, InputStream stream) throws PersistenceException { try { File temporaryFile = File.createTempFile("pmMDA_zargo", ".zargo"); temporaryFile.deleteOnExit(); FileInputStream inputStream = new FileInputStream(file); ZipInputStream input = new ZipInputStream(inputStream); ZipOutputStream output = new ZipOutputStream(new FileOutputStream(temporaryFile)); ZipEntry entry = input.getNextEntry(); while (entry != null) { ZipEntry zipEntry = new ZipEntry(entry); zipEntry.setCompressedSize(-1); output.putNextEntry(zipEntry); if (!entry.getName().equals(entryName)) { IOUtils.copy(input, output); } else { IOUtils.copy(stream, output); } input.closeEntry(); output.closeEntry(); entry = input.getNextEntry(); } input.close(); inputStream.close(); output.close(); System.gc(); boolean isSuccess = file.delete(); if (!isSuccess) { throw new PersistenceException(); } isSuccess = temporaryFile.renameTo(file); if (!isSuccess) { throw new PersistenceException(); } } catch (IOException e) { throw new PersistenceException(e); } } Code Sample 2: public String gen() { String plainText = this.password; MessageDigest mdAlgorithm; StringBuffer hexString = new StringBuffer(); try { mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(plainText.getBytes()); byte[] digest = mdAlgorithm.digest(); for (int i = 0; i < digest.length; i++) { plainText = Integer.toHexString(0xFF & digest[i]); if (plainText.length() < 2) plainText = "0" + plainText; hexString.append(plainText); } } catch (NoSuchAlgorithmException ex) { } return hexString.toString(); }
00
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private byte[] odszyfrujKlucz(byte[] kluczSesyjny, int rozmiarKlucza) { byte[] odszyfrowanyKlucz = null; byte[] kluczTymczasowy = null; try { MessageDigest skrot = MessageDigest.getInstance("SHA-1"); skrot.update(haslo.getBytes()); byte[] skrotHasla = skrot.digest(); Object kluczDoKlucza = MARS_Algorithm.makeKey(skrotHasla); byte[] tekst = null; kluczTymczasowy = new byte[rozmiarKlucza]; int liczbaBlokow = rozmiarKlucza / ROZMIAR_BLOKU; for (int i = 0; i < liczbaBlokow; i++) { tekst = MARS_Algorithm.blockDecrypt(kluczSesyjny, i * ROZMIAR_BLOKU, kluczDoKlucza); System.arraycopy(tekst, 0, kluczTymczasowy, i * ROZMIAR_BLOKU, tekst.length); } odszyfrowanyKlucz = new byte[dlugoscKlucza]; System.arraycopy(kluczTymczasowy, 0, odszyfrowanyKlucz, 0, dlugoscKlucza); } catch (InvalidKeyException ex) { Logger.getLogger(SzyfrowaniePliku.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return odszyfrowanyKlucz; }
11
Code Sample 1: public Vector split() { File nextFile = new File(filename); long fileSize = nextFile.length(); long parts = fileSize / splitSize; Vector vec = new Vector(new Long(parts).intValue()); if (debug) { System.out.println("File: " + nextFile.getName() + "\nfileSize: " + fileSize + "\nsplitSize: " + splitSize + "\nparts: " + parts); } if (fileSize % splitSize > 0) { parts++; } try { FileInputStream fis = new FileInputStream(nextFile); DataInputStream dis = new DataInputStream(fis); long bytesRead = 0; File destinationDirectory = new File(nextFile.getParent()); if (!destinationDirectory.exists()) { destinationDirectory.mkdir(); } for (long k = 0; k < parts; k++) { if (debug) { System.out.println("Splitting parts: " + nextFile.getName() + " into part " + k); } String filePartName = nextFile.getName(); filePartName = filePartName + "." + String.valueOf(k); File outputFile = new File(destinationDirectory, filePartName); FileOutputStream fos = new FileOutputStream(outputFile); DataOutputStream dos = new DataOutputStream(fos); long bytesWritten = 0; while ((bytesWritten < splitSize) && (bytesRead < fileSize)) { dos.writeByte(dis.readByte()); bytesRead++; bytesWritten++; } dos.close(); vec.addElement(outputFile.getAbsolutePath()); if (debug) { System.out.println("Wrote " + bytesWritten + " bytes." + outputFile.getName() + " created."); } } } catch (FileNotFoundException fnfe) { System.err.println("FileNotFoundException: " + fnfe.getMessage()); vec = null; } catch (IOException ioe) { System.err.println("IOException: " + ioe.getMessage()); vec = null; } return vec; } Code Sample 2: private void execute(File file) throws IOException { if (file == null) throw new RuntimeException("undefined file"); if (!file.exists()) throw new RuntimeException("file not found :" + file); if (!file.isFile()) throw new RuntimeException("not a file :" + file); String login = cfg.getProperty(GC_USERNAME); String password = null; if (cfg.containsKey(GC_PASSWORD)) { password = cfg.getProperty(GC_PASSWORD); } else { password = new String(Base64.decode(cfg.getProperty(GC_PASSWORD64))); } PostMethod post = null; try { HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(login + ":" + password)); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new IOException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } finally { if (post != null) post.releaseConnection(); } }
00
Code Sample 1: private void preprocessImages(GeoImage[] detailedImages) throws IOException { for (int i = 0; i < detailedImages.length; i++) { BufferedImage img = loadImage(detailedImages[i].getPath()); detailedImages[i].setLatDim(img.getHeight()); detailedImages[i].setLonDim(img.getWidth()); freeImage(img); String fileName = detailedImages[i].getPath(); int dotindex = fileName.lastIndexOf("."); dotindex = dotindex < 0 ? 0 : dotindex; String tmp = dotindex < 1 ? fileName : fileName.substring(0, dotindex + 3) + "w"; System.out.println("filename " + tmp); File worldFile = new File(tmp); if (!worldFile.exists()) { System.out.println("Rez: Could not find file: " + tmp); debug("Rez: Could not find directory: " + tmp); throw new IOException("File not Found"); } BufferedReader worldFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(worldFile))); if (staticDebugOn) debug("b4nextline: "); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); if (line != null) { tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLonSpacing(Double.valueOf(tokenizer.nextToken()).doubleValue()); detailedImages[i].setLonExtent(detailedImages[i].getLonSpacing() * ((double) detailedImages[i].getLonDim() - 1d)); System.out.println("setLonExtent " + detailedImages[i].getLonExtent()); line = worldFileReader.readLine(); if (staticDebugOn) debug("skip line: " + line); line = worldFileReader.readLine(); if (staticDebugOn) debug("skip line: " + line); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLatSpacing(Double.valueOf(tokenizer.nextToken()).doubleValue()); detailedImages[i].setLatExtent(detailedImages[i].getLatSpacing() * ((double) detailedImages[i].getLatDim() - 1d)); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLon(Double.valueOf(tokenizer.nextToken()).doubleValue()); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLat(Double.valueOf(tokenizer.nextToken()).doubleValue()); int slashindex = fileName.lastIndexOf(java.io.File.separator); slashindex = slashindex < 0 ? 0 : slashindex; if (slashindex == 0) { slashindex = fileName.lastIndexOf("/"); slashindex = slashindex < 0 ? 0 : slashindex; } tmp = slashindex < 1 ? fileName : fileName.substring(slashindex + 1, fileName.length()); System.out.println("filename " + destinationDirectory + XPlat.fileSep + tmp); detailedImages[i].setPath(tmp); DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName))); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationDirectory + XPlat.fileSep + tmp))); System.out.println("copying to " + destinationDirectory + XPlat.fileSep + tmp); for (; ; ) { try { dataOut.writeShort(dataIn.readShort()); } catch (EOFException e) { break; } catch (IOException e) { break; } } dataOut.close(); } else { System.out.println("Rez: ERROR: World file for image is null"); } } } Code Sample 2: private HttpsURLConnection setUpConnection(URL url) throws NoSuchAlgorithmException, KeyManagementException, IOException { HttpsURLConnection openConnection = (HttpsURLConnection) url.openConnection(); openConnection.setAllowUserInteraction(true); openConnection.setUseCaches(false); openConnection.setDoInput(true); openConnection.setDoOutput(true); SSLContext sc = SSLContext.getInstance(SSL_PROTOCOL); sc.init(new KeyManager[] { new MyKeyManager() }, new TrustManager[] { new BypassTrustManager() }, null); openConnection.setSSLSocketFactory(sc.getSocketFactory()); return openConnection; }
00
Code Sample 1: public void deleteProposal(String id) throws Exception { String tmp = ""; PreparedStatement prepStmt = null; try { if (id == null || id.length() == 0) throw new Exception("Invalid parameter"); con = database.getConnection(); String delProposal = "delete from proposal where PROPOSAL_ID='" + id + "'"; prepStmt = con.prepareStatement(delProposal); prepStmt.executeUpdate(); con.commit(); prepStmt.close(); con.close(); } catch (Exception e) { if (!con.isClosed()) { con.rollback(); prepStmt.close(); con.close(); } throw e; } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: private static String md5(String text) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(text.getBytes("UTF-8")); byte[] messageDigest = digest.digest(); StringBuilder hexString = new StringBuilder(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } Code Sample 2: public static Object getInputStream(String name, boolean showMsg, URL appletDocumentBase, String appletProxy) { String errorMessage = null; int iurlPrefix; for (iurlPrefix = urlPrefixes.length; --iurlPrefix >= 0; ) if (name.startsWith(urlPrefixes[iurlPrefix])) break; boolean isURL = (iurlPrefix >= 0); boolean isApplet = (appletDocumentBase != null); InputStream in = null; int length; try { if (isApplet || isURL) { if (isApplet && isURL && appletProxy != null) name = appletProxy + "?url=" + URLEncoder.encode(name, "utf-8"); URL url = (isApplet ? new URL(appletDocumentBase, name) : new URL(name)); name = url.toString(); if (showMsg) Logger.info("FileManager opening " + url.toString()); URLConnection conn = url.openConnection(); length = conn.getContentLength(); in = conn.getInputStream(); } else { if (showMsg) Logger.info("FileManager opening " + name); File file = new File(name); length = (int) file.length(); in = new FileInputStream(file); } return new MonitorInputStream(in, length); } catch (Exception e) { try { if (in != null) in.close(); } catch (IOException e1) { } errorMessage = "" + e; } return errorMessage; }
11
Code Sample 1: public static void copyFile(HttpServletResponse response, String file) throws IOException { response.setContentType(FileUtils.getContentType(file)); response.setContentLength(FileUtils.getContentLength(file)); response.setHeader("Content-Length", Integer.toString(FileUtils.getContentLength(file))); InputStream input = new FileInputStream(file); OutputStream output = response.getOutputStream(); IOUtils.copy(input, output, true); } Code Sample 2: private void processBasicContent() { String[] packageNames = sourceCollector.getPackageNames(); for (int i = 0; i < packageNames.length; i++) { XdcSource[] sources = sourceCollector.getXdcSources(packageNames[i]); File dir = new File(outputDir, packageNames[i]); dir.mkdirs(); Set pkgDirs = new HashSet(); for (int j = 0; j < sources.length; j++) { XdcSource source = sources[j]; Properties patterns = source.getPatterns(); if (patterns != null) { tables.put("patterns", patterns); } pkgDirs.add(source.getFile().getParentFile()); DialectHandler dialectHandler = source.getDialectHandler(); Writer out = null; try { String sourceFilePath = source.getFile().getAbsolutePath(); source.setProcessingProperties(baseProperties, j > 0 ? sources[j - 1].getFileName() : null, j < sources.length - 1 ? sources[j + 1].getFileName() : null); String rootComment = XslUtils.transformToString(sourceFilePath, XSL_PKG + "/source-header.xsl", tables); source.setRootComment(rootComment); Document htmlDoc = XslUtils.transform(sourceFilePath, encoding, dialectHandler.getXslResourcePath(), tables); if (LOG.isInfoEnabled()) { LOG.info("Processing source file " + sourceFilePath); } out = IOUtils.getWriter(new File(dir, source.getFile().getName() + ".html"), docencoding); XmlUtils.printHtml(out, htmlDoc); if (sourceProcessor != null) { sourceProcessor.processSource(source, encoding, docencoding); } XdcSource.clearProcessingProperties(baseProperties); } catch (XmlException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } for (Iterator iter = pkgDirs.iterator(); iter.hasNext(); ) { File docFilesDir = new File((File) iter.next(), "xdc-doc-files"); if (docFilesDir.exists() && docFilesDir.isDirectory()) { File targetDir = new File(dir, "xdc-doc-files"); targetDir.mkdirs(); try { IOUtils.copyTree(docFilesDir, targetDir); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } }
00
Code Sample 1: public FTPClient sample1a(String server, int port, String username, String password) throws SocketException, IOException { FTPClient ftpClient = new FTPClient(); ftpClient.connect(server, port); ftpClient.login(username, password); return ftpClient; } Code Sample 2: public DataSet guessAtUnknowns(String filename) { TasselFileType guess = TasselFileType.Sequence; DataSet tds = null; try { BufferedReader br = null; if (filename.startsWith("http")) { URL url = new URL(filename); br = new BufferedReader(new InputStreamReader(url.openStream())); } else { br = new BufferedReader(new FileReader(filename)); } String line1 = br.readLine().trim(); String[] sval1 = line1.split("\\s"); String line2 = br.readLine().trim(); String[] sval2 = line2.split("\\s"); boolean lociMatchNumber = false; if (!sval1[0].startsWith("<") && (sval1.length == 2) && (line1.indexOf(':') < 0)) { int countLoci = Integer.parseInt(sval1[1]); if (countLoci == sval2.length) { lociMatchNumber = true; } } if (sval1[0].equalsIgnoreCase("<Annotated>")) { guess = TasselFileType.Annotated; } else if (line1.startsWith("<") || line1.startsWith("#")) { boolean isTrait = false; boolean isMarker = false; boolean isNumeric = false; boolean isMap = false; Pattern tagPattern = Pattern.compile("[<>\\s]+"); String[] info1 = tagPattern.split(line1); String[] info2 = tagPattern.split(line2); if (info1.length > 1) { if (info1[1].toUpperCase().startsWith("MARKER")) { isMarker = true; } else if (info1[1].toUpperCase().startsWith("TRAIT")) { isTrait = true; } else if (info1[1].toUpperCase().startsWith("NUMER")) { isNumeric = true; } else if (info1[1].toUpperCase().startsWith("MAP")) { isMap = true; } } if (info2.length > 1) { if (info2[1].toUpperCase().startsWith("MARKER")) { isMarker = true; } else if (info2[1].toUpperCase().startsWith("TRAIT")) { isTrait = true; } else if (info2[1].toUpperCase().startsWith("NUMER")) { isNumeric = true; } else if (info2[1].toUpperCase().startsWith("MAP")) { isMap = true; } } else { guess = null; String inline = br.readLine(); while (guess == null && inline != null && (inline.startsWith("#") || inline.startsWith("<"))) { if (inline.startsWith("<")) { String[] info = tagPattern.split(inline); if (info[1].toUpperCase().startsWith("MARKER")) { isMarker = true; } else if (info[1].toUpperCase().startsWith("TRAIT")) { isTrait = true; } else if (info[1].toUpperCase().startsWith("NUMER")) { isNumeric = true; } else if (info[1].toUpperCase().startsWith("MAP")) { isMap = true; } } } } if (isTrait || (isMarker && isNumeric)) { guess = TasselFileType.Phenotype; } else if (isMarker) { guess = TasselFileType.Polymorphism; } else if (isMap) { guess = TasselFileType.GeneticMap; } else { throw new IOException("Improperly formatted header. Data will not be imported."); } } else if ((line1.startsWith(">")) || (line1.startsWith(";"))) { guess = TasselFileType.Fasta; } else if (sval1.length == 1) { guess = TasselFileType.SqrMatrix; } else if (line1.indexOf(':') > 0) { guess = TasselFileType.Polymorphism; } else if ((sval1.length == 2) && (lociMatchNumber)) { guess = TasselFileType.Polymorphism; } else if ((line1.startsWith("#Nexus")) || (line1.startsWith("#NEXUS")) || (line1.startsWith("CLUSTAL")) || ((sval1.length == 2) && (sval2.length == 2))) { guess = TasselFileType.Sequence; } else if (sval1.length == 3) { guess = TasselFileType.Numerical; } myLogger.info("guessAtUnknowns: type: " + guess); tds = processDatum(filename, guess); br.close(); } catch (Exception e) { } return tds; }
11
Code Sample 1: public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: public static String criptografar(String senha) { if (senha == null) { return null; } try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ns) { LoggerFactory.getLogger(UtilAdrs.class).error(Msg.EXCEPTION_MESSAGE, UtilAdrs.class.getSimpleName(), ns); return senha; } }
11
Code Sample 1: public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); HttpSession session = request.getSession(); String session_id = session.getId(); File session_fileDir = new File(destinationDir + java.io.File.separator + session_id); session_fileDir.mkdir(); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(1 * 1024 * 1024); fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); String pathToFile = new String(); try { List items = uploadHandler.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { ; } else { pathToFile = getServletContext().getRealPath("/") + "files" + java.io.File.separator + session_id; File file = new File(pathToFile + java.io.File.separator + item.getName()); item.write(file); getContents(file, pathToFile); ComtorStandAlone.setMode(Mode.CLOUD); Comtor.start(pathToFile); } } try { File reportFile = new File(pathToFile + java.io.File.separator + "comtorReport.txt"); String reportURLString = AWSServices.storeReportS3(reportFile, session_id).toString(); if (reportURLString.startsWith("https")) reportURLString = reportURLString.replaceFirst("https", "http"); String requestURL = request.getRequestURL().toString(); String url = requestURL.substring(0, requestURL.lastIndexOf("/")); out.println("<html><head/><body>"); out.println("<a href=\"" + url + "\">Return to home</a>&nbsp;&nbsp;"); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/><hr/>"); Scanner scan = new Scanner(reportFile); out.println("<pre>"); while (scan.hasNextLine()) out.println(scan.nextLine()); out.println("</pre><hr/>"); out.println("<a href=\"" + url + "\">Return to home</a>&nbsp;&nbsp;"); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/>"); out.println("</body></html>"); } catch (Exception ex) { System.err.println(ex); } } catch (FileUploadException ex) { System.err.println("Error encountered while parsing the request" + ex); } catch (Exception ex) { System.err.println("Error encountered while uploading file" + ex); } } Code Sample 2: public File createReadmeFile(File dir, MavenProject mavenProject) throws IOException { InputStream is = getClass().getResourceAsStream("README.template"); StringWriter sw = new StringWriter(); IOUtils.copy(is, sw); String content = sw.getBuffer().toString(); content = StringUtils.replace(content, "{project_name}", mavenProject.getArtifactId()); File readme = new File(dir, "README.TXT"); FileUtils.writeStringToFile(readme, content); return readme; }
00
Code Sample 1: public boolean download(URL url, File file) { OutputStream out = null; URLConnection conn = null; InputStream in = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[4096]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } } catch (Exception e) { System.out.println(e); return false; } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { return false; } } return true; } Code Sample 2: public static File extract(File source, String filename, File target) { if (source.exists() == false || filename == null || filename.trim().length() < 1 || target == null) return null; boolean isDirectory = (filename.lastIndexOf("/") == filename.length() - 1); try { Map contents = (Map) jarContents.get(source.getPath()); if (contents == null) { contents = new HashMap(); jarContents.put(source.getPath(), contents); ZipInputStream input = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry = null; while ((zipEntry = input.getNextEntry()) != null) { if (zipEntry.isDirectory()) continue; contents.put(zipEntry.getName(), zipEntry); } input.close(); } if (isDirectory) { Iterator it = contents.keySet().iterator(); while (it.hasNext()) { String next = (String) it.next(); if (next.startsWith(filename)) { ZipEntry zipEntry = (ZipEntry) contents.get(next); int n = filename.length(); File newTarget = new File(target, zipEntry.getName().substring(n)); extract(source, next, newTarget); } } return target; } ZipEntry entry = (ZipEntry) contents.get(filename); ZipFile input = new ZipFile(source); InputStream in = input.getInputStream(entry); target.getParentFile().mkdirs(); int bytesRead; byte[] buffer = new byte[1024]; FileOutputStream output = new FileOutputStream(target); while ((bytesRead = in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); input.close(); return target; } catch (Exception ex) { ex.printStackTrace(); } return null; }
11
Code Sample 1: public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; inputLine = in.readLine(); String dist_metric = in.readLine(); File outFile = new File("data.txt"); FileWriter outw = new FileWriter(outFile); outw.write(inputLine); outw.close(); File sample_coords = new File("sample_coords.txt"); sample_coords.delete(); File sp_coords = new File("sp_coords.txt"); sp_coords.delete(); try { System.out.println("Running python script..."); System.out.println("Command: " + "python l19test.py " + "\"" + dist_metric + "\""); Process pr = Runtime.getRuntime().exec("python l19test.py " + dist_metric); BufferedReader br = new BufferedReader(new InputStreamReader(pr.getErrorStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println("Process Exit Value: " + exitVal); System.out.println("done."); } catch (Exception e) { System.out.println("Unable to run python script for PCoA analysis"); } File myFile = new File("sp_coords.txt"); byte[] mybytearray = new byte[(new Long(myFile.length())).intValue()]; FileInputStream fis = new FileInputStream(myFile); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); for (int i = 0; i < myFile.length(); i++) { out.writeByte(fis.read()); } myFile = new File("sample_coords.txt"); mybytearray = new byte[(int) myFile.length()]; fis = new FileInputStream(myFile); fis.read(mybytearray); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); out.write(mybytearray); myFile = new File("evals.txt"); mybytearray = new byte[(new Long(myFile.length())).intValue()]; fis = new FileInputStream(myFile); fis.read(mybytearray); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); out.write(mybytearray); out.flush(); out.close(); in.close(); clientSocket.close(); serverSocket.close(); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: private boolean copy(File in, File out) { try { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); FileChannel readableChannel = fis.getChannel(); FileChannel writableChannel = fos.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); fis.close(); fos.close(); return true; } catch (IOException ioe) { guiBuilder.showError("Copy Error", "IOException during copy", ioe.getMessage()); return false; } } Code Sample 2: public static void fileCopy(File src, File dst) throws FileNotFoundException, IOException { if (src.isDirectory() && (!dst.exists() || dst.isDirectory())) { if (!dst.exists()) { if (!dst.mkdirs()) throw new IOException("unable to mkdir " + dst); } File dst1 = new File(dst, src.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); dst = dst1; File[] files = src.listFiles(); for (File f : files) { if (f.isDirectory()) { dst1 = new File(dst, f.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); } else { dst1 = dst; } fileCopy(f, dst1); } return; } else if (dst.isDirectory()) { dst = new File(dst, src.getName()); } FileChannel ic = new FileInputStream(src).getChannel(); FileChannel oc = new FileOutputStream(dst).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
11
Code Sample 1: public void update() { try { String passwordMD5 = new String(); if (this.password != null && this.password.length() > 0) { MessageDigest md = MessageDigest.getInstance("md5"); md.update(this.password.getBytes()); byte[] digest = md.digest(); for (int i = 0; i < digest.length; i++) { passwordMD5 += Integer.toHexString((digest[i] >> 4) & 0xf); passwordMD5 += Integer.toHexString((digest[i] & 0xf)); } } this.authCode = new String(Base64Encoder.encode(new String(this.username + ";" + passwordMD5).getBytes())); } catch (Throwable throwable) { throwable.printStackTrace(); } } Code Sample 2: @SuppressWarnings("unchecked") private int syncCustomers() throws RemoteException, BasicException { dlintegration.syncCustomersBefore(); ArrayList<String> notToSync = new ArrayList<String>(); int step = 0; User[] remoteUsers; int cpt = 0; do { remoteUsers = externalsales.getUsersBySteps(step); step++; if (remoteUsers == null) { throw new BasicException(AppLocal.getIntString("message.returnnull") + " > Customers null"); } if (remoteUsers.length > 0) { String perms; for (User remoteUser : remoteUsers) { if (notToSync.contains(remoteUser.getLogin())) continue; cpt++; String name = externalsales.encodeString((remoteUser.getFirstname().trim() + " " + remoteUser.getLastname()).trim()); String firstname = externalsales.encodeString(remoteUser.getFirstname()); String lastname = externalsales.encodeString(remoteUser.getLastname()); String description = externalsales.encodeString(remoteUser.getDescription()); String address = externalsales.encodeString(remoteUser.getAddress()); String address2 = externalsales.encodeString(remoteUser.getAddress2()); String city = externalsales.encodeString(remoteUser.getCity()); String country = externalsales.encodeString(remoteUser.getCountry()); String phone = externalsales.encodeString(remoteUser.getPhone()); String mobile = externalsales.encodeString(remoteUser.getMobile()); String zipcode = externalsales.encodeString(remoteUser.getZipcode()); CustomerSync copyCustomer = new CustomerSync(remoteUser.getId()); if (firstname == null || firstname.equals("")) firstname = " "; copyCustomer.setFirstname(firstname.toUpperCase()); if (lastname == null || lastname.equals("")) lastname = " "; copyCustomer.setLastname(lastname.toUpperCase()); copyCustomer.setTaxid(remoteUser.getLogin()); copyCustomer.setSearchkey(remoteUser.getLogin() + name.toUpperCase()); if (name == null || name.equals("")) name = " "; copyCustomer.setName(name.toUpperCase()); if (description == null || description.equals("")) description = " "; copyCustomer.setNotes(description); copyCustomer.setEmail(remoteUser.getEmail()); if (address == null || address.equals("")) address = " "; copyCustomer.setAddress(address); if (address2 == null || address2.equals("")) address2 = " "; copyCustomer.setAddress2(address2); if (city == null || city.equals("")) city = "Brussels"; copyCustomer.setCity(city); if (country == null || country.equals("")) country = "Belgium"; copyCustomer.setCountry(country); copyCustomer.setMaxdebt(10000.0); if (phone == null || phone.equals("")) phone = " "; copyCustomer.setPhone(phone); if (mobile == null || mobile.equals("")) mobile = " "; copyCustomer.setPhone2(mobile); if (zipcode == null || zipcode.equals("")) zipcode = " "; copyCustomer.setPostal(zipcode); if (TicketInfo.isWS() && TicketInfo.getPayID() == 2 && remoteUser.getEmail().contains("@DONOTSENDME")) { notToSync.add(copyCustomer.getTaxid()); continue; } dlintegration.syncCustomer(copyCustomer); notToSync.add(copyCustomer.getTaxid()); } } } while (remoteUsers.length > 0); List<CustomerSync> localList = dlintegration.getCustomers(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (CustomerSync localCustomer : localList) { Date now = new Date(); if (notToSync.contains(localCustomer.getTaxid())) { continue; } cpt++; User userAdd = new User(); userAdd.setLogin(localCustomer.getTaxid()); userAdd.setId(localCustomer.getTaxid()); userAdd.setFirstname(" "); String tmpName = localCustomer.getName().trim(); tmpName = tmpName.replace("'", ""); while (tmpName.charAt(0) == ' ') { tmpName = tmpName.substring(1); } userAdd.setLastname(tmpName); char[] pw = new char[8]; int c = 'A'; int r1 = 0; for (int i = 0; i < 8; i++) { r1 = (int) (Math.random() * 3); switch(r1) { case 0: c = '0' + (int) (Math.random() * 10); break; case 1: c = 'a' + (int) (Math.random() * 26); break; case 2: c = 'A' + (int) (Math.random() * 26); break; } pw[i] = (char) c; } String clave = new String(pw); byte[] password = { 00 }; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(clave.getBytes()); password = md5.digest(); userAdd.setPassword(password.toString()); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UsersSync.class.getName()).log(Level.SEVERE, null, ex); userAdd.setPassword(clave); } userAdd.setTitle("M"); if (localCustomer.getEmail() == null || localCustomer.getEmail().trim().equals("") || localCustomer.getEmail().indexOf('@') <= 0) userAdd.setEmail(localCustomer.getTaxid() + defaultEmail); else userAdd.setEmail(localCustomer.getEmail()); userAdd.setDescription(localCustomer.getNotes() + ""); userAdd.setAddress(localCustomer.getAddress() + ""); userAdd.setAddress2(localCustomer.getAddress2() + ""); userAdd.setState_region(localCustomer.getRegion() + ""); userAdd.setCity(localCustomer.getCity() + ""); userAdd.setCountry(localCustomer.getCountry() + ""); userAdd.setZipcode(localCustomer.getPostal() + ""); userAdd.setPhone(localCustomer.getPhone() + ""); userAdd.setMobile(localCustomer.getPhone2() + ""); userAdd.setFax(" "); try { userAdd.setCdate(df.format(localCustomer.getCurdate())); } catch (NullPointerException nu) { userAdd.setCdate(df.format(now)); } userAdd.setPerms("shopper"); userAdd.setBank_account_nr(""); userAdd.setBank_account_holder(""); userAdd.setBank_account_type(""); userAdd.setBank_iban(""); userAdd.setBank_name(""); userAdd.setBank_sort_code(""); userAdd.setMdate(df.format(now)); userAdd.setShopper_group_id("1"); externalsales.addUser(userAdd); } return cpt; }
00
Code Sample 1: public static long[] getUids(String myUid) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpGet get = new HttpGet(UIDS_URI); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); JSONArray result = new JSONArray(res); long[] friends = new long[result.length()]; long uid = Long.parseLong(myUid); for (int i = 0; i < result.length(); i++) { if (uid != result.getLong(i)) { friends[i] = result.getLong(i); } } return friends; } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); } Code Sample 2: protected void copy(File src, File dest) throws IOException { if (src.isDirectory() && dest.isFile()) throw new IOException("Cannot copy a directory to a file"); if (src.isDirectory()) { File newDir = new File(dest, src.getName()); if (!newDir.mkdirs()) throw new IOException("Cannot create a new Directory"); File[] entries = src.listFiles(); for (int i = 0; i < entries.length; ++i) copy(entries[i], newDir); return; } if (dest.isDirectory()) { File newFile = new File(dest, src.getName()); newFile.createNewFile(); copy(src, newFile); return; } try { if (src.length() == 0) { dest.createNewFile(); return; } FileChannel fc = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); long transfered = 0; long totalLength = src.length(); while (transfered < totalLength) { long num = fc.transferTo(transfered, totalLength - transfered, dstChannel); if (num == 0) throw new IOException("Error while copying"); transfered += num; } dstChannel.close(); fc.close(); } catch (IOException e) { if (os.equals("Unix")) { _logger.fine("Trying to use cp to copy file..."); File cp = new File("/usr/bin/cp"); if (!cp.exists()) cp = new File("/bin/cp"); if (!cp.exists()) cp = new File("/usr/local/bin/cp"); if (!cp.exists()) cp = new File("/sbin/cp"); if (!cp.exists()) cp = new File("/usr/sbin/cp"); if (!cp.exists()) cp = new File("/usr/local/sbin/cp"); if (cp.exists()) { Process cpProcess = Runtime.getRuntime().exec(cp.getAbsolutePath() + " '" + src.getAbsolutePath() + "' '" + dest.getAbsolutePath() + "'"); int errCode; try { errCode = cpProcess.waitFor(); } catch (java.lang.InterruptedException ie) { throw e; } return; } } throw e; } }
11
Code Sample 1: public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } } Code Sample 2: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(targetPath + filename)); IOUtils.copy(is, fos); response.setStatus(HttpServletResponse.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
11
Code Sample 1: public void generate(String rootDir, RootModel root) throws Exception { IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("stylesheet.css"), new FileOutputStream(new File(rootDir, "stylesheet.css"))); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("model", root); context.put("util", new VelocityUtils()); context.put("msg", messages); processTemplate("index.html", new File(rootDir, "index.html"), context); processTemplate("list.html", new File(rootDir, "list.html"), context); processTemplate("summary.html", new File(rootDir, "summary.html"), context); File imageDir = new File(rootDir, "images"); imageDir.mkdir(); IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("primarykey.gif"), new FileOutputStream(new File(imageDir, "primarykey.gif"))); File tableDir = new File(rootDir, "tables"); tableDir.mkdir(); for (TableModel table : root.getTables()) { context.put("table", table); processTemplate("table.html", new File(tableDir, table.getTableName() + ".html"), context); } } Code Sample 2: @Override public void run() { try { FileChannel in = new FileInputStream(inputfile).getChannel(); long pos = 0; for (int i = 1; i <= noofparts; i++) { FileChannel out = new FileOutputStream(outputfile.getAbsolutePath() + "." + "v" + i).getChannel(); status.setText("Rozdělovač: Rozděluji část " + i + ".."); in.transferTo(pos, splitsize, out); pos += splitsize; remainingsize -= splitsize; if (remainingsize < splitsize) in.transferTo(pos, remainingsize, out); pb.setValue(100 * i / noofparts); out.close(); } in.close(); if (deleteOnFinish) new File(inputfile + "").delete(); status.setText("Rozdělovač: Hotovo.."); JOptionPane.showMessageDialog(null, "Rozděleno!", "Rozdělovač", JOptionPane.INFORMATION_MESSAGE); } catch (IOException ex) { } }
11
Code Sample 1: public static String read(URL url) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringWriter res = new StringWriter(); PrintWriter writer = new PrintWriter(new BufferedWriter(res)); String line; while ((line = reader.readLine()) != null) { writer.println(line); } reader.close(); writer.close(); return res.toString(); } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: public String getHashedPhoneId(Context aContext) { if (hashedPhoneId == null) { final String androidId = BuildInfo.getAndroidID(aContext); if (androidId == null) { hashedPhoneId = "EMULATOR"; } else { try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(androidId.getBytes()); messageDigest.update(aContext.getPackageName().getBytes()); final StringBuilder stringBuilder = new StringBuilder(); for (byte b : messageDigest.digest()) { stringBuilder.append(String.format("%02X", b)); } hashedPhoneId = stringBuilder.toString(); } catch (Exception e) { Log.e(LoggingExceptionHandler.class.getName(), "Unable to get phone id", e); hashedPhoneId = "Not Available"; } } } return hashedPhoneId; } Code Sample 2: private InputStream urlToInputStream(URL url) throws IOException { URLConnection conn = url.openConnection(); conn.setRequestProperty("User-Agent", IE); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.connect(); String encoding = conn.getContentEncoding(); if ((encoding != null) && encoding.equalsIgnoreCase("gzip")) return new GZIPInputStream(conn.getInputStream()); else if ((encoding != null) && encoding.equalsIgnoreCase("deflate")) return new InflaterInputStream(conn.getInputStream(), new Inflater(true)); else return conn.getInputStream(); }
00
Code Sample 1: protected List<? extends SearchResult> searchVideo(String words, int number, int offset, CancelMonitor cancelMonitor) { List<VideoSearchResult> resultsList = new ArrayList<>(); try { // set up the HTTP request factory HttpTransport transport = new NetHttpTransport(); HttpRequestFactory factory = transport.createRequestFactory(new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) { // set the parser JsonCParser parser = new JsonCParser(); parser.jsonFactory = JSON_FACTORY; request.addParser(parser); // set up the Google headers GoogleHeaders headers = new GoogleHeaders(); headers.setApplicationName("OGLExplorer/1.0"); headers.gdataVersion = "2"; request.headers = headers; } }); // build the YouTube URL YouTubeUrl url = new YouTubeUrl("https://gdata.youtube.com/feeds/api/videos"); url.maxResults = number; url.words = words; url.startIndex = offset + 1; // build HttpRequest request = factory.buildGetRequest(url); // execute HttpResponse response = request.execute(); VideoFeed feed = response.parseAs(VideoFeed.class); if (feed.items == null) { return null; } // browse result and convert them to the local generic object model for (int i = 0; i < feed.items.size() && !cancelMonitor.isCanceled(); i++) { Video result = feed.items.get(i); VideoSearchResult modelResult = new VideoSearchResult(offset + i + 1); modelResult.setTitle(result.title); modelResult.setDescription(result.description); modelResult.setThumbnailURL(new URL(result.thumbnail.lowThumbnailURL)); modelResult.setPath(result.player.defaultUrl); resultsList.add(modelResult); } } catch (Exception e) { e.printStackTrace(); } if (cancelMonitor.isCanceled()) { return null; } return resultsList; } Code Sample 2: public static String CreateHash(String s) { String str = s.toString(); if (str == null || str.length() == 0) { throw new IllegalArgumentException("String cannot be null or empty"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return (hexString.toString()); }
00
Code Sample 1: private static byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(frase.getBytes()); return md.digest(); } catch (Exception e) { return null; } } Code Sample 2: static void copyFile(File in, File outDir, String outFileName) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); outDir.mkdirs(); File outFile = new File(outDir, outFileName); FileChannel outChannel = new FileOutputStream(outFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
00
Code Sample 1: @Override public CelShadingModel loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException { boolean baseURLWasNull = setBaseURLFromModelURL(url); CelShadingModel model = loadModel(url.openStream(), skin); if (baseURLWasNull) { popBaseURL(); } return (model); } Code Sample 2: public void reset(String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, currentPilot); psta.setString(2, componentName); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
00
Code Sample 1: private String MD5Sum(String input) { String hashtext = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes()); byte[] digest = md.digest(); BigInteger bigInt = new BigInteger(1, digest); hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashtext; } Code Sample 2: public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, String myImagesBehaviour) { File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); File fileXML = new File(directoryPath + "images.xml"); SAXBuilder builder = new SAXBuilder(false); try { Document docXML = builder.build(fileXML); Element root = docXML.getRootElement(); List images = root.getChildren("image"); Iterator j = images.iterator(); int i = 0; TIGDataBase.activateTransactions(); while (j.hasNext() && !stop && !cancel) { current = i; i++; Element image = (Element) j.next(); String name = image.getAttributeValue("name"); List categories = image.getChildren("category"); Iterator k = categories.iterator(); if (exists(list, name)) { String pathSrc = directoryPath.concat(name); String pathDst = System.getProperty("user.dir") + File.separator + "images" + File.separator + name.substring(0, 1).toUpperCase() + File.separator; String folder = System.getProperty("user.dir") + File.separator + "images" + File.separator + name.substring(0, 1).toUpperCase(); if (myImagesBehaviour.equals(TLanguage.getString("TIGImportDBDialog.REPLACE_IMAGES"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.'))); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name.substring(0, name.lastIndexOf('.'))); TIGDataBase.deleteAsociatedOfImage(idImage); } pathDst = pathDst.concat(name); } if (myImagesBehaviour.equals(TLanguage.getString("TIGImportDBDialog.ADD_IMAGES"))) { Vector aux = new Vector(); aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.'))); int fileCount = 0; if (aux.size() != 0) { while (aux.size() != 0) { fileCount++; aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.')) + "_" + fileCount); } pathDst = pathDst + name.substring(0, name.lastIndexOf('.')) + '_' + fileCount + name.substring(name.lastIndexOf('.'), name.length()); name = name.substring(0, name.lastIndexOf('.')) + '_' + fileCount + name.substring(name.lastIndexOf('.'), name.length()); } else { pathDst = pathDst.concat(name); } } String pathThumbnail = (pathDst.substring(0, pathDst.lastIndexOf("."))).concat("_th.jpg"); File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertImageDB(name.substring(0, name.lastIndexOf('.')), name); int idImage = TIGDataBase.imageKeySearchName(name.substring(0, name.lastIndexOf('.'))); while (k.hasNext()) { Element category = (Element) k.next(); int idCategory = TIGDataBase.insertConceptDB(category.getValue()); TIGDataBase.insertAsociatedDB(idCategory, idImage); } } else { errorImages = errorImages + System.getProperty("line.separator") + name; } } TIGDataBase.executeQueries(); current = lengthOfTask; } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public static void bubbleSort(Auto[] xs) { boolean unsorted = true; while (unsorted) { unsorted = false; for (int i = 0; i < xs.length - 1; i++) { if (!(xs[i].getPreis() >= xs[i + 1].getPreis())) { Auto dummy = xs[i]; xs[i] = xs[i + 1]; xs[i + 1] = dummy; unsorted = true; } } } } Code Sample 2: public static InputStream retrievePricesHTML(String username, String password) throws IOException, SAXException { List<String> cookies = new ArrayList<String>(); URL url = new URL("http://motormouth.com.au/default_fl.aspx"); HttpURLConnection loginConnection = (HttpURLConnection) url.openConnection(); String viewStateValue = HTMLParser.parseHTMLInputTagValue(new InputStreamReader(loginConnection.getInputStream()), "__VIEWSTATE"); setCookies(cookies, loginConnection); HttpURLConnection postCredsConnection = (HttpURLConnection) url.openConnection(); postCredsConnection.setDoOutput(true); postCredsConnection.setRequestMethod("POST"); postCredsConnection.setInstanceFollowRedirects(false); postCredsConnection.setRequestProperty("Cookie", buildCookieString(cookies)); OutputStreamWriter postCredsWriter = new OutputStreamWriter(postCredsConnection.getOutputStream()); postCredsWriter.append("__VIEWSTATE=").append(URLEncoder.encode(viewStateValue, "UTF-8")).append('&'); postCredsWriter.append("Login_Module1%3Ausername=").append(URLEncoder.encode(username, "UTF-8")).append('&'); postCredsWriter.append("Login_Module1%3Apassword=").append(URLEncoder.encode(password, "UTF-8")).append('&'); postCredsWriter.append("Login_Module1%3AButtonLogin.x=0").append('&'); postCredsWriter.append("Login_Module1%3AButtonLogin.y=0"); postCredsWriter.flush(); postCredsWriter.close(); int postResponseCode = postCredsConnection.getResponseCode(); if (postResponseCode == 302) { setCookies(cookies, postCredsConnection); URL dataUrl = new URL(url, postCredsConnection.getHeaderField("Location")); HttpURLConnection dataConnection = (HttpURLConnection) dataUrl.openConnection(); dataConnection.setRequestProperty("Cookie", buildCookieString(cookies)); InputStream dataInputStream = dataConnection.getInputStream(); return dataInputStream; } else if (postResponseCode == 200) { URL dataUrl = new URL(url, "/secure/mymotormouth.aspx"); HttpURLConnection dataConnection = (HttpURLConnection) dataUrl.openConnection(); dataConnection.setRequestProperty("Cookie", buildCookieString(cookies)); InputStream dataInputStream = dataConnection.getInputStream(); return dataInputStream; } else { return null; } }
00
Code Sample 1: private String getMD5(String data) { try { MessageDigest md5Algorithm = MessageDigest.getInstance("MD5"); md5Algorithm.update(data.getBytes(), 0, data.length()); byte[] digest = md5Algorithm.digest(); StringBuffer hexString = new StringBuffer(); String hexDigit = null; for (int i = 0; i < digest.length; i++) { hexDigit = Integer.toHexString(0xFF & digest[i]); if (hexDigit.length() < 2) { hexDigit = "0" + hexDigit; } hexString.append(hexDigit); } return hexString.toString(); } catch (NoSuchAlgorithmException ne) { return data; } } Code Sample 2: @Override public Response executeGet(String url) throws IOException { if (logger.isLoggable(INFO)) logger.info("Making a GET request to " + url); HttpURLConnection httpUrlConnection = null; InputStream inputStream = null; try { httpUrlConnection = openConnection(new URL(url)); httpUrlConnection.setReadTimeout(DEFAULT_READ_TIMEOUT_IN_MS); httpUrlConnection.setUseCaches(false); customizeConnection(httpUrlConnection); httpUrlConnection.setRequestMethod("GET"); httpUrlConnection.connect(); if (logger.isLoggable(FINER)) logger.finer("Response headers: " + httpUrlConnection.getHeaderFields()); try { inputStream = httpUrlConnection.getResponseCode() != HTTP_OK ? httpUrlConnection.getErrorStream() : httpUrlConnection.getInputStream(); } catch (IOException e) { if (logger.isLoggable(WARNING)) logger.warning("An error occurred while making a GET request to " + url + ": " + e); } return new Response(httpUrlConnection.getResponseCode(), fromInputStream(inputStream)); } finally { closeQuietly(httpUrlConnection); } }
00
Code Sample 1: public static String encrypt(String text) { char[] toEncrypt = text.toCharArray(); StringBuffer hexString = new StringBuffer(); try { MessageDigest dig = MessageDigest.getInstance("MD5"); dig.reset(); String pw = ""; for (int i = 0; i < toEncrypt.length; i++) { pw += toEncrypt[i]; } dig.update(pw.getBytes()); byte[] digest = dig.digest(); int digestLength = digest.length; for (int i = 0; i < digestLength; i++) { hexString.append(hexDigit(digest[i])); } } catch (java.security.NoSuchAlgorithmException ae) { ae.printStackTrace(); } return hexString.toString(); } Code Sample 2: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: @SuppressWarnings("unchecked") public static void unzip(String zipFileName, String folder, boolean isCreate) throws IOException { File file = new File(zipFileName); File folderfile = null; if (file.exists() && file.isFile()) { String mfolder = folder == null ? file.getParent() : folder; String fn = file.getName(); fn = fn.substring(0, fn.lastIndexOf(".")); mfolder = isCreate ? (mfolder + File.separator + fn) : mfolder; folderfile = new File(mfolder); if (!folderfile.exists()) { folderfile.mkdirs(); } } else { throw new FileNotFoundException("不存在 zip 文件"); } ZipFile zipFile = new ZipFile(file); try { Enumeration<ZipArchiveEntry> en = zipFile.getEntries(); ZipArchiveEntry ze = null; while (en.hasMoreElements()) { ze = en.nextElement(); if (ze.isDirectory()) { String dirName = ze.getName(); dirName = dirName.substring(0, dirName.length() - 1); File f = new File(folderfile.getPath() + File.separator + dirName); f.mkdirs(); } else { File f = new File(folderfile.getPath() + File.separator + ze.getName()); if (!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } f.createNewFile(); InputStream in = zipFile.getInputStream(ze); OutputStream out = new FileOutputStream(f); IOUtils.copy(in, out); out.close(); in.close(); } } } finally { zipFile.close(); } } Code Sample 2: private static void userAuth(String challenge) throws IOException { try { MessageDigest md = MessageDigest.getInstance("BrokenMD4"); String passwd = null; if (System.getProperty("jarsync.password.gui") != null) { JPasswordField pass = new JPasswordField(); JPanel panel = new JPanel(new GridLayout(2, 1)); panel.add(new JLabel("Password:")); panel.add(pass); JOptionPane.showMessageDialog(null, panel, remoteUser + '@' + remoteHost + "'s Password", JOptionPane.QUESTION_MESSAGE); passwd = new String(pass.getPassword()); } else { System.out.print(remoteUser + '@' + remoteHost + "'s password: "); passwd = Util.readLine(System.in); System.out.println(); } md.update(new byte[4]); md.update(passwd.getBytes("US-ASCII")); md.update(challenge.getBytes("US-ASCII")); byte[] response = md.digest(); Util.writeASCII(out, remoteUser + " " + Util.base64(response) + '\n'); out.flush(); } catch (NoSuchAlgorithmException nsae) { throw new IOException("could not create message digest."); } }
00
Code Sample 1: public void execute(PaymentInfoMagcard payinfo) { if (payinfo.getTotal().compareTo(BigDecimal.ZERO) > 0) { try { StringBuffer sb = new StringBuffer(); sb.append("x_login="); sb.append(URLEncoder.encode(m_sCommerceID, "UTF-8")); sb.append("&x_password="); sb.append(URLEncoder.encode(m_sCommercePassword, "UTF-8")); sb.append("&x_version=3.1"); sb.append("&x_test_request="); sb.append(m_bTestMode); sb.append("&x_method=CC"); sb.append("&x_type="); sb.append(OPERATIONVALIDATE); sb.append("&x_amount="); NumberFormat formatter = new DecimalFormat("000.00"); String amount = formatter.format(payinfo.getTotal()); sb.append(URLEncoder.encode((String) amount, "UTF-8")); sb.append("&x_delim_data=TRUE"); sb.append("&x_delim_char=|"); sb.append("&x_relay_response=FALSE"); sb.append("&x_exp_date="); String tmp = payinfo.getExpirationDate(); sb.append(tmp.charAt(2)); sb.append(tmp.charAt(3)); sb.append(tmp.charAt(0)); sb.append(tmp.charAt(1)); sb.append("&x_card_num="); sb.append(URLEncoder.encode(payinfo.getCardNumber(), "UTF-8")); sb.append("&x_description=Shop+Transaction"); String[] cc_name = payinfo.getHolderName().split(" "); sb.append("&x_first_name="); if (cc_name.length > 0) { sb.append(URLEncoder.encode(cc_name[0], "UTF-8")); } sb.append("&x_last_name="); if (cc_name.length > 1) { sb.append(URLEncoder.encode(cc_name[1], "UTF-8")); } URL url = new URL(ENDPOINTADDRESS); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(sb.toString().getBytes()); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; line = in.readLine(); in.close(); String[] ccRep = line.split("\\|"); if ("1".equals(ccRep[0])) { payinfo.paymentOK((String) ccRep[4]); } else { payinfo.paymentError(AppLocal.getIntString("message.paymenterror") + "\n" + ccRep[0] + " -- " + ccRep[3]); } } catch (UnsupportedEncodingException eUE) { payinfo.paymentError(AppLocal.getIntString("message.paymentexceptionservice") + "\n" + eUE.getMessage()); } catch (MalformedURLException eMURL) { payinfo.paymentError(AppLocal.getIntString("message.paymentexceptionservice") + "\n" + eMURL.getMessage()); } catch (IOException e) { payinfo.paymentError(AppLocal.getIntString("message.paymenterror") + "\n" + e.getMessage()); } } else { payinfo.paymentError(AppLocal.getIntString("message.paymentrefundsnotsupported")); } } Code Sample 2: public void run() { try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); log.trace("passing in cookies: ", cookies); connection.setRequestProperty("Cookie", cookies); connection.getContent(); } catch (Exception e) { log.error(e); } }
11
Code Sample 1: public int delete(BusinessObject o) throws DAOException { int delete = 0; Bill bill = (Bill) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_BILL")); pst.setInt(1, bill.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; } Code Sample 2: public int delete(BusinessObject o) throws DAOException { int delete = 0; Account acc = (Account) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_ACCOUNT")); pst.setInt(1, acc.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; }
00
Code Sample 1: static String doHttp(String postURL, String text) { String returnValue = null; StringBuffer sb = new StringBuffer(); sb.append("bsh.client=Remote"); sb.append("&bsh.script="); sb.append(URLEncoder.encode(text)); String formData = sb.toString(); try { URL url = new URL(postURL); HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); urlcon.setRequestMethod("POST"); urlcon.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); urlcon.setDoOutput(true); urlcon.setDoInput(true); PrintWriter pout = new PrintWriter(new OutputStreamWriter(urlcon.getOutputStream(), "8859_1"), true); pout.print(formData); pout.flush(); int rc = urlcon.getResponseCode(); if (rc != HttpURLConnection.HTTP_OK) System.out.println("Error, HTTP response: " + rc); returnValue = urlcon.getHeaderField("Bsh-Return"); BufferedReader bin = new BufferedReader(new InputStreamReader(urlcon.getInputStream())); String line; while ((line = bin.readLine()) != null) System.out.println(line); System.out.println("Return Value: " + returnValue); } catch (MalformedURLException e) { System.out.println(e); } catch (IOException e2) { System.out.println(e2); } return returnValue; } Code Sample 2: public static Collection providers(Class service, ClassLoader loader) { List classList = new ArrayList(); List nameSet = new ArrayList(); String name = "META-INF/services/" + service.getName(); Enumeration services; try { services = (loader == null) ? ClassLoader.getSystemResources(name) : loader.getResources(name); } catch (IOException ioe) { System.err.println("Service: cannot load " + name); return classList; } while (services.hasMoreElements()) { URL url = (URL) services.nextElement(); InputStream input = null; BufferedReader reader = null; try { input = url.openStream(); reader = new BufferedReader(new InputStreamReader(input, "utf-8")); String line = reader.readLine(); while (line != null) { int ci = line.indexOf('#'); if (ci >= 0) line = line.substring(0, ci); line = line.trim(); int si = line.indexOf(' '); if (si >= 0) line = line.substring(0, si); line = line.trim(); if (line.length() > 0) { if (!nameSet.contains(line)) nameSet.add(line); } line = reader.readLine(); } } catch (IOException ioe) { System.err.println("Service: problem with: " + url); } finally { try { if (input != null) input.close(); if (reader != null) reader.close(); } catch (IOException ioe2) { System.err.println("Service: problem with: " + url); } } } Iterator names = nameSet.iterator(); while (names.hasNext()) { String className = (String) names.next(); try { classList.add(Class.forName(className, true, loader).newInstance()); } catch (ClassNotFoundException e) { System.err.println("Service: cannot find class: " + className); } catch (InstantiationException e) { System.err.println("Service: cannot instantiate: " + className); } catch (IllegalAccessException e) { System.err.println("Service: illegal access to: " + className); } catch (NoClassDefFoundError e) { System.err.println("Service: " + e + " for " + className); } catch (Exception e) { System.err.println("Service: exception for: " + className + " " + e); } } return classList; }
11
Code Sample 1: @Override public void alterar(QuestaoDiscursiva q) throws Exception { System.out.println("ALTERAR " + q.getIdQuestao()); PreparedStatement stmt = null; String sql = "UPDATE questao SET id_disciplina=?, enunciado=?, grau_dificuldade=? WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getDisciplina().getIdDisciplina()); stmt.setString(2, q.getEnunciado()); stmt.setString(3, q.getDificuldade().name()); stmt.setInt(4, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); alterarQuestaoDiscursiva(q); } catch (SQLException e) { conexao.rollback(); throw e; } } Code Sample 2: @Override public boolean putDescription(String uuid, String description) throws DatabaseException { if (uuid == null) throw new NullPointerException("uuid"); if (description == null) throw new NullPointerException("description"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } boolean found = true; try { PreparedStatement findSt = getConnection().prepareStatement(SELECT_COMMON_DESCRIPTION_STATEMENT); PreparedStatement updSt = null; findSt.setString(1, uuid); ResultSet rs = findSt.executeQuery(); found = rs.next(); int modified = 0; updSt = getConnection().prepareStatement(found ? UPDATE_COMMON_DESCRIPTION_STATEMENT : INSERT_COMMON_DESCRIPTION_STATEMENT); updSt.setString(1, description); updSt.setString(2, uuid); modified = updSt.executeUpdate(); if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + findSt + "\" and \"" + updSt + "\""); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback! Queries: \"" + findSt + "\" and \"" + updSt + "\""); found = false; } } catch (SQLException e) { LOGGER.error(e); found = false; } finally { closeConnection(); } return found; }
11
Code Sample 1: private final boolean copy_to_file_nio(File src, File dst) throws IOException { FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(src).getChannel(); dstChannel = new FileOutputStream(dst).getChannel(); { int safe_max = (64 * 1024 * 1024) / 4; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, safe_max, dstChannel); } } return true; } finally { try { if (srcChannel != null) srcChannel.close(); } catch (IOException e) { Debug.debug(e); } try { if (dstChannel != null) dstChannel.close(); } catch (IOException e) { Debug.debug(e); } } } Code Sample 2: private void saveFile(Folder folder, Object key, InputStream stream) throws FileManagerException { File file = new File(folder, key.toString()); LOGGER.debug("Writing file: " + file.getAbsolutePath()); Writer writer = null; Writer encodedWriter = null; try { encodedWriter = new OutputStreamWriter(new FileOutputStream(file), getEncodeCharset()); IOUtils.copy(stream, encodedWriter, getDecodeCharset()); LOGGER.info("saveFile(), decode charset: " + getDecodeCharset() + ", encode charset: " + getEncodeCharset()); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } finally { try { encodedWriter.close(); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } } }
00
Code Sample 1: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.close(output); } } finally { IOUtils.close(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } Code Sample 2: private void bokActionPerformed(java.awt.event.ActionEvent evt) { if (this.seriesstatementpanel.getEnteredvalues().get(0).toString().trim().equals("")) { this.showWarningMessage("Enter Series Title"); } else { String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveSeriesName("2", seriesstatementpanel.getEnteredvalues(), patlib); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SeriesNameServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } } }
00
Code Sample 1: @Override public void checkConnection(byte[] options) throws Throwable { Properties opts = PropertiesUtils.deserializeProperties(options); String server = opts.getProperty(TRANSFER_OPTION_SERVER); String username = opts.getProperty(TRANSFER_OPTION_USERNAME); String password = opts.getProperty(TRANSFER_OPTION_PASSWORD); String filePath = opts.getProperty(TRANSFER_OPTION_FILEPATH); URL url = new URL(PROTOCOL_PREFIX + username + ":" + password + "@" + server + filePath + ";type=i"); URLConnection urlc = url.openConnection(BackEnd.getProxy(Proxy.Type.SOCKS)); urlc.setConnectTimeout(Preferences.getInstance().preferredTimeOut * 1000); urlc.setReadTimeout(Preferences.getInstance().preferredTimeOut * 1000); urlc.connect(); } Code Sample 2: public String md5(String phrase) { MessageDigest m; String coded = new String(); try { m = MessageDigest.getInstance("MD5"); m.update(phrase.getBytes(), 0, phrase.length()); coded = (new BigInteger(1, m.digest()).toString(16)).toString(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return coded; }
00
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { if (System.getProperty("os.name").toUpperCase().indexOf("WIN") != -1) { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } else { inChannel.transferTo(0, inChannel.size(), outChannel); } } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public void doPreparedStatementQueryAndUpdate(Connection conn, String id) throws SQLException { try { int key = getNextKey(); String bValue = "doPreparedStatementQueryAndUpdate:" + id + ":" + testId; PreparedStatement s1; if (key >= MAX_KEY_VALUE) { key = key % MAX_KEY_VALUE; s1 = conn.prepareStatement("delete from many_threads where a = ?"); s1.setInt(1, key); s1.executeUpdate(); s1.close(); } s1 = conn.prepareStatement("insert into many_threads values (?, ?, 0)"); s1.setInt(1, key); s1.setString(2, bValue); assertEquals(1, s1.executeUpdate()); s1.close(); s1 = conn.prepareStatement("select a from many_threads where a = ?"); s1.setInt(1, key); assertEquals(key, executeQuery(s1)); s1.close(); s1 = conn.prepareStatement("update many_threads set value = a * a, b = b || ? where a = ?"); s1.setString(1, "&" + bValue); s1.setInt(2, key + 1); s1.executeUpdate(); s1.close(); if (!conn.getAutoCommit()) { conn.commit(); } } catch (SQLException e) { if (!conn.getAutoCommit()) { try { conn.rollback(); } catch (SQLException e2) { } } } }
00
Code Sample 1: public static void copyFile5(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copyLarge(in, out); in.close(); out.close(); } Code Sample 2: private static void _readAllRegionMDFiles(ClassLoader loader, RegionMetadata bean, String regionMDFile) { if (_LOG.isFinest()) { _LOG.finest("searching for region-metadata with resource:{0}", regionMDFile); } try { Enumeration<URL> files = loader.getResources(regionMDFile); while (files.hasMoreElements()) { URL url = files.nextElement(); String publicId = url.toString(); try { InputStream in = url.openStream(); _readRegionMetadata(bean, in, publicId); in.close(); } catch (IOException e) { _error(publicId, e); } } } catch (IOException e) { _LOG.warning("ERR_GET_REGION_METADATA_FILE", __CONFIG_FILE_OTHER); _LOG.warning(e); } }
00
Code Sample 1: void copyFile(String sInput, String sOutput) throws IOException { File inputFile = new File(sInput); File outputFile = new File(sOutput); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public void launch(String xmlControl, String xmlDoc, long docId) { AgentLauncher l; Environment env; Properties prop; Resource res; String token; String deflt; String answ; String key; String entry; ShipService service; de.fhg.igd.util.URL url; java.net.URL wsurl; NodeList flow; InputSource xmlcontrolstream; TreeMap results; synchronized (lock_) { if (xmlControl == null || xmlControl.length() == 0 || xmlDoc == null || xmlDoc.length() == 0) { System.out.println("---- Need control AND XML document! ----"); return; } Vector v_delegations_host = new Vector(); Vector v_delegations_url = new Vector(); Vector v_delegations_method = new Vector(); xmlcontrolstream = new InputSource(new StringReader(xmlControl)); NodeList destinations = SimpleXMLParser.parseDocument(xmlcontrolstream, AgentBehaviour.XML_DELEGATE); for (int i = 0; i < destinations.getLength(); i++) { if (destinations.item(i).getTextContent() != null && destinations.item(i).getTextContent().length() > 0) { System.out.println(destinations.item(i).getTextContent()); entry = SimpleXMLParser.findChildEntry(destinations.item(i), AgentBehaviour.XML_HOST); v_delegations_host.add(entry); entry = SimpleXMLParser.findChildEntry(destinations.item(i), AgentBehaviour.XML_URL); v_delegations_url.add(entry); entry = SimpleXMLParser.findChildEntry(destinations.item(i), AgentBehaviour.XML_METHOD); v_delegations_method.add(entry); } } token = ""; results = new TreeMap(); for (int i = 0; i < TOKEN_LENGTH; i++) { token = token + (char) (Math.random() * 26 + 65); } results.put(token, null); prop = AgentStructure.defaults(); prop.setProperty(AgentStructure.PROP_AGENT_CLASS, AGENT_); prop.setProperty(AgentBehaviour.CTX_DOCID, String.valueOf(docId)); prop.setProperty(AgentBehaviour.CTX_XML, xmlDoc); prop.setProperty("token", token); deflt = prop.getProperty(AgentStructure.PROP_AGENT_EXCLUDE); prop.setProperty(AgentStructure.PROP_AGENT_EXCLUDE, deflt + ":" + ADDITIONAL_EXCLUDES); service = (ShipService) getEnvironment().lookup(WhatIs.stringValue(ShipService.WHATIS)); for (int i = 0; i < v_delegations_host.size(); i++) { System.out.println("\n-----SCANNING DELEGATES-----"); System.out.println("\n-----DELEGATE " + i + "-----"); System.out.println("-----HOST: " + i + ": " + (String) v_delegations_host.elementAt(i)); System.out.println("-----URL: " + i + ": " + (String) v_delegations_url.elementAt(i)); System.out.println("-----METHOD: " + i + ": " + (String) v_delegations_method.elementAt(i)); try { url = new de.fhg.igd.util.URL((String) v_delegations_host.elementAt(i)); boolean alive = service.isAlive(url); System.out.println("-----ALIVE: " + alive); if (alive) { wsurl = new java.net.URL((String) v_delegations_url.elementAt(i)); try { wsurl.openStream(); System.out.println("-----WEBSERVICE: ON"); if (!prop.containsKey(0 + "." + AgentBehaviour.XML_URL)) { System.out.println("-----MIGRATION: First online host found. I will migrate here:)!"); prop.setProperty(0 + "." + AgentBehaviour.XML_HOST, (String) v_delegations_host.elementAt(i)); prop.setProperty(0 + "." + AgentBehaviour.XML_URL, (String) v_delegations_url.elementAt(i)); prop.setProperty(0 + "." + AgentBehaviour.XML_METHOD, (String) v_delegations_method.elementAt(i)); } else { System.out.println("-----MIGRATION: I will not migrate here:(!"); } } catch (IOException ex) { System.out.println("-----WEBSERVICE: Could not connect to the webservice!"); System.out.println("-----MIGRATION: WEBSERVICE NOT FOUND! I will not migrate here:(!"); } } } catch (ShipException she) { System.out.println("-----ALIVE: false"); System.out.println("-----MIGRATION: HOST NOT FOUND! I will not migrate here:(!"); } catch (SecurityException see) { System.out.println("-----EXCEPTION: Access connection to remote SHIP service fails! " + "No proper ShipPermission permission to invoke lookups! " + "Ignoring this host...."); } catch (MalformedURLException murle) { System.out.println("-----EXCEPTION: The host URL is not valid! Ignoring this host...."); } } res = new MemoryResource(); env = Environment.getEnvironment(); key = WhatIs.stringValue(AgentLauncher.WHATIS); l = (AgentLauncher) env.lookup(key); if (l == null) { System.out.println("Can't find the agent launcher"); return; } try { l.launchAgent(res, prop); } catch (IllegalAgentException ex) { System.out.println(ex); } catch (GeneralSecurityException ex) { System.out.println(ex); } catch (IOException ex) { System.out.println(ex); } syncmap_.put(token, results); System.out.println("----- TOKEN = " + token + "------"); } try { synchronized (token) { token.wait(TIMEOUT); Map m_results = (Map) syncmap_.get(token); Collection c_results = m_results.values(); String[] sa_results = (String[]) c_results.toArray(new String[0]); answ = ""; for (int j = 0; j < sa_results.length; j++) { answ = answ + sa_results[j]; } syncmap_.remove(token); System.out.println("----- " + answ + " -----"); callbackWS(xmlControl, answ, docId); } } catch (InterruptedException ex) { System.out.println(ex); } }
00
Code Sample 1: protected EntailmentType invokeHttp(String stuff) { String data = encode("theory") + "=" + encode(stuff); URL url; EntailmentType result = EntailmentType.unkown; try { url = new URL(httpAddress); } catch (MalformedURLException e) { throw new RuntimeException("FOL Reasoner not correclty configured: '" + httpAddress + "' is not an URL"); } log.debug("sending theory to endpoint: " + url); try { URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { log.debug("resultline: " + line); if (line.contains("Proof found")) { result = EntailmentType.entailed; } if (line.contains("Ran out of time")) { result = EntailmentType.unkown; } if (line.contains("Completion found")) { result = EntailmentType.notEntailed; } } wr.close(); rd.close(); } catch (IOException io) { throw new RuntimeException("the remote reasoner did not respond:" + io, io); } return result; } Code Sample 2: protected void processAnnotationsJndi(URL url) { try { URLConnection urlConn = url.openConnection(); DirContextURLConnection dcUrlConn; if (!(urlConn instanceof DirContextURLConnection)) { sm.getString("contextConfig.jndiUrlNotDirContextConn", url); return; } dcUrlConn = (DirContextURLConnection) urlConn; dcUrlConn.setUseCaches(false); String type = dcUrlConn.getHeaderField(ResourceAttributes.TYPE); if (ResourceAttributes.COLLECTION_TYPE.equals(type)) { Enumeration<String> dirs = dcUrlConn.list(); while (dirs.hasMoreElements()) { String dir = dirs.nextElement(); URL dirUrl = new URL(url.toString() + '/' + dir); processAnnotationsJndi(dirUrl); } } else { if (url.getPath().endsWith(".class")) { InputStream is = null; try { is = dcUrlConn.getInputStream(); processAnnotationsStream(is); } catch (IOException e) { logger.error(sm.getString("contextConfig.inputStreamJndi", url), e); } finally { if (is != null) { try { is.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } } } } catch (IOException e) { logger.error(sm.getString("contextConfig.jndiUrl", url), e); } }
00
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: protected boolean checkResource(final String resourceName) { boolean isValid = true; HttpURLConnection.setFollowRedirects(false); try { final URL url = new URL(buildUrl(new Resource(resourceName).getName())); logger.debug("check url: " + url.toString()); final HttpURLConnection headConnection = (HttpURLConnection) url.openConnection(); addHeaders(headConnection); headConnection.setRequestMethod("HEAD"); headConnection.setDoOutput(true); int statusCode = headConnection.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_MOVED_PERM) { isValid = false; logger.debug("responseCode: " + statusCode); } else { logger.debug("responseCode: " + statusCode); } } catch (MalformedURLException e) { logger.error(e.toString()); isValid = false; } catch (ProtocolException e) { logger.error(e.toString()); isValid = false; } catch (IOException e) { logger.error(e.toString()); isValid = false; } HttpURLConnection.setFollowRedirects(true); return isValid; }
11
Code Sample 1: public void copiarMidias(final File vidDir, final File imgDir) { for (int i = 0; i < getMidias().size(); i++) { try { FileChannel src = new FileInputStream(getMidias().get(i).getUrl().trim()).getChannel(); FileChannel dest; if (getMidias().get(i).getTipo().equals("video")) { FileChannel vidDest = new FileOutputStream(vidDir + "/" + processaString(getMidias().get(i).getTitulo()) + "." + retornaExtensaoMidia(getMidias().get(i))).getChannel(); dest = vidDest; } else { FileChannel midDest = new FileOutputStream(imgDir + "/" + processaString(getMidias().get(i).getTitulo()) + "." + retornaExtensaoMidia(getMidias().get(i))).getChannel(); dest = midDest; } dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (Exception e) { System.err.print(e.getMessage()); e.printStackTrace(); } } } Code Sample 2: protected File downloadUpdate(String resource) throws AgentException { RESTCall call = makeRESTCall(resource); call.invoke(); File tmpFile; try { tmpFile = File.createTempFile("controller-update-", ".war", new File(tmpPath)); } catch (IOException e) { throw new AgentException("Failed to create temporary file", e); } InputStream is; try { is = call.getInputStream(); } catch (IOException e) { throw new AgentException("Failed to open input stream", e); } try { FileOutputStream os; try { os = new FileOutputStream(tmpFile); } catch (FileNotFoundException e) { throw new AgentException("Failed to open temporary file for writing", e); } boolean success = false; try { IOUtils.copy(is, os); success = true; } catch (IOException e) { throw new AgentException("Failed to download update", e); } finally { try { os.flush(); os.close(); } catch (IOException e) { if (!success) throw new AgentException("Failed to flush to disk", e); } } } finally { try { is.close(); } catch (IOException e) { log.error("Failed to close input stream", e); } call.disconnect(); } return tmpFile; }
00
Code Sample 1: protected TaobaoResponse _fetch(HttpPost post, Map<String, CharSequence> payload, File file) throws IOException { Set<Entry<String, CharSequence>> entries = payload.entrySet(); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); for (Entry<String, CharSequence> entry : entries) { NameValuePair nvp = new BasicNameValuePair(entry.getKey(), (String) entry.getValue()); nvps.add(nvp); } if (file != null) { } else { post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); } if (this.keepAlive) { post.setHeader("Connection", "Keep-Alive"); } Header responseHeader = null; HttpResponse response = httpClient.execute(post); responseHeader = post.getLastHeader("sip_status"); String body = EntityUtils.toString(response.getEntity()); TaobaoResponse urlRsp = new TaobaoResponse(); if (responseHeader != null) { String status = responseHeader.getValue(); if (!SIP_STATUS_OK.equals(status)) { urlRsp.setErrorCode(status); urlRsp.setMsg(post.getLastHeader("sip_error_message").getValue()); if (status.equals("1004")) { urlRsp.setRedirectUrl(post.getLastHeader("sip_isp_loginurl").getValue()); } } } urlRsp.setBody(body); return urlRsp; } Code Sample 2: private void write(File src, File dst, byte id3v1Tag[], byte id3v2HeadTag[], byte id3v2TailTag[]) throws IOException { if (src == null || !src.exists()) throw new IOException(Debug.getDebug("missing src", src)); if (!src.getName().toLowerCase().endsWith(".mp3")) throw new IOException(Debug.getDebug("src not mp3", src)); if (dst == null) throw new IOException(Debug.getDebug("missing dst", dst)); if (dst.exists()) { dst.delete(); if (dst.exists()) throw new IOException(Debug.getDebug("could not delete dst", dst)); } boolean hasId3v1 = new MyID3v1().hasID3v1(src); long id3v1Length = hasId3v1 ? ID3_V1_TAG_LENGTH : 0; long id3v2HeadLength = new MyID3v2().findID3v2HeadLength(src); long id3v2TailLength = new MyID3v2().findID3v2TailLength(src, hasId3v1); OutputStream os = null; InputStream is = null; try { dst.getParentFile().mkdirs(); os = new FileOutputStream(dst); os = new BufferedOutputStream(os); if (!skipId3v2Head && !skipId3v2 && id3v2HeadTag != null) os.write(id3v2HeadTag); is = new FileInputStream(src); is = new BufferedInputStream(is); is.skip(id3v2HeadLength); long total_to_read = src.length(); total_to_read -= id3v1Length; total_to_read -= id3v2HeadLength; total_to_read -= id3v2TailLength; byte buffer[] = new byte[1024]; long total_read = 0; while (total_read < total_to_read) { int remainder = (int) (total_to_read - total_read); int readSize = Math.min(buffer.length, remainder); int read = is.read(buffer, 0, readSize); if (read <= 0) throw new IOException("unexpected EOF"); os.write(buffer, 0, read); total_read += read; } if (!skipId3v2Tail && !skipId3v2 && id3v2TailTag != null) os.write(id3v2TailTag); if (!skipId3v1 && id3v1Tag != null) os.write(id3v1Tag); } finally { try { if (is != null) is.close(); } catch (Throwable e) { Debug.debug(e); } try { if (os != null) os.close(); } catch (Throwable e) { Debug.debug(e); } } }
00
Code Sample 1: private void load(Runestone stone) throws RunesExceptionRuneExecution, RunesExceptionNoSuchContent { final Tokeniser tokeniser = stone.<Tokeniser>getContent("tokeniser").iterator().next(); rules = new HashMap<Node, List<GazRule>>(); System.out.println("Loading Gaz from: " + _url); if (_url == null) return; BufferedReader typesIn = null, entryIn = null; try { typesIn = new BufferedReader(new InputStreamReader(_url.openStream())); String tData = typesIn.readLine(); while (tData != null) { Map<String, Map> gaz = new HashMap<String, Map>(); String[] data = tData.split(":"); URL listURL = new URL(_url, data[0]); System.err.println("Loading from " + listURL); entryIn = new BufferedReader(new InputStreamReader(listURL.openStream())); String entry = entryIn.readLine(); while (entry != null) { entry = entry.trim(); if (!entry.equals("")) { final List<Token> tokens; try { tokens = tokeniser.tokenise(entry); } catch (IOException e) { throw new RunesExceptionRuneExecution(e, this); } Map<String, Map> m = gaz; for (Token t : tokens) { String token = t.getString(); if (_case_insensitive_gazetteer) token = token.toLowerCase(); @SuppressWarnings("unchecked") Map<String, Map> next = m.get(token); if (next == null) next = new HashMap<String, Map>(); m.put(token, next); m = next; } m.put(STOP, null); } entry = entryIn.readLine(); } for (Map.Entry<String, Map> er : gaz.entrySet()) { NodeAbstract start = new NodeStringImpl(TOKEN_TYPE, null); if (_case_insensitive_gazetteer) { start.addFeature(TOKEN_HAS_STRING, new NodeRegExpImpl(TOKEN_STRING, "(?i:" + er.getKey().toLowerCase() + ")")); } else { start.addFeature(TOKEN_HAS_STRING, new NodeStringImpl(TOKEN_STRING, er.getKey())); } @SuppressWarnings("unchecked") Transition transition = mapToTransition(er.getValue()); String major = data[1]; String minor = (data.length == 3 ? data[2] : null); GazRule gr = new GazRule(major, minor, transition); List<GazRule> rl = rules.get(start); if (rl == null) rl = new ArrayList<GazRule>(); rl.add(gr); rules.put(start, rl); } entryIn.close(); System.err.println(rules.size()); tData = typesIn.readLine(); } } catch (IOException e) { throw new RunesExceptionRuneExecution(e, this); } finally { try { if (typesIn != null) typesIn.close(); } catch (IOException e) { } try { if (entryIn != null) entryIn.close(); } catch (IOException e) { } } } Code Sample 2: @Override public void create(DisciplinaDTO disciplina) { try { this.criaConexao(false); } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } String sql = "insert into Disciplina select nextval('sq_Disciplina') as id, ? as nome"; PreparedStatement stmt = null; try { stmt = this.getConnection().prepareStatement(sql); stmt.setString(1, disciplina.getNome()); int retorno = stmt.executeUpdate(); if (retorno == 0) { this.getConnection().rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de inserir dados de Disciplina no banco!"); } this.getConnection().commit(); } catch (SQLException e) { try { this.getConnection().rollback(); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } } }
11
Code Sample 1: public boolean backup() { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/data/android.bluebox/databases/bluebox.db"; String backupDBPath = "/Android/bluebox.bak"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); return true; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } Code Sample 2: public void execute() throws BuildException { Project proj = getProject(); if (templateFile == null) throw new BuildException("Template file not set"); if (targetFile == null) throw new BuildException("Target file not set"); try { File template = new File(templateFile); File target = new File(targetFile); if (!template.exists()) throw new BuildException("Template file does not exist " + template.toString()); if (!template.canRead()) throw new BuildException("Cannot read template file: " + template.toString()); if (((!append) && (!overwrite)) && (!target.exists())) throw new BuildException("Target file already exists and append and overwrite are false " + target.toString()); if (VERBOSE) { System.out.println("ProcessTemplate: tmpl in " + template.toString()); System.out.println("ProcessTemplate: file out " + target.toString()); } BufferedReader reader = new BufferedReader(new FileReader(template)); BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, append)); parse(reader, writer); writer.flush(); writer.close(); } catch (Exception e) { if (VERBOSE) e.printStackTrace(); throw new BuildException(e); } }
00
Code Sample 1: protected Document loadDocument() throws MalformedURLException, DocumentException, IOException { if (jiraFilterURL.startsWith("file")) { URL url = getSourceURL(); return parseDocument(url); } else { HttpClient httpClient = new DefaultHttpClient(); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("os_username", jiraUser)); formparams.add(new BasicNameValuePair("os_password", jiraPassword)); formparams.add(new BasicNameValuePair("os_cookie", "true")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); HttpPost post = new HttpPost(getJiraRootUrl() + "/secure/login.jsp"); post.setEntity(entity); HttpResponse response = httpClient.execute(post); response.getEntity().consumeContent(); String url_str = StringEscapeUtils.unescapeXml(jiraFilterURL); HttpGet get = new HttpGet(url_str); response = httpClient.execute(get); return parseDocument(response.getEntity().getContent()); } } Code Sample 2: public ActionForward saveImageMap(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { log.debug("MapAction saveImageMap()"); String imageURL = RequestUtil.getRequest(request, "imgUrl"); DataInputStream di = null; FileOutputStream fo = null; byte[] b = new byte[1]; URL url = new URL(imageURL); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename=" + "map.png"); OutputStream outstream = response.getOutputStream(); byte abyte0[] = new byte[4096]; try { BufferedInputStream instream = new BufferedInputStream(urlConnection.getInputStream()); int i; while ((i = instream.read(abyte0, 0, 4096)) != -1) outstream.write(abyte0, 0, i); instream.close(); } catch (Exception e) { e.printStackTrace(); } return null; }
11
Code Sample 1: private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir, BackUpInfoFileGroup fileGroup, LinkedList<String> restoreList) { LinkedList<BackUpInfoFile> fileList = fileGroup.getFileList(); if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } for (int i = 0; i < fileList.size(); i++) { if (fileList.get(i).getId().equals(entry.getName())) { for (int j = 0; j < restoreList.size(); j++) { if ((fileList.get(i).getName() + "." + fileList.get(i).getType()).equals(restoreList.get(j))) { counter += 1; File outputFile = new File(outputDir, fileList.get(i).getName() + "." + fileList.get(i).getType()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream; BufferedOutputStream outputStream; try { inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (IOException ex) { throw new BackupException(ex.getMessage()); } } } } } } Code Sample 2: public static void concatFiles(final String as_base_file_name) throws IOException, FileNotFoundException { new File(as_base_file_name).createNewFile(); final OutputStream lo_out = new FileOutputStream(as_base_file_name, true); int ln_part = 1, ln_readed = -1; final byte[] lh_buffer = new byte[32768]; File lo_file = new File(as_base_file_name + "part1"); while (lo_file.exists() && lo_file.isFile()) { final InputStream lo_input = new FileInputStream(lo_file); while ((ln_readed = lo_input.read(lh_buffer)) != -1) { lo_out.write(lh_buffer, 0, ln_readed); } ln_part++; lo_file = new File(as_base_file_name + "part" + ln_part); } lo_out.flush(); lo_out.close(); }
11
Code Sample 1: public void testAddingEntries() throws Exception { DiskCache c = new DiskCache(); { c.setRoot(rootFolder.getAbsolutePath()); c.setHtmlExtension("htm"); c.setPropertiesExtension("txt"); assertEquals("htm", c.getHtmlExtension()); assertEquals("txt", c.getPropertiesExtension()); assertEquals(rootFolder.getAbsolutePath(), c.getRoot()); } String key1 = "cat1/key1"; String key2 = "cat1/key2"; try { try { { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(300005L); i.setTranslationCount(10); i.setEncoding("ISO-8859-7"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = new ByteArrayInputStream(greekTextBytes); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } c.storeInCache(key1, i); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key2, null); CacheItem i = c.getOrCreateCacheEntry(key2); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(350000L); i.setTranslationCount(11); i.setEncoding("ISO-8859-1"); i.setHeader(new ResponseHeaderImpl("Test3", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test4", new String[] { "Value1" })); String englishText = "Hello this is another example"; { InputStream input = new ByteArrayInputStream(englishText.getBytes("ISO-8859-1")); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[29]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test3", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test4", h.getName()); assertEquals("[Value1]", Arrays.toString(h.getValues())); } } } c.storeInCache(key2, i); assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-1"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(englishText, w.toString()); } } { CacheItem i = c.getOrCreateCacheEntry(key1); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); } } finally { c.removeCacheEntry(key1, null); } } finally { c.removeCacheEntry(key2, null); } } Code Sample 2: private void copyFile(File source, File target) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
00
Code Sample 1: @Override protected InputStream getResourceStream(String name) throws Exception { final BundleEntry entry = cpm.findLocalEntry(name); if (entry != null) return entry.getInputStream(); final URL url = cpm.getBaseData().getBundle().getResource(name); if (url != null) return url.openStream(); return null; } Code Sample 2: @Override protected Map<String, Definition> loadDefinitionsFromURL(URL url) { Map<String, Definition> defsMap = null; try { URLConnection connection = url.openConnection(); connection.connect(); lastModifiedDates.put(url.toExternalForm(), connection.getLastModified()); defsMap = reader.read(connection.getInputStream()); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("File " + null + " not found, continue [" + e.getMessage() + "]"); } } return defsMap; }
00
Code Sample 1: public List<MytemHistory> getMytemHistories(String janCode) throws GaeException { HttpClient client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); HttpConnectionParams.setSoTimeout(httpParams, 10000); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); BufferedReader reader = null; StringBuffer request = new StringBuffer(address); request.append("api/mytems/history?jan="); request.append(janCode); try { HttpGet httpGet = new HttpGet(request.toString()); HttpResponse httpResponse = client.execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == NOT_FOUND) { return null; } if (statusCode >= 400) { throw new GaeException("Status Error = " + Integer.toString(statusCode)); } reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { builder.append(line); } return createMytemHistories(builder.toString()); } catch (ClientProtocolException e) { throw new GaeException(e); } catch (SocketTimeoutException e) { throw new GaeException(e); } catch (IOException exception) { throw new GaeException(exception); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } Code Sample 2: public void runTask(HashMap pjobParms) throws Exception { FTPClient lftpClient = null; FileOutputStream lfosTargetFile = null; JBJFPluginDefinition lpluginCipher = null; IJBJFPluginCipher theCipher = null; try { JBJFFTPDefinition lxmlFTP = null; if (getFTPDefinition() != null) { lxmlFTP = getFTPDefinition(); this.mstrSourceDirectory = lxmlFTP.getSourceDirectory(); this.mstrTargetDirectory = lxmlFTP.getTargetDirectory(); this.mstrFilename = lxmlFTP.getFilename(); this.mstrRemoteServer = lxmlFTP.getServer(); if (getResources().containsKey("plugin-cipher")) { lpluginCipher = (JBJFPluginDefinition) getResources().get("plugin-cipher"); } if (lpluginCipher != null) { theCipher = getTaskPlugins().getCipherPlugin(lpluginCipher.getPluginId()); } if (theCipher != null) { this.mstrServerUsr = theCipher.decryptString(lxmlFTP.getUser()); this.mstrServerPwd = theCipher.decryptString(lxmlFTP.getPass()); } else { this.mstrServerUsr = lxmlFTP.getUser(); this.mstrServerPwd = lxmlFTP.getPass(); } } else { throw new Exception("Work unit [ " + SHORT_NAME + " ] is missing an FTP Definition. Please check" + " your JBJF Batch Definition file an make sure" + " this work unit has a <resource> element added" + " within the <task> element."); } lfosTargetFile = new FileOutputStream(mstrTargetDirectory + File.separator + mstrFilename); lftpClient = new FTPClient(); lftpClient.connect(mstrRemoteServer); lftpClient.setFileType(lxmlFTP.getFileTransferType()); if (!FTPReply.isPositiveCompletion(lftpClient.getReplyCode())) { throw new Exception("FTP server [ " + mstrRemoteServer + " ] refused connection."); } if (!lftpClient.login(mstrServerUsr, mstrServerPwd)) { throw new Exception("Unable to login to server [ " + mstrTargetDirectory + " ]."); } if (!lftpClient.changeWorkingDirectory(mstrSourceDirectory)) { throw new Exception("Unable to change to remote directory [ " + mstrSourceDirectory + "]"); } lftpClient.enterLocalPassiveMode(); if (!lftpClient.retrieveFile(mstrFilename, lfosTargetFile)) { throw new Exception("Unable to download [ " + mstrSourceDirectory + "/" + mstrFilename + " to " + mstrTargetDirectory + File.separator + mstrFilename + " ] from server [ " + mstrRemoteServer + " ]"); } lfosTargetFile.close(); lftpClient.logout(); } catch (Exception e) { throw e; } finally { if (lftpClient != null && lftpClient.isConnected()) { try { lftpClient.disconnect(); } catch (IOException ioe) { } } if (lfosTargetFile != null) { try { lfosTargetFile.close(); } catch (Exception e) { } } } }
11
Code Sample 1: static void linkBlocks(File from, File to, int oldLV) throws IOException { if (!from.isDirectory()) { if (from.getName().startsWith(COPY_FILE_PREFIX)) { IOUtils.copyBytes(new FileInputStream(from), new FileOutputStream(to), 16 * 1024, true); } else { if (oldLV >= PRE_GENERATIONSTAMP_LAYOUT_VERSION) { to = new File(convertMetatadataFileName(to.getAbsolutePath())); } HardLink.createHardLink(from, to); } return; } if (!to.mkdir()) throw new IOException("Cannot create directory " + to); String[] blockNames = from.list(new java.io.FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith(BLOCK_SUBDIR_PREFIX) || name.startsWith(BLOCK_FILE_PREFIX) || name.startsWith(COPY_FILE_PREFIX); } }); for (int i = 0; i < blockNames.length; i++) linkBlocks(new File(from, blockNames[i]), new File(to, blockNames[i]), oldLV); } Code Sample 2: private void copyFileNFS(String sSource, String sTarget) throws Exception { FileInputStream fis = new FileInputStream(sSource); FileOutputStream fos = new FileOutputStream(sTarget); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buf = new byte[2048]; int i = 0; while ((i = bis.read(buf)) != -1) bos.write(buf, 0, i); bis.close(); bos.close(); fis.close(); fos.close(); }
11
Code Sample 1: public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } Code Sample 2: public void run() { try { File outDir = new File(outDirTextField.getText()); if (!outDir.exists()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "The chosen directory does not exist!", "Directory Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (!outDir.isDirectory()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "The chosen file is not a directory!", "Not a Directory Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (!outDir.canWrite()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "Cannot write to the chosen directory!", "Directory Not Writeable Error", JOptionPane.ERROR_MESSAGE); } }); return; } File archiveDir = new File("foo.bar").getAbsoluteFile().getParentFile(); URL baseUrl = UnpackWizard.class.getClassLoader().getResource(UnpackWizard.class.getName().replaceAll("\\.", "/") + ".class"); if (baseUrl.getProtocol().equals("jar")) { String jarPath = baseUrl.getPath(); jarPath = jarPath.substring(0, jarPath.indexOf('!')); if (jarPath.startsWith("file:")) { try { archiveDir = new File(new URI(jarPath)).getAbsoluteFile().getParentFile(); } catch (URISyntaxException e1) { e1.printStackTrace(System.err); } } } SortedMap<Integer, String> inputFileNames = new TreeMap<Integer, String>(); for (Entry<Object, Object> anEntry : indexProperties.entrySet()) { String key = anEntry.getKey().toString(); if (key.startsWith("archive file ")) { inputFileNames.put(Integer.parseInt(key.substring("archive file ".length())), anEntry.getValue().toString()); } } byte[] buff = new byte[64 * 1024]; try { long bytesToWrite = 0; long bytesReported = 0; long bytesWritten = 0; for (String aFileName : inputFileNames.values()) { File aFile = new File(archiveDir, aFileName); if (aFile.exists()) { if (aFile.isFile()) { bytesToWrite += aFile.length(); } else { final File wrongFile = aFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "File \"" + wrongFile.getAbsolutePath() + "\" is not a standard file!", "Non Standard File Error", JOptionPane.ERROR_MESSAGE); } }); return; } } else { final File wrongFile = aFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "File \"" + wrongFile.getAbsolutePath() + "\" does not exist!", "File Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } } MultiFileInputStream mfis = new MultiFileInputStream(archiveDir, inputFileNames.values().toArray(new String[inputFileNames.size()])); TarArchiveInputStream tis = new TarArchiveInputStream(new BufferedInputStream(mfis)); TarArchiveEntry tarEntry = tis.getNextTarEntry(); while (tarEntry != null) { File outFile = new File(outDir.getAbsolutePath() + "/" + tarEntry.getName()); if (outFile.exists()) { final File wrongFile = outFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "Was about to write out file \"" + wrongFile.getAbsolutePath() + "\" but it already " + "exists.\nPlease [re]move existing files out of the way " + "and try again.", "File Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (tarEntry.isDirectory()) { outFile.getAbsoluteFile().mkdirs(); } else { outFile.getAbsoluteFile().getParentFile().mkdirs(); OutputStream os = new BufferedOutputStream(new FileOutputStream(outFile)); int len = tis.read(buff, 0, buff.length); while (len != -1) { os.write(buff, 0, len); bytesWritten += len; if (bytesWritten - bytesReported > (10 * 1024 * 1024)) { bytesReported = bytesWritten; final int progress = (int) (bytesReported * 100 / bytesToWrite); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setValue(progress); } }); } len = tis.read(buff, 0, buff.length); } os.close(); } tarEntry = tis.getNextTarEntry(); } long expectedCrc = 0; try { expectedCrc = Long.parseLong(indexProperties.getProperty("CRC32", "0")); } catch (NumberFormatException e) { System.err.println("Error while obtaining the expected CRC"); e.printStackTrace(System.err); } if (mfis.getCRC() == expectedCrc) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "Extraction completed successfully!", "Done!", JOptionPane.INFORMATION_MESSAGE); } }); return; } else { System.err.println("CRC Error: was expecting " + expectedCrc + " but got " + mfis.getCRC()); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "CRC Error: the data extracted does not have the expected CRC!\n" + "You should probably delete the extracted files, as they are " + "likely to be invalid.", "CRC Error", JOptionPane.ERROR_MESSAGE); } }); return; } } catch (final IOException e) { e.printStackTrace(System.err); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "Input/Output Error: " + e.getLocalizedMessage(), "Input/Output Error", JOptionPane.ERROR_MESSAGE); } }); return; } } finally { SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); setEnabled(true); } }); } }
11
Code Sample 1: @Test public void testWriteAndReadSecondLevel() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile directory1 = new RFile("directory1"); RFile directory2 = new RFile(directory1, "directory2"); RFile file = new RFile(directory2, "testreadwrite2nd.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } } Code Sample 2: @Override public void executeInterruptible() { encodingTerminated = false; File destinationFile = null; try { Runtime runtime = Runtime.getRuntime(); IconAndFileListElement element; while ((element = getNextFileElement()) != null) { File origFile = element.getFile(); destinationFile = new File(encodeFileCard.getDestinationFolder().getValue(), origFile.getName()); if (!destinationFile.getParentFile().exists()) { destinationFile.getParentFile().mkdirs(); } actualFileLabel.setText(origFile.getName()); actualFileModel.setMaximum((int) origFile.length()); actualFileModel.setValue(0); int bitrate; synchronized (bitratePattern) { Matcher bitrateMatcher = bitratePattern.matcher(encodeFileCard.getBitrate().getValue()); bitrateMatcher.find(); bitrate = Integer.parseInt(bitrateMatcher.group(1)); } List<String> command = new LinkedList<String>(); command.add(encoderFile.getCanonicalPath()); command.add("--mp3input"); command.add("-m"); command.add("j"); String sampleFreq = Settings.getSetting("encode.sample.freq"); if (Util.isNotEmpty(sampleFreq)) { command.add("--resample"); command.add(sampleFreq); } QualityElement quality = (QualityElement) ((JComboBox) encodeFileCard.getQuality().getValueComponent()).getSelectedItem(); command.add("-q"); command.add(Integer.toString(quality.getValue())); command.add("-b"); command.add(Integer.toString(bitrate)); command.add("--cbr"); command.add("-"); command.add(destinationFile.getCanonicalPath()); if (LOG.isDebugEnabled()) { StringBuilder commandLine = new StringBuilder(); boolean first = true; for (String part : command) { if (!first) commandLine.append(" "); commandLine.append(part); first = false; } LOG.debug("Command line: " + commandLine.toString()); } encodingProcess = runtime.exec(command.toArray(new String[0])); lastPosition = 0l; InputStream fileStream = null; try { fileStream = new PositionNotifierInputStream(new FileInputStream(origFile), origFile.length(), 2048, this); IOUtils.copy(fileStream, encodingProcess.getOutputStream()); encodingProcess.getOutputStream().close(); } finally { IOUtils.closeQuietly(fileStream); if (LOG.isDebugEnabled()) { InputStream processOut = null; try { processOut = encodingProcess.getInputStream(); StringWriter sw = new StringWriter(); IOUtils.copy(processOut, sw); LOG.debug("Process output stream:\n" + sw); IOUtils.closeQuietly(processOut); processOut = encodingProcess.getErrorStream(); sw = new StringWriter(); IOUtils.copy(processOut, sw); LOG.debug("Process error stream:\n" + sw); } finally { IOUtils.closeQuietly(processOut); } } } int result = encodingProcess.waitFor(); encodingProcess = null; if (result != 0) { LOG.warn("Encoder process returned error code " + result); } if (Boolean.parseBoolean(encodeFileCard.getCopyTag().getValue())) { MP3File mp3Input = new MP3File(origFile); MP3File mp3Output = new MP3File(destinationFile); boolean write = false; if (mp3Input.hasID3v2tag()) { ID3v2Tag id3v2Tag = new ID3v2Tag(); for (ID3v2Frame frame : mp3Input.getID3v2tag().getAllframes()) { id3v2Tag.addFrame(frame); } mp3Output.setID3v2tag(id3v2Tag); write = true; } if (mp3Input.hasID3v11tag()) { mp3Output.setID3v11tag(mp3Input.getID3v11tag()); write = true; } if (write) mp3Output.write(); } } actualFileLabel.setText(Messages.getString("operations.file.encode.execute.actualfile.terminated")); actualFileModel.setValue(actualFileModel.getMaximum()); } catch (Exception e) { LOG.error("Cannot encode files", e); if (!(e instanceof IOException && encodingTerminated)) MainWindowInterface.showError(e); if (destinationFile != null) destinationFile.delete(); } }
11
Code Sample 1: public static String getPasswordHash(String password) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } md.update(password.getBytes()); byte[] digest = md.digest(); BigInteger i = new BigInteger(1, digest); String hash = i.toString(16); while (hash.length() < 32) { hash = "0" + hash; } return hash; } Code Sample 2: public static String getETag(final String uri, final long lastModified) { try { final MessageDigest dg = MessageDigest.getInstance("MD5"); dg.update(uri.getBytes("utf-8")); dg.update(new byte[] { (byte) ((lastModified >> 24) & 0xFF), (byte) ((lastModified >> 16) & 0xFF), (byte) ((lastModified >> 8) & 0xFF), (byte) (lastModified & 0xFF) }); return CBASE64Codec.encode(dg.digest()); } catch (final Exception ignore) { return uri + lastModified; } }
00
Code Sample 1: public boolean checkConnection() { int tries = 3; for (int i = 0; i < tries; i++) { try { final URL url = new URL(wsURL); final URLConnection conn = url.openConnection(); conn.setReadTimeout(3000); conn.getContent(); return true; } catch (IOException ex) { Logger.getLogger(ExternalSalesHelper.class.getName()).log(Level.SEVERE, null, ex); } try { Thread.currentThread().sleep(2000); } catch (InterruptedException ex) { Logger.getLogger(OrdersSync.class.getName()).log(Level.SEVERE, null, ex); } } return false; } Code Sample 2: public void initResources() throws XAwareException { final String methodName = "initResources"; if (!initialized) { String host = channelObject.getProperty(XAwareConstants.BIZDRIVER_HOST); if (host == null || host.trim().length() == 0) { throw new XAwareException("xa:host must be specified."); } String portString = channelObject.getProperty(XAwareConstants.BIZDRIVER_PORT); if (portString == null || portString.trim().length() == 0) { throw new XAwareException("xa:port must be specified."); } int port = 0; try { port = Integer.parseInt(portString); } catch (Exception exception) { throw new XAwareException("xa:port must be numeric."); } String remoteVerification = channelObject.getProperty(XAwareConstants.XAWARE_FTP_REMOTE_VERIFICATION); String userName = channelObject.getProperty(XAwareConstants.BIZDRIVER_USER); String password = channelObject.getProperty(XAwareConstants.BIZDRIVER_PWD); String proxyUser = channelObject.getProperty(XAwareConstants.BIZCOMPONENT_ATTR_PROXYUSER); String proxyPassword = channelObject.getProperty(XAwareConstants.BIZCOMPONENT_ATTR_PROXYPASSWORD); ftpClient = new FTPClient(); logger.finest("Connecting to host:" + host + " Port:" + port, className, methodName); try { ftpClient.connect(host, port); if (remoteVerification != null && remoteVerification.trim().equals(XAwareConstants.XAWARE_YES)) { ftpClient.setRemoteVerificationEnabled(true); } else { ftpClient.setRemoteVerificationEnabled(false); } final int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); String errorMessage = "FTP server refused connection. Error Code:" + reply; logger.severe(errorMessage, className, methodName); throw new XAwareException(errorMessage); } logger.finest("Logging in User:" + userName + " PWD:" + password, className, methodName); if (!ftpClient.login(userName, password)) { ftpClient.logout(); String errorMessage = "Error logging into server. Please check credentials."; logger.severe(errorMessage, className, methodName); throw new XAwareException(errorMessage); } if (proxyUser != null && proxyUser.trim().length() > 0) { logger.finest("Logging in again proxy UID:" + proxyUser + " proxy password:" + proxyPassword, className, methodName); if (!ftpClient.login(proxyUser, proxyPassword)) { ftpClient.logout(); String errorMessage = "Error logging using proxy user/pwd. Please check proxy credentials."; logger.severe(errorMessage, className, methodName); throw new XAwareException(errorMessage); } } } catch (SocketException e) { String errorMessage = "SocketException: " + ExceptionMessageHelper.getExceptionMessage(e); logger.severe(errorMessage, className, methodName); throw new XAwareException(errorMessage, e); } catch (IOException e) { String errorMessage = "IOException: " + ExceptionMessageHelper.getExceptionMessage(e); logger.severe(errorMessage, className, methodName); throw new XAwareException(errorMessage, e); } logger.finest("Connected to host:" + host + " Port:" + port, className, methodName); initialized = true; } }
00
Code Sample 1: public void bubblesort(String filenames[]) { for (int i = filenames.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { String temp; if (filenames[j].compareTo(filenames[j + 1]) > 0) { temp = filenames[j]; filenames[j] = filenames[j + 1]; filenames[j + 1] = temp; } } } } Code Sample 2: public static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
00
Code Sample 1: private synchronized void createFTPConnection() throws RemoteClientException { ftpClient = new FTPClient(); try { URL url = fileset.getHostURL(); PasswordAuthentication passwordAuthentication = fileset.getPasswordAuthentication(); if (null == passwordAuthentication) { passwordAuthentication = anonPassAuth; } InetAddress inetAddress = InetAddress.getByName(url.getHost()); if (url.getPort() == -1) { ftpClient.connect(inetAddress); } else { ftpClient.connect(inetAddress, url.getPort()); } if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { throw new FTPBrowseException(ftpClient.getReplyString()); } ftpClient.login(passwordAuthentication.getUserName(), new StringBuffer().append(passwordAuthentication.getPassword()).toString()); if (url.getPath().length() > 0) { ftpClient.changeWorkingDirectory(url.getPath()); } } catch (UnknownHostException e) { throw new RemoteClientException("Host not found.", e); } catch (SocketException e) { throw new RemoteClientException("Socket cannot be opened.", e); } catch (IOException e) { throw new RemoteClientException("Socket cannot be opened.", e); } } Code Sample 2: @Test public void testEncryptDecrypt() throws IOException { BlockCipher cipher = new SerpentEngine(); Random rnd = new Random(); byte[] key = new byte[256 / 8]; rnd.nextBytes(key); byte[] iv = new byte[cipher.getBlockSize()]; rnd.nextBytes(iv); byte[] data = new byte[1230000]; new Random().nextBytes(data); ByteArrayOutputStream bout = new ByteArrayOutputStream(); CryptOutputStream eout = new CryptOutputStream(bout, cipher, key); eout.write(data); eout.close(); byte[] eData = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(eData); CryptInputStream din = new CryptInputStream(bin, cipher, key); bout = new ByteArrayOutputStream(); IOUtils.copy(din, bout); eData = bout.toByteArray(); Assert.assertTrue(Arrays.areEqual(data, eData)); }
00
Code Sample 1: public static void main(String[] args) throws FileNotFoundException, IOException { String filePath = "/Users/francisbaril/Downloads/test-1.pdf"; String testFilePath = "/Users/francisbaril/Desktop/testpdfbox/test.pdf"; File file = new File(filePath); final File testFile = new File(testFilePath); if (testFile.exists()) { testFile.delete(); } IOUtils.copy(new FileInputStream(file), new FileOutputStream(testFile)); System.out.println(getLongProperty(new FileInputStream(testFile), PROPRIETE_ID_IGID)); } Code Sample 2: private boolean doPost(String content) throws IOException { logger.debug("Service Registry PutRecordHandler: " + baseurl.toString()); logger.debug("**** Service Registry PutRecord Request ****\n " + content); HttpURLConnection huc = (HttpURLConnection) (baseurl.openConnection()); huc.setRequestMethod("POST"); huc.setDoOutput(true); ByteArrayInputStream in = new ByteArrayInputStream(content.getBytes()); OutputStream out = huc.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; BufferedInputStream bis = new BufferedInputStream(in); int count = 0; while ((count = bis.read(buffer)) != -1) { out.write(buffer, 0, count); } out.close(); int code = huc.getResponseCode(); logger.debug("Service Registry Response Code: " + code); if (code == 200) { return true; } else return false; }
00
Code Sample 1: public static void main(String[] args) { String u = "http://portal.acm.org/results.cfm?query=%28Author%3A%22" + "Boehm%2C+Barry" + "%22%29&srt=score%20dsc&short=0&source_disp=&since_month=&since_year=&before_month=&before_year=&coll=ACM&dl=ACM&termshow=matchboolean&range_query=&CFID=22704101&CFTOKEN=37827144&start=1"; URL url = null; AcmSearchresultPageParser_2010May cb = new AcmSearchresultPageParser_2010May(); try { url = new URL(u); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setUseCaches(false); InputStream is = uc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ParserDelegator pd = new ParserDelegator(); pd.parse(br, cb, true); br.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("all doc num= " + cb.getAllDocNum()); for (int i = 0; i < cb.getEachResultStartPositions().size(); i++) { HashMap<String, Integer> m = cb.getEachResultStartPositions().get(i); System.out.println(i + "pos= " + m); } } Code Sample 2: public static ArrayList<FriendInfo> downloadFriendsList(String username) { try { URL url; url = new URL(WS_URL + "/user/" + URLEncoder.encode(username, "UTF-8") + "/friends.xml"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); DocumentBuilderFactory dbFac = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbFac.newDocumentBuilder(); Document doc = db.parse(is); NodeList friends = doc.getElementsByTagName("user"); ArrayList<FriendInfo> result = new ArrayList<FriendInfo>(); for (int i = 0; i < friends.getLength(); i++) try { result.add(new FriendInfo((Element) friends.item(i))); } catch (Utils.ParseException e) { Log.e(TAG, "in downloadFriendsList", e); return null; } return result; } catch (Exception e) { Log.e(TAG, "in downloadFriendsList", e); return null; } }
00
Code Sample 1: private void getViolationsReportByProductOfferIdYearMonth() throws IOException { String xmlFile8Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "getViolationsReportByProductOfferIdYearMonth.xml"; URL url8; url8 = new URL(bmReportingWSUrl); URLConnection connection8 = url8.openConnection(); HttpURLConnection httpConn8 = (HttpURLConnection) connection8; FileInputStream fin8 = new FileInputStream(xmlFile8Send); ByteArrayOutputStream bout8 = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin8, bout8); fin8.close(); byte[] b8 = bout8.toByteArray(); httpConn8.setRequestProperty("Content-Length", String.valueOf(b8.length)); httpConn8.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn8.setRequestProperty("SOAPAction", soapAction); httpConn8.setRequestMethod("POST"); httpConn8.setDoOutput(true); httpConn8.setDoInput(true); OutputStream out8 = httpConn8.getOutputStream(); out8.write(b8); out8.close(); InputStreamReader isr8 = new InputStreamReader(httpConn8.getInputStream()); BufferedReader in8 = new BufferedReader(isr8); String inputLine8; StringBuffer response8 = new StringBuffer(); while ((inputLine8 = in8.readLine()) != null) { response8.append(inputLine8); } in8.close(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: Business Manager\n" + "Interface Name: getReport\n" + "Operation Name:" + "getViolationsReportByProductOfferIdYearMonth\n" + "Input" + "ProductOfferID-1\n" + "PartyID-1\n" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println("--------------------------------"); System.out.println("Response\n" + response8.toString()); } Code Sample 2: void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }