label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: private void unpackBundle() throws IOException { File useJarPath = null; if (DownloadManager.isWindowsVista()) { useJarPath = lowJarPath; File jarDir = useJarPath.getParentFile(); if (jarDir != null) { jarDir.mkdirs(); } } else { useJarPath = jarPath; } DownloadManager.log("Unpacking " + this + " to " + useJarPath); InputStream rawStream = new FileInputStream(localPath); JarInputStream in = new JarInputStream(rawStream) { public void close() throws IOException { } }; try { File jarTmp = null; JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { String entryName = entry.getName(); if (entryName.equals("classes.pack")) { File packTmp = new File(useJarPath + ".pack"); packTmp.getParentFile().mkdirs(); DownloadManager.log("Writing temporary .pack file " + packTmp); OutputStream tmpOut = new FileOutputStream(packTmp); try { DownloadManager.send(in, tmpOut); } finally { tmpOut.close(); } jarTmp = new File(useJarPath + ".tmp"); DownloadManager.log("Writing temporary .jar file " + jarTmp); unpack(packTmp, jarTmp); packTmp.delete(); } else if (!entryName.startsWith("META-INF")) { File dest; if (DownloadManager.isWindowsVista()) { dest = new File(lowJavaPath, entryName.replace('/', File.separatorChar)); } else { dest = new File(DownloadManager.JAVA_HOME, entryName.replace('/', File.separatorChar)); } if (entryName.equals(BUNDLE_JAR_ENTRY_NAME)) dest = useJarPath; File destTmp = new File(dest + ".tmp"); boolean exists = dest.exists(); if (!exists) { DownloadManager.log(dest + ".mkdirs()"); dest.getParentFile().mkdirs(); } try { DownloadManager.log("Using temporary file " + destTmp); FileOutputStream out = new FileOutputStream(destTmp); try { byte[] buffer = new byte[2048]; int c; while ((c = in.read(buffer)) > 0) out.write(buffer, 0, c); } finally { out.close(); } if (exists) dest.delete(); DownloadManager.log("Renaming from " + destTmp + " to " + dest); if (!destTmp.renameTo(dest)) { throw new IOException("unable to rename " + destTmp + " to " + dest); } } catch (IOException e) { if (!exists) throw e; } } } if (jarTmp != null) { if (useJarPath.exists()) jarTmp.delete(); else if (!jarTmp.renameTo(useJarPath)) { throw new IOException("unable to rename " + jarTmp + " to " + useJarPath); } } if (DownloadManager.isWindowsVista()) { DownloadManager.log("Using broker to move " + name); if (!DownloadManager.moveDirWithBroker(DownloadManager.getKernelJREDir() + name)) { throw new IOException("unable to create " + name); } DownloadManager.log("Broker finished " + name); } DownloadManager.log("Finished unpacking " + this); } finally { rawStream.close(); } if (deleteOnInstall) { localPath.delete(); } } Code Sample 2: public static String getHash(String password) { try { MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(password.getBytes()); return new String(digest.digest()); } catch (NoSuchAlgorithmException e) { log.error("Hashing algorithm not found"); return password; } }
00
Code Sample 1: public void run() { RandomAccessFile file = null; InputStream stream = null; try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Range", "bytes=" + downloaded + "-"); connection.connect(); if (connection.getResponseCode() / 100 != 2) { error(); } int contentLength = connection.getContentLength(); if (contentLength < 1) { error(); } if (size == -1) { size = contentLength; stateChanged(); } file = new RandomAccessFile(saveas, "rw"); file.seek(downloaded); stream = connection.getInputStream(); while (status == DOWNLOADING) { byte buffer[]; if (size - downloaded > MAX_BUFFER_SIZE) { buffer = new byte[MAX_BUFFER_SIZE]; } else { buffer = new byte[size - downloaded]; } int read = stream.read(buffer); if (read == -1) break; file.write(buffer, 0, read); downloaded += read; stateChanged(); } if (status == DOWNLOADING) { status = COMPLETE; stateChanged(); } } catch (Exception e) { e.printStackTrace(); error(); } finally { if (file != null) { try { file.close(); } catch (Exception e) { } } if (stream != null) { try { stream.close(); } catch (Exception e) { } } } } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
00
Code Sample 1: private void runUpdateAppListing() { DataStorage.clearListedAppListing(); GenericUrl url = new GoogleUrl(EnterpriseMarketplaceUrl.generateAppListingUrl() + DataStorage.getVendorProfile().vendorId); AppListing appListingBody = buildAppListing(appsMarketplaceProject); JsonHttpContent content = new JsonHttpContent(); content.jsonFactory = jsonFactory; if (appListingBody != null) { content.data = appListingBody; } AppListing appListing; try { HttpRequest request = requestFactory.buildPutRequest(url, content); request.addParser(jsonHttpParser); request.readTimeout = readTimeout; HttpResponse response = request.execute(); appListing = response.parseAs(AppListing.class); operationStatus = validateAppListing(appListing, appListingBody); if (operationStatus) { DataStorage.setListedAppListing(appListing); } response.getContent().close(); } catch (IOException e) { AppsMarketplacePluginLog.logError(e); } } Code Sample 2: public WordEntry[] getVariants(String word) throws MatchPackException { String upperWord = word.toUpperCase(); if (variantsDictionary == null) { try { long start = System.currentTimeMillis(); URL url = this.getClass().getResource("varlex.dic"); ObjectInputStream si = new ObjectInputStream(url.openStream()); variantsDictionary = (Map) si.readObject(); long end = System.currentTimeMillis(); System.out.println("loaded " + (end - start) + "ms"); si.close(); } catch (Exception e) { throw new MatchPackException("cannot load: varlex.dic " + e.getMessage()); } } List l = (List) variantsDictionary.get(upperWord); if (l == null) { return new WordEntry[0]; } return (WordEntry[]) l.toArray(new WordEntry[0]); }
00
Code Sample 1: public static int[] BubbleSortDEC(int[] values) { boolean change = true; int aux; int[] indexes = new int[values.length]; for (int i = 0; i < values.length; i++) { indexes[i] = i; } while (change) { change = false; for (int i = 0; i < values.length - 1; i++) { if (values[i] < values[i + 1]) { aux = values[i]; values[i] = values[i + 1]; values[i + 1] = aux; aux = indexes[i]; indexes[i] = indexes[i + 1]; indexes[i + 1] = aux; change = true; } } } return (indexes); } Code Sample 2: public static String checkPublicIP() { String ipAddress = null; try { URL url; url = new URL("http://checkip.dyndns.org/"); InputStreamReader in = new InputStreamReader(url.openStream()); BufferedReader buffer = new BufferedReader(in); String line; Pattern p = Pattern.compile("\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b"); while ((line = buffer.readLine()) != null) { if (line.indexOf("IP Address:") != -1) { Matcher m = p.matcher(line); if (m.find()) { ipAddress = m.group(); break; } } } buffer.close(); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ipAddress; }
00
Code Sample 1: @Override public User createUser(User bean) throws SitoolsException { checkUser(); if (!User.isValid(bean)) { throw new SitoolsException("CREATE_USER_MALFORMED"); } Connection cx = null; try { cx = ds.getConnection(); cx.setAutoCommit(false); PreparedStatement st = cx.prepareStatement(jdbcStoreResource.CREATE_USER); int i = 1; st.setString(i++, bean.getIdentifier()); st.setString(i++, bean.getFirstName()); st.setString(i++, bean.getLastName()); st.setString(i++, bean.getSecret()); st.setString(i++, bean.getEmail()); st.executeUpdate(); st.close(); createProperties(bean, cx); if (!cx.getAutoCommit()) { cx.commit(); } } catch (SQLException e) { try { cx.rollback(); } catch (SQLException e1) { e1.printStackTrace(); throw new SitoolsException("CREATE_USER ROLLBACK" + e1.getMessage(), e1); } e.printStackTrace(); throw new SitoolsException("CREATE_USER " + e.getMessage(), e); } finally { closeConnection(cx); } return getUserById(bean.getIdentifier()); } Code Sample 2: public T08OTSDTMInterpositionUnitTestCase(String name) throws java.io.IOException { super(name); java.net.URL url = ClassLoader.getSystemResource("host0.cosnaming.jndi.properties"); jndiProps = new java.util.Properties(); jndiProps.load(url.openStream()); }
00
Code Sample 1: private void copyTemplates(ProjectPath pPath) { String sourceAntPath = pPath.sourceAntPath(); final String moduleName = projectOperations.getFocusedTopLevelPackage().toString(); logger.info("Module Name: " + moduleName); String targetDirectory = pPath.canonicalFileSystemPath(projectOperations); logger.info("Moving into target Directory: " + targetDirectory); if (!targetDirectory.endsWith("/")) { targetDirectory += "/"; } if (!fileManager.exists(targetDirectory)) { fileManager.createDirectory(targetDirectory); } System.out.println("Target Directory: " + pPath.sourceAntPath()); String path = TemplateUtils.getTemplatePath(getClass(), sourceAntPath); Set<URL> urls = UrlFindingUtils.findMatchingClasspathResources(context.getBundleContext(), path); Assert.notNull(urls, "Could not search bundles for resources for Ant Path '" + path + "'"); if (urls.isEmpty()) { logger.info("URLS are empty stopping..."); } for (URL url : urls) { logger.info("Stepping into " + url.toExternalForm()); String fileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1); fileName = fileName.replace("-template", ""); String targetFilename = targetDirectory + fileName; logger.info("Handling " + targetFilename); if (!fileManager.exists(targetFilename)) { try { logger.info("Copied file"); String input = FileCopyUtils.copyToString(new InputStreamReader(url.openStream())); logger.info("TopLevelPackage: " + projectOperations.getFocusedTopLevelPackage()); logger.info("SegmentPackage: " + pPath.canonicalFileSystemPath(projectOperations)); String topLevelPackage = projectOperations.getFocusedTopLevelPackage().toString(); input = input.replace("__TOP_LEVEL_PACKAGE__", topLevelPackage); input = input.replace("__SEGMENT_PACKAGE__", pPath.segmentPackage()); input = input.replace("__PROJECT_NAME__", projectOperations.getFocusedProjectName()); input = input.replace("__ENTITY_NAME__", entityName); MutableFile mutableFile = fileManager.createFile(targetFilename); FileCopyUtils.copy(input.getBytes(), mutableFile.getOutputStream()); } catch (IOException ioe) { throw new IllegalStateException("Unable to create '" + targetFilename + "'", ioe); } } } } Code Sample 2: public static void compress(final File zip, final Map<InputStream, String> entries) throws IOException { if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!"); if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip))); out.setLevel(Deflater.BEST_COMPRESSION); InputStream in = null; try { for (InputStream inputStream : entries.keySet()) { in = inputStream; ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(in))); out.putNextEntry(zipEntry); IOUtils.copy(in, out); out.closeEntry(); in.close(); } } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
00
Code Sample 1: private PluginInfo loadPluginInfo(URL filename) throws PluginNotFoundException { if (filename == null) return null; BufferedReader in = null; InputStream is = null; String mainClass = null; String u = filename.toString(); PluginInfo pi = new PluginInfo(); URL url; try { url = new URL("jar:" + u + "!/"); } catch (MalformedURLException mue) { throw new PluginNotFoundException(mue); } pi.setURL(filename); HashMap names = new HashMap(); boolean seemsOK = false; for (int tries = 0; (tries <= 5) && (!seemsOK); tries++) { try { JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); jarConnection.setUseCaches(false); JarFile jf = jarConnection.getJarFile(); is = jf.getInputStream(jf.getJarEntry("META-INF/MANIFEST.MF")); in = new BufferedReader(new InputStreamReader(is)); String line; while ((line = in.readLine()) != null) { if (line.startsWith("Frostplugin-Main-Class: ")) { mainClass = line.substring("Frostplugin-Main-Class: ".length()).trim(); pi.setMainClass(mainClass); logger.log(Level.SEVERE, "Found plugin main class " + mainClass + " from manifest"); } } is = jf.getInputStream(jf.getJarEntry("pluginname.properties")); in = new BufferedReader(new InputStreamReader(is)); while ((line = in.readLine()) != null) { if (line.startsWith("#")) { continue; } if (line.length() == 0) { continue; } String[] sa = line.split("=", 2); names.put(sa[0], sa[1]); pi.setPluginNames(names); } seemsOK = true; } catch (Exception e) { if (tries >= 5) throw new PluginNotFoundException("Initialization error:" + filename, e); try { Thread.sleep(100); } catch (Exception ee) { } } finally { try { if (is != null) is.close(); if (in != null) in.close(); } catch (IOException ioe) { } } } return pi; } Code Sample 2: public void addStadium(Stadium stadium) throws StadiumException { Connection conn = ConnectionManager.getManager().getConnection(); if (findStadiumBy_N_C(stadium.getName(), stadium.getCity()) != -1) throw new StadiumException("Stadium already exists"); try { PreparedStatement stm = conn.prepareStatement(Statements.INSERT_STADIUM); conn.setAutoCommit(false); stm.setString(1, stadium.getName()); stm.setString(2, stadium.getCity()); stm.executeUpdate(); int id = getMaxId(); TribuneLogic logic = TribuneLogic.getInstance(); for (Tribune trib : stadium.getTribunes()) { int tribuneId = logic.addTribune(trib); if (tribuneId != -1) { stm = conn.prepareStatement(Statements.INSERT_STAD_TRIBUNE); stm.setInt(1, id); stm.setInt(2, tribuneId); stm.executeUpdate(); } } } catch (SQLException e) { try { conn.rollback(); conn.setAutoCommit(true); } catch (SQLException e1) { e1.printStackTrace(); } throw new StadiumException("Adding stadium failed", e); } try { conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } }
00
Code Sample 1: 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!"); } Code Sample 2: public TtsTrackImpl(URL url, String voiceName, VoicesCache vc) throws IOException { this.voiceCache = vc; isReady = false; URLConnection connection = url.openConnection(); frameSize = (int) (period * format.getChannels() * format.getSampleSizeInBits() * format.getSampleRate() / 8000); voice = voiceCache.allocateVoice(voiceName); TTSAudioBuffer audioBuffer = new TTSAudioBuffer(); this.voice.setAudioPlayer(audioBuffer); this.voice.speak(connection.getInputStream()); audioBuffer.flip(); }
11
Code Sample 1: 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!"); } Code Sample 2: public ResourceMigrator createDefaultResourceMigrator(NotificationReporter reporter, boolean strictMode) throws ResourceMigrationException { return new ResourceMigrator() { public void migrate(InputMetadata meta, InputStream inputStream, OutputCreator outputCreator) throws IOException, ResourceMigrationException { OutputStream outputStream = outputCreator.createOutputStream(); IOUtils.copy(inputStream, outputStream); } }; }
11
Code Sample 1: public static String md5hash(String data) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); return new BigInteger(1, digest.digest()).toString(16); } catch (NoSuchAlgorithmException e) { LOG.error(e); } return null; } Code Sample 2: public static String crypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } 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 final int copyFiles(File[] list, String dest, boolean dest_is_full_name) throws InterruptedException { Context c = ctx; File file = null; for (int i = 0; i < list.length; i++) { boolean existed = false; FileChannel in = null; FileChannel out = null; File outFile = null; file = list[i]; if (file == null) { error(c.getString(R.string.unkn_err)); break; } String uri = file.getAbsolutePath(); try { if (isStopReq()) { error(c.getString(R.string.canceled)); break; } long last_modified = file.lastModified(); String fn = file.getName(); outFile = dest_is_full_name ? new File(dest) : new File(dest, fn); if (file.isDirectory()) { if (depth++ > 40) { error(ctx.getString(R.string.too_deep_hierarchy)); break; } else if (outFile.exists() || outFile.mkdir()) { copyFiles(file.listFiles(), outFile.getAbsolutePath(), false); if (errMsg != null) break; } else error(c.getString(R.string.cant_md, outFile.getAbsolutePath())); depth--; } else { if (existed = outFile.exists()) { int res = askOnFileExist(c.getString(R.string.file_exist, outFile.getAbsolutePath()), commander); if (res == Commander.SKIP) continue; if (res == Commander.REPLACE) { if (outFile.equals(file)) continue; else outFile.delete(); } if (res == Commander.ABORT) break; } if (move) { long len = file.length(); if (file.renameTo(outFile)) { counter++; totalBytes += len; int so_far = (int) (totalBytes * conv); sendProgress(outFile.getName() + " " + c.getString(R.string.moved), so_far, 0); continue; } } in = new FileInputStream(file).getChannel(); out = new FileOutputStream(outFile).getChannel(); long size = in.size(); final long max_chunk = 524288; long pos = 0; long chunk = size > max_chunk ? max_chunk : size; long t_chunk = 0; long start_time = 0; int speed = 0; int so_far = (int) (totalBytes * conv); String sz_s = Utils.getHumanSize(size); String rep_s = c.getString(R.string.copying, fn); for (pos = 0; pos < size; ) { if (t_chunk == 0) start_time = System.currentTimeMillis(); sendProgress(rep_s + sizeOfsize(pos, sz_s), so_far, (int) (totalBytes * conv), speed); long transferred = in.transferTo(pos, chunk, out); pos += transferred; t_chunk += transferred; totalBytes += transferred; if (isStopReq()) { Log.d(TAG, "Interrupted!"); error(c.getString(R.string.canceled)); return counter; } long time_delta = System.currentTimeMillis() - start_time; if (time_delta > 0) { speed = (int) (1000 * t_chunk / time_delta); t_chunk = 0; } } in.close(); out.close(); in = null; out = null; if (i >= list.length - 1) sendProgress(c.getString(R.string.copied_f, fn) + sizeOfsize(pos, sz_s), (int) (totalBytes * conv)); counter++; } if (move) file.delete(); outFile.setLastModified(last_modified); final int GINGERBREAD = 9; if (android.os.Build.VERSION.SDK_INT >= GINGERBREAD) ForwardCompat.setFullPermissions(outFile); } catch (SecurityException e) { error(c.getString(R.string.sec_err, e.getMessage())); } catch (FileNotFoundException e) { error(c.getString(R.string.not_accs, e.getMessage())); } catch (ClosedByInterruptException e) { error(c.getString(R.string.canceled)); } catch (IOException e) { String msg = e.getMessage(); error(c.getString(R.string.acc_err, uri, msg != null ? msg : "")); } catch (RuntimeException e) { error(c.getString(R.string.rtexcept, uri, e.getMessage())); } finally { try { if (in != null) in.close(); if (out != null) out.close(); if (!move && errMsg != null && outFile != null && !existed) { Log.i(TAG, "Deleting failed output file"); outFile.delete(); } } catch (IOException e) { error(c.getString(R.string.acc_err, uri, e.getMessage())); } } } return counter; } Code Sample 2: protected final String H(String data) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(data.getBytes("UTF8")); byte[] bytes = digest.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { int aByte = bytes[i]; if (aByte < 0) aByte += 256; if (aByte < 16) sb.append('0'); sb.append(Integer.toHexString(aByte)); } return sb.toString(); }
11
Code Sample 1: @Transient private String md5sum(String text) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(text.getBytes()); byte messageDigest[] = md.digest(); return bufferToHex(messageDigest, 0, messageDigest.length); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } Code Sample 2: @Test public void testHandleMessageInvalidSignature() throws Exception { KeyPair keyPair = MiscTestUtils.generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null); ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class); Map<String, String> httpHeaders = new HashMap<String, String>(); HttpSession mockHttpSession = EasyMock.createMock(HttpSession.class); HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class); EasyMock.expect(mockServletConfig.getInitParameter("AuditService")).andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter("AuditServiceClass")).andStubReturn(AuditTestService.class.getName()); EasyMock.expect(mockServletConfig.getInitParameter("SignatureService")).andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter("SignatureServiceClass")).andStubReturn(SignatureTestService.class.getName()); EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("remote-address"); MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); byte[] document = "hello world".getBytes(); byte[] digestValue = messageDigest.digest(document); EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_VALUE_SESSION_ATTRIBUTE)).andStubReturn(digestValue); EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_ALGO_SESSION_ATTRIBUTE)).andStubReturn("SHA-1"); SignatureDataMessage message = new SignatureDataMessage(); message.certificateChain = new LinkedList<X509Certificate>(); message.certificateChain.add(certificate); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(keyPair.getPrivate()); signature.update("foobar-document".getBytes()); byte[] signatureValue = signature.sign(); message.signatureValue = signatureValue; EasyMock.replay(mockServletConfig, mockHttpSession, mockServletRequest); AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance); this.testedInstance.init(mockServletConfig); try { this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, mockHttpSession); fail(); } catch (ServletException e) { LOG.debug("expected exception: " + e.getMessage()); EasyMock.verify(mockServletConfig, mockHttpSession, mockServletRequest); assertNull(SignatureTestService.getSignatureValue()); assertEquals("remote-address", AuditTestService.getAuditSignatureRemoteAddress()); assertEquals(certificate, AuditTestService.getAuditSignatureClientCertificate()); } }
00
Code Sample 1: @Override public String post(final FetchInfos fetchInfos, final String data) throws HttpException { URL url = null; try { url = new URL(fetchInfos.getUri()); } catch (MalformedURLException exception) { throw new HttpException("uri is malformed '" + fetchInfos.getUri() + "'", exception); } HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); } catch (IOException exception) { fetchInfos.setResult(FETCHING_RESULT.IO_ERROR); throw new HttpException("get '" + fetchInfos.getUri() + "' failed", exception); } InputStream input = null; try { connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length)); final DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(data); wr.flush(); wr.close(); input = connection.getInputStream(); if ("gzip".equals(connection.getHeaderField("content-encoding"))) { input = new GZIPInputStream(input); } if (HttpServiceImpl.LOGGER.isDebugEnabled()) { this.logConnection(connection); input = new LoggingInputStream(input); } } catch (SocketTimeoutException exception) { fetchInfos.setResult(FETCHING_RESULT.TIME_OUT); throw new HttpException("get '" + fetchInfos.getUri() + "' timeout", exception); } catch (IOException exception) { fetchInfos.setResult(FETCHING_RESULT.IO_ERROR); throw new HttpException("get '" + fetchInfos.getUri() + "' failed", exception); } fetchInfos.setResult(FETCHING_RESULT.OK); String response = null; try { response = this.toString(input); } catch (IOException exception) { throw new HttpException("converting inputstream to string failed", exception); } return response; } Code Sample 2: public static boolean urlStrIsDir(String urlStr) { if (urlStr.endsWith("/")) return true; int lastSlash = urlStr.lastIndexOf('/'); int lastPeriod = urlStr.lastIndexOf('.'); if (lastPeriod != -1 && (lastSlash == -1 || lastPeriod > lastSlash)) return false; String urlStrWithSlash = urlStr + "/"; try { URL url = new URL(urlStrWithSlash); InputStream f = url.openStream(); f.close(); return true; } catch (Exception e) { return false; } }
00
Code Sample 1: private static void testIfNoneMatch() throws Exception { String eTag = c.getHeaderField("ETag"); InputStream in = c.getInputStream(); byte[] buffer = new byte[1024]; int read = 0; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); do { read = in.read(buffer); if (read > 0) md5.update(buffer, 0, read); } while (read < 0); byte[] digest = md5.digest(); String hexDigest = getHexString(digest); if (hexDigest.equals(eTag)) System.out.print("eTag content : md5 hex string"); String quotedHexDigest = "\"" + hexDigest + "\""; if (quotedHexDigest.equals(eTag)) System.out.print("eTag content : quoted md5 hex string"); HttpURLConnection c2 = (HttpURLConnection) url.openConnection(); c2.addRequestProperty("If-None-Match", eTag); c2.connect(); int code = c2.getResponseCode(); System.out.print("If-None-Match response: "); boolean supported = (code == 304); System.out.println(b2s(supported) + " - " + code + " (" + c2.getResponseMessage() + ")"); } Code Sample 2: @SuppressWarnings("rawtypes") public static String[] loadAllPropertiesFromClassLoader(Properties properties, String... resourceNames) throws IOException { List successLoadProperties = new ArrayList(); for (String resourceName : resourceNames) { URL url = GeneratorProperties.class.getResource(resourceName); if (url != null) { successLoadProperties.add(url.getFile()); InputStream input = null; try { URLConnection con = url.openConnection(); con.setUseCaches(false); input = con.getInputStream(); if (resourceName.endsWith(".xml")) { properties.loadFromXML(input); } else { properties.load(input); } } finally { if (input != null) { input.close(); } } } } return (String[]) successLoadProperties.toArray(new String[0]); }
00
Code Sample 1: private void createSoundbank(String testSoundbankFileName) throws Exception { System.out.println("Create soundbank"); File packageDir = new File("testsoundbank"); if (packageDir.exists()) { for (File file : packageDir.listFiles()) assertTrue(file.delete()); assertTrue(packageDir.delete()); } packageDir.mkdir(); String sourceFileName = "testsoundbank/TestSoundBank.java"; File sourceFile = new File(sourceFileName); FileWriter writer = new FileWriter(sourceFile); writer.write("package testsoundbank;\n" + "public class TestSoundBank extends com.sun.media.sound.ModelAbstractOscillator { \n" + " @Override public int read(float[][] buffers, int offset, int len) throws java.io.IOException { \n" + " return 0;\n" + " }\n" + " @Override public String getVersion() {\n" + " return \"" + (soundbankRevision++) + "\";\n" + " }\n" + "}\n"); writer.close(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("."))); compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile))).call(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testSoundbankFileName)); ZipEntry ze = new ZipEntry("META-INF/services/javax.sound.midi.Soundbank"); zos.putNextEntry(ze); zos.write("testsoundbank.TestSoundBank".getBytes()); ze = new ZipEntry("testsoundbank/TestSoundBank.class"); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream("testsoundbank/TestSoundBank.class"); int b = fis.read(); while (b != -1) { zos.write(b); b = fis.read(); } zos.close(); } Code Sample 2: public static String hashPassword(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); byte result[] = md5.digest("InTeRlOgY".getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < result.length; i++) { String s = Integer.toHexString(result[i]); int length = s.length(); if (length >= 2) { sb.append(s.substring(length - 2, length)); } else { sb.append("0"); sb.append(s); } } return "{md5}" + sb.toString(); } catch (NoSuchAlgorithmException e) { return password; } }
00
Code Sample 1: public int procesar() { int mas = 0; String uriOntologia = "", source = "", uri = ""; String fichOrigenHTML = "", fichOrigenLN = ""; String ficheroOutOWL = ""; md5 firma = null; StringTokenV2 entra = null, entra2 = null, entra3 = null; FileInputStream lengNat = null; BufferedInputStream lengNat2 = null; DataInputStream entradaLenguajeNatural = null; FileWriter salOWL = null; BufferedWriter salOWL2 = null; PrintWriter salidaOWL = null; String sujeto = "", verbo = "", CD = "", CI = "", fraseOrigen = ""; StringTokenV2 token2; boolean bandera = false; OntClass c = null; OntClass cBak = null; String claseTrabajo = ""; String nombreClase = "", nombrePropiedad = "", variasPalabras = ""; int incre = 0, emergencia = 0; String lineaSalida = ""; String[] ontologia = new String[5]; ontologia[0] = "http://www.criado.info/owl/vertebrados_es.owl#"; ontologia[1] = "http://www.w3.org/2001/sw/WebOnt/guide-src/wine#"; ontologia[2] = "http://www.co-ode.org/ontologies/pizza/2005/10/18/pizza.owl#"; ontologia[3] = "http://www.w3.org/2001/sw/WebOnt/guide-src/food#"; ontologia[4] = "http://www.daml.org/2001/01/gedcom/gedcom#"; String[] ontologiaSource = new String[5]; ontologiaSource[0] = this.directorioMapeo + "\\" + "mapeo_vertebrados_es.xml"; ontologiaSource[1] = this.directorioMapeo + "\\" + "mapeo_wine_es.xml"; ontologiaSource[2] = this.directorioMapeo + "\\" + "mapeo_pizza_es.xml"; ontologiaSource[3] = this.directorioMapeo + "\\" + "mapeo_food_es.xml"; ontologiaSource[4] = this.directorioMapeo + "\\" + "mapeo_parentesco_es.xml"; mapeoIdiomas clasesOntologias; try { if ((entrada = entradaFichero.readLine()) != null) { if (entrada.trim().length() > 10) { entrada2 = new StringTokenV2(entrada.trim(), "\""); if (entrada2.isIncluidaSubcadena("<fichero ontologia=")) { ontologiaOrigen = entrada2.getToken(2); fichOrigenHTML = entrada2.getToken(4); fichOrigenLN = entrada2.getToken(6); if (ontologiaOrigen.equals("VERTEBRADOS")) { source = ontologiaSource[0]; uriOntologia = ontologia[0]; } if (ontologiaOrigen.equals("WINE")) { source = ontologiaSource[1]; uriOntologia = ontologia[1]; } if (ontologiaOrigen.equals("PIZZA")) { source = ontologiaSource[2]; uriOntologia = ontologia[2]; } if (ontologiaOrigen.equals("FOOD")) { source = ontologiaSource[3]; uriOntologia = ontologia[3]; } if (ontologiaOrigen.equals("PARENTESCOS")) { source = ontologiaSource[4]; uriOntologia = ontologia[4]; } firma = new md5(uriOntologia, false); clasesOntologias = new mapeoIdiomas(source); uri = ""; ficheroOutOWL = ""; entra2 = new StringTokenV2(fichOrigenHTML, "\\"); int numToken = entra2.getNumeroTokenTotales(); entra = new StringTokenV2(fichOrigenHTML, " "); if (entra.isIncluidaSubcadena(directorioLocal)) { entra = new StringTokenV2(entra.getQuitar(directorioLocal) + "", " "); uri = entra.getCambiar("\\", "/"); uri = entra.getQuitar(entra2.getToken(numToken)) + ""; entra3 = new StringTokenV2(entra2.getToken(numToken), "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; uri = urlPatron + uri + ficheroOutOWL; } entra3 = new StringTokenV2(fichOrigenHTML, "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; lineaSalida = "<vistasemantica origen=\"" + fichOrigenLN + "\" destino=\"" + uri + "\" />"; lengNat = new FileInputStream(fichOrigenLN); lengNat2 = new BufferedInputStream(lengNat); entradaLenguajeNatural = new DataInputStream(lengNat2); salOWL = new FileWriter(ficheroOutOWL); salOWL2 = new BufferedWriter(salOWL); salidaOWL = new PrintWriter(salOWL2); while ((entradaInstancias = entradaLenguajeNatural.readLine()) != null) { sujeto = ""; verbo = ""; CD = ""; CI = ""; fraseOrigen = ""; if (entradaInstancias.trim().length() > 10) { entrada2 = new StringTokenV2(entradaInstancias.trim(), "\""); if (entrada2.isIncluidaSubcadena("<oracion sujeto=")) { sujeto = entrada2.getToken(2).trim(); verbo = entrada2.getToken(4).trim(); CD = entrada2.getToken(6).trim(); CI = entrada2.getToken(8).trim(); fraseOrigen = entrada2.getToken(10).trim(); if (sujeto.length() > 0 & verbo.length() > 0 & CD.length() > 0) { bandera = false; c = null; cBak = null; nombreClase = clasesOntologias.getClaseInstancia(CD); if (nombreClase.length() > 0) { bandera = true; } if (bandera) { if (incre == 0) { salidaOWL.write(" <rdf:RDF " + "\n"); salidaOWL.write(" xmlns:j.0=\"" + uriOntologia + "\"" + "\n"); salidaOWL.write(" xmlns:protege=\"http://protege.stanford.edu/plugins/owl/protege#\"" + "\n"); salidaOWL.write(" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"" + "\n"); salidaOWL.write(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"" + "\n"); salidaOWL.write(" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"" + "\n"); salidaOWL.write(" xmlns:owl=\"http://www.w3.org/2002/07/owl#\" " + "\n"); salidaOWL.write(" xmlns=\"" + uri + "#\"" + "\n"); salidaOWL.write(" xml:base=\"" + uri + "\">" + "\n"); salidaOWL.write(" <owl:Ontology rdf:about=\"\">" + "\n"); salidaOWL.write(" <owl:imports rdf:resource=\"" + uriOntologia + "\"/>" + "\n"); salidaOWL.write(" </owl:Ontology>" + "\n"); salidaOWL.flush(); salida.write(lineaSalida + "\n"); salida.flush(); incre = 1; } salidaOWL.write(" <j.0:" + nombreClase + " rdf:ID=\"" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" <owl:AllDifferent>" + "\n"); salidaOWL.write(" <owl:distinctMembers rdf:parseType=\"Collection\">" + "\n"); salidaOWL.write(" <" + nombreClase + " rdf:about=\"#" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" </owl:distinctMembers>" + "\n"); salidaOWL.write(" </owl:AllDifferent>" + "\n"); salidaOWL.flush(); bandera = false; } } } } } salidaOWL.write(" </rdf:RDF>" + "\n" + "\n"); salidaOWL.write("<!-- Creado por [html2ws] http://www.luis.criado.org -->" + "\n"); salidaOWL.flush(); } } mas = 1; } else { salida.write("</listaVistasSemanticas>\n"); salida.flush(); salida.close(); bw2.close(); fw2.close(); salidaOWL.close(); entradaFichero.close(); ent2.close(); ent1.close(); mas = -1; } } catch (Exception e) { mas = -2; salida.write("No se encuentra: " + fichOrigen + "\n"); salida.flush(); } return mas; } Code Sample 2: public String md5(String string) throws GeneralSecurityException { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(string.getBytes()); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString(); }
00
Code Sample 1: public List<String[]> getCSV(String name) { return new ResourceLoader<List<String[]>>(name) { @Override protected List<String[]> get(URL url) throws Exception { CSVReader reader = null; try { reader = new CSVReader(new InputStreamReader(url.openStream())); return reader.readAll(); } finally { IOUtils.closeQuietly(reader); } } }.get(); } Code Sample 2: public static String machineInfo() { StringBuilder machineInfo = new StringBuilder(); try { Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement(); if ("eth0".equals(networkInterface.getDisplayName())) { for (byte b : networkInterface.getHardwareAddress()) { StringTools.appendWithDelimiter(machineInfo, String.format("%02x", b).toUpperCase(), ":"); } machineInfo.append("\n"); break; } } } catch (IOException x) { System.out.println("LicenseTools.machineInfo: " + x.getMessage()); x.printStackTrace(); } if (machineInfo.length() == 0) { return null; } String info = machineInfo.toString(); try { MessageDigest messageDigest = MessageDigest.getInstance("MD5", "SUN"); messageDigest.update(info.getBytes()); byte[] md5 = messageDigest.digest(info.getBytes()); return new String(Base64.encodeBase64(md5)); } catch (Exception x) { System.out.println("LicenseTools.machineInfo: " + x.getMessage()); x.printStackTrace(); } return null; }
11
Code Sample 1: public void addUser(String username, String password, String filename) { String data = ""; try { open(filename); MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer encPasswd = new StringBuffer(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); data = username + " " + encPasswd + "\r\n"; } try { long length = file.length(); file.seek(length); file.write(data.getBytes()); } catch (IOException ex) { ex.printStackTrace(); } close(); } catch (NoSuchAlgorithmException ex) { } } Code Sample 2: protected static String encodePassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); return HexString.bufferToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
00
Code Sample 1: public static String encrypt(String plaintext) throws NoSuchAlgorithmException { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { logger.error("unable to encrypt password" + e.getMessage()); throw new NoSuchAlgorithmException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { logger.error("unable to encrypt password" + e.getMessage()); throw new NoSuchAlgorithmException(e.getMessage()); } byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); } Code Sample 2: public static String move_files(String sessionid, String keys, String absolutePathForTheDestinationTag) { String resultJsonString = "some problem existed inside the create_new_tag() function if you see this string"; try { Log.d("current running function name:", "move_files"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "move_file")); nameValuePairs.add(new BasicNameValuePair("absolute_new_parent_tag", absolutePathForTheDestinationTag)); nameValuePairs.add(new BasicNameValuePair("keys", keys)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); resultJsonString = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", resultJsonString); return resultJsonString; } catch (Exception e) { e.printStackTrace(); } return resultJsonString; }
11
Code Sample 1: public String getWebPage(String url) { String content = ""; URL urlObj = null; try { urlObj = new URL(url); } catch (MalformedURLException urlEx) { urlEx.printStackTrace(); throw new Error("URL creation failed."); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream())); String line; while ((line = reader.readLine()) != null) { content += line; } } catch (IOException e) { e.printStackTrace(); throw new Error("Page retrieval failed."); } return content; } Code Sample 2: public void loadFromFile() { if (filename == null) return; try { BufferedReader reader; try { File file = new File(filename); if (!file.exists()) return; reader = new BufferedReader(new FileReader(file)); } catch (java.security.AccessControlException e) { URL url = new URL(filename); reader = new BufferedReader(new InputStreamReader(url.openStream())); } String line; while (true) { line = reader.readLine(); if (line == null) break; String name = line.substring(0, line.indexOf("\t")); String rest1 = line.substring(line.indexOf("\t") + 1); String guiname = rest1.substring(0, rest1.indexOf("\t")); String rest2 = rest1.substring(rest1.indexOf("\t") + 1); String type = rest2.substring(0, rest2.indexOf("\t")); String value = rest2.substring(rest2.indexOf("\t") + 1); defineField(name, guiname, type); setField(name, value, true); } reader.close(); } catch (IOException e) { throw new JGameError("Error reading file '" + filename + "'.", false); } }
00
Code Sample 1: public static String hashPassword(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); byte result[] = md5.digest("InTeRlOgY".getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < result.length; i++) { String s = Integer.toHexString(result[i]); int length = s.length(); if (length >= 2) { sb.append(s.substring(length - 2, length)); } else { sb.append("0"); sb.append(s); } } return "{md5}" + sb.toString(); } catch (NoSuchAlgorithmException e) { return password; } } Code Sample 2: public ProjectDeploymentConfiguration deleteProjectDeploymentConfig(int id) throws AdaptationException { ProjectDeploymentConfiguration config = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProjectDeploymentConfigurations " + "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 project deployment " + "configuration failed."; log.error(msg); throw new AdaptationException(msg); } config = getProjectDeploymentConfiguration(resultSet); query = "DELETE FROM ProjectDeploymentConfigurations " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProjectDeploymentConfig"; 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 config; }
00
Code Sample 1: public Configuration load(URL url) throws ConfigurationException { LOG.info("Configuring from url : " + url.toString()); try { return load(url.openStream(), url.toString()); } catch (IOException ioe) { throw new ConfigurationException("Could not configure from URL : " + url, ioe); } } Code Sample 2: public static boolean compress(File source, File target, Manifest manifest) { try { if (!(source.exists() & source.isDirectory())) return false; if (target.exists()) target.delete(); ZipOutputStream output = null; boolean isJar = target.getName().toLowerCase().endsWith(".jar"); if (isJar) { File manifestDir = new File(source, "META-INF"); remove(manifestDir); if (manifest != null) output = new JarOutputStream(new FileOutputStream(target), manifest); else output = new JarOutputStream(new FileOutputStream(target)); } else output = new ZipOutputStream(new FileOutputStream(target)); ArrayList list = getContents(source); String baseDir = source.getAbsolutePath().replace('\\', '/'); if (!baseDir.endsWith("/")) baseDir = baseDir + "/"; int baseDirLength = baseDir.length(); byte[] buffer = new byte[1024]; int bytesRead; for (int i = 0, n = list.size(); i < n; i++) { File file = (File) list.get(i); FileInputStream f_in = new FileInputStream(file); String filename = file.getAbsolutePath().replace('\\', '/'); if (filename.startsWith(baseDir)) filename = filename.substring(baseDirLength); if (isJar) output.putNextEntry(new JarEntry(filename)); else output.putNextEntry(new ZipEntry(filename)); while ((bytesRead = f_in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); f_in.close(); output.closeEntry(); } output.close(); } catch (Exception exc) { exc.printStackTrace(); return false; } return true; }
00
Code Sample 1: protected void removeMessage(ReplicationMessage message) { logger.info(String.format("remove replication message: %d", message.getId())); ConnectionProvider cp = null; Connection conn = null; PreparedStatement ps = null; try { SessionFactoryImplementor impl = (SessionFactoryImplementor) portalDao.getSessionFactory(); cp = impl.getConnectionProvider(); conn = cp.getConnection(); conn.setAutoCommit(false); ps = conn.prepareStatement("delete from light_replication_message where id=?"); ps.setLong(1, message.getId()); ps.executeUpdate(); conn.commit(); ps.close(); conn.close(); } catch (Exception e) { try { conn.rollback(); ps.close(); conn.close(); } catch (Exception se) { } } } Code Sample 2: static String fetchURLComposeExternPackageList(String urlpath, String pkglisturlpath) { String link = pkglisturlpath + "package-list"; try { boolean relative = isRelativePath(urlpath); readPackageList((new URL(link)).openStream(), urlpath, relative); } catch (MalformedURLException exc) { return getText("doclet.MalformedURL", link); } catch (IOException exc) { return getText("doclet.URL_error", link); } return null; }
11
Code Sample 1: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } Code Sample 2: @Override public void fileUpload(UploadEvent uploadEvent) { FileOutputStream tmpOutStream = null; try { tmpUpload = File.createTempFile("projectImport", ".xml"); tmpOutStream = new FileOutputStream(tmpUpload); IOUtils.copy(uploadEvent.getInputStream(), tmpOutStream); panel.setGeneralMessage("Project file " + uploadEvent.getFileName() + " uploaded and ready for import."); } catch (Exception e) { panel.setGeneralMessage("Could not upload file: " + e); } finally { if (tmpOutStream != null) { IOUtils.closeQuietly(tmpOutStream); } } }
00
Code Sample 1: public static JSONObject doJSONQuery(String urlstr) throws IOException, MalformedURLException, JSONException, SolrException { URL url = new URL(urlstr); HttpURLConnection con = null; try { con = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuffer buffer = new StringBuffer(); String str; while ((str = in.readLine()) != null) { buffer.append(str + "\n"); } in.close(); JSONObject response = new JSONObject(buffer.toString()); return response; } catch (IOException e) { if (con != null) { try { int statusCode = con.getResponseCode(); if (statusCode >= 400) { throw (new SolrSelectUtils()).new SolrException(statusCode); } } catch (IOException exc) { } } throw (e); } } Code Sample 2: public static String rename_file(String sessionid, String key, String newFileName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_file"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_file")); nameValuePairs.add(new BasicNameValuePair("new_name", newFileName)); nameValuePairs.add(new BasicNameValuePair("key", key)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
00
Code Sample 1: private String xifraPassword() throws Exception { String password2 = instance.getUsuaris().getPassword2(); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(password2.getBytes(), 0, password2.length()); password2 = new BigInteger(1, m.digest()).toString(16); return password2; } Code Sample 2: public static JSONObject fromUrl(String url) throws Throwable { Validate.notEmpty(url); InputStream stream = null; HttpClient httpclient = null; try { httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); if (response != null) { HttpEntity entity = response.getEntity(); if (entity != null) { try { stream = entity.getContent(); return fromStream(stream); } finally { try { if (stream != null) stream.close(); } catch (Exception ex) { } } } } } catch (Throwable tr) { Logger.e(TAG, "fromUrl", tr); throw tr; } finally { if (httpclient != null) httpclient.getConnectionManager().shutdown(); } return null; }
11
Code Sample 1: @Test public void testLargePut() throws Throwable { int size = CommonParameters.BLOCK_SIZE; InputStream is = new FileInputStream(_fileName); RepositoryFileOutputStream ostream = new RepositoryFileOutputStream(_nodeName, _putHandle, CommonParameters.local); int readLen = 0; int writeLen = 0; byte[] buffer = new byte[CommonParameters.BLOCK_SIZE]; while ((readLen = is.read(buffer, 0, size)) != -1) { ostream.write(buffer, 0, readLen); writeLen += readLen; } ostream.close(); CCNStats stats = _putHandle.getNetworkManager().getStats(); Assert.assertEquals(0, stats.getCounter("DeliverInterestFailed")); } Code Sample 2: public boolean doUpload(int count) { String objFileName = Long.toString(new java.util.Date().getTime()) + Integer.toString(count); try { this.objectFileName[count] = objFileName + "_bak." + this.sourceFileExt[count]; File objFile = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); if (objFile.exists()) { this.doUpload(count); } else { objFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(objFile); BufferedOutputStream bos = new BufferedOutputStream(fos); int readLength = 0; int offset = 0; String str = ""; long readSize = 0L; while ((readLength = this.inStream.readLine(this.b, 0, this.b.length)) != -1) { str = new String(this.b, 0, readLength); if (str.indexOf("Content-Type:") != -1) { break; } } this.inStream.readLine(this.b, 0, this.b.length); while ((readLength = this.inStream.readLine(this.b, 0, b.length)) != -1) { str = new String(this.b, 0, readLength); if (this.b[0] == 45 && this.b[1] == 45 && this.b[2] == 45 && this.b[3] == 45 && this.b[4] == 45) { break; } bos.write(this.b, 0, readLength); readSize += readLength; if (readSize > this.size) { this.fileMessage[count] = "�ϴ��ļ������ļ���С�������ƣ�"; this.ok = false; break; } } if (this.ok) { bos.flush(); bos.close(); int fileLength = (int) (objFile.length()); byte[] bb = new byte[fileLength - 2]; FileInputStream fis = new FileInputStream(objFile); BufferedInputStream bis = new BufferedInputStream(fis); bis.read(bb, 0, (fileLength - 2)); fis.close(); bis.close(); this.objectFileName[count] = objFileName + "." + this.sourceFileExt[count]; File ok_file = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); ok_file.createNewFile(); BufferedOutputStream bos_ok = new BufferedOutputStream(new FileOutputStream(ok_file)); bos_ok.write(bb); bos_ok.close(); objFile.delete(); this.fileMessage[count] = "OK"; return true; } else { bos.flush(); bos.close(); File delFile = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); delFile.delete(); this.objectFileName[count] = "none"; return false; } } catch (Exception e) { this.objectFileName[count] = "none"; this.fileMessage[count] = e.toString(); return false; } }
00
Code Sample 1: public void deletePortletName(PortletNameBean portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (portletNameBean.getPortletId() == null) throw new IllegalArgumentException("portletNameId is null"); String sql = "delete from WM_PORTAL_PORTLET_NAME " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } Code Sample 2: public static Map<VariableLengthInteger, ElementDescriptor> readDescriptors(URL url) throws IOException, XMLStreamException { if (url == null) { throw new IllegalArgumentException("url is null"); } InputStream stream = new BufferedInputStream(url.openStream()); try { return readDescriptors(stream); } finally { try { stream.close(); } catch (IOException ignored) { } } }
00
Code Sample 1: public static String sha256(String str) { StringBuffer buf = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] data = new byte[64]; md.update(str.getBytes("iso-8859-1"), 0, str.length()); data = md.digest(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } } catch (Exception e) { errorLog("{Malgn.sha256} " + e.getMessage()); } return buf.toString(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: static boolean generateKey() throws NoSuchAlgorithmException { java.util.Random rand = new Random(reg_name.hashCode() + System.currentTimeMillis()); DecimalFormat vf = new DecimalFormat("000"); ccKey = keyProduct + FIELD_SEPERATOR + keyType + FIELD_SEPERATOR + keyQuantity + FIELD_SEPERATOR + vf.format(lowMajorVersion) + FIELD_SEPERATOR + vf.format(lowMinorVersion) + FIELD_SEPERATOR + vf.format(highMajorVersion) + FIELD_SEPERATOR + vf.format(highMinorVersion) + FIELD_SEPERATOR + reg_name + FIELD_SEPERATOR + Integer.toHexString(rand.nextInt()).toUpperCase(); byte[] md5; MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(ccKey.getBytes()); md.update(FIELD_SEPERATOR.getBytes()); md.update(zuonicsPassword.getBytes()); md5 = md.digest(); userKey = ccKey + FIELD_SEPERATOR; for (int i = 0; i < md5.length; i++) userKey += Integer.toHexString(md5[i]).toUpperCase(); return true; } Code Sample 2: private static String getSuitableWCSVersion(String host, String _version) throws ConnectException, IOException { String request = WCSProtocolHandler.buildCapabilitiesSuitableVersionRequest(host, _version); String version = new String(); StringReader reader = null; DataInputStream dis = null; try { URL url = new URL(request); byte[] buffer = new byte[1024]; dis = new DataInputStream(url.openStream()); dis.readFully(buffer); reader = new StringReader(new String(buffer)); KXmlParser kxmlParser = null; kxmlParser = new KXmlParser(); kxmlParser.setInput(reader); kxmlParser.nextTag(); if (kxmlParser.getEventType() != KXmlParser.END_DOCUMENT) { if ((kxmlParser.getName().compareTo(CapabilitiesTags.WCS_CAPABILITIES_ROOT1_0_0) == 0)) { version = kxmlParser.getAttributeValue("", CapabilitiesTags.VERSION); } } reader.close(); dis.close(); return version; } catch (ConnectException conEx) { throw new ConnectException(conEx.getMessage()); } catch (IOException ioEx) { throw new IOException(ioEx.getMessage()); } catch (XmlPullParserException xmlEx) { xmlEx.printStackTrace(); return ""; } finally { if (reader != null) { try { reader.close(); } catch (Exception ex) { ex.printStackTrace(); } } if (dis != null) { try { dis.close(); } catch (Exception ex) { ex.printStackTrace(); } } } }
00
Code Sample 1: public void reload() throws SAXException, IOException { if (url != null) { java.io.InputStream is = url.openStream(); configDoc = builder.parse(is); is.close(); System.out.println("XML config file read correctly from " + url); } else { configDoc = builder.parse(configFile); System.out.println("XML config file read correctly from " + configFile); } } Code Sample 2: public void update(String target, String cfgVersion) throws MalformedURLException, FileNotFoundException, IOException { Debug.log("Config Updater", "Checking for newer configuration..."); URL url = new URL(target); String[] urlSplit = target.split("/"); this.fileName = urlSplit[urlSplit.length - 1]; BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(Main.getHomeDir() + "tmp-" + this.fileName)); URLConnection urlConnection = url.openConnection(); InputStream in = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int numRead; int fileSize = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); fileSize += numRead; } Debug.log("Config Updater", "Read latest configuration: " + fileSize + " bytes"); in.close(); out.close(); XMLController xmlC = new XMLController(); String newFileVersion = xmlC.readCfgVersion(Main.getHomeDir() + "tmp-" + this.fileName); if (new File(Main.getHomeDir() + this.fileName).exists()) { Debug.log("Config Updater", "Local configfile '" + Main.getHomeDir() + this.fileName + "' exists (version " + cfgVersion + ")"); if (Double.parseDouble(newFileVersion) > Double.parseDouble(cfgVersion)) { Debug.log("Config Updater", "Removing old config and replacing it with version " + newFileVersion); new File(Main.getHomeDir() + this.fileName).delete(); new File(Main.getHomeDir() + "tmp-" + this.fileName).renameTo(new File(Main.getHomeDir() + this.fileName)); this.result = "ConfigFile upgraded to version " + newFileVersion; } else { new File(Main.getHomeDir() + "tmp-" + this.fileName).delete(); Debug.log("Config Updater", "I already have the latest version " + cfgVersion); } } else { Debug.log("Config Updater", "Local config doesn't exist. Loading the new one, version " + newFileVersion); new File(Main.getHomeDir() + "tmp-" + this.fileName).renameTo(new File(Main.getHomeDir() + this.fileName)); this.result = "ConfigFile upgraded to version " + newFileVersion; } Debug.log("Config Updater", "Update of configuration done"); }
11
Code Sample 1: protected void copyAndDelete(final URL _src, final long _temp) throws IOException { final File storage = getStorageFile(_src, _temp); final File dest = new File(_src.getFile()); FileChannel in = null; FileChannel out = null; if (storage.equals(dest)) { return; } try { readWriteLock_.lockWrite(); if (dest.exists()) { dest.delete(); } if (storage.exists() && !storage.renameTo(dest)) { in = new FileInputStream(storage).getChannel(); out = new FileOutputStream(dest).getChannel(); final long len = in.size(); final long copied = out.transferFrom(in, 0, in.size()); if (len != copied) { throw new IOException("unable to complete write"); } } } finally { readWriteLock_.unlockWrite(); try { if (in != null) { in.close(); } } catch (final IOException _evt) { FuLog.error(_evt); } try { if (out != null) { out.close(); } } catch (final IOException _evt) { FuLog.error(_evt); } storage.delete(); } } Code Sample 2: private static void copyFile(File source, File destination) throws IOException, SecurityException { if (!destination.exists()) destination.createNewFile(); FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); destinationChannel = new FileOutputStream(destination).getChannel(); long count = 0; long size = sourceChannel.size(); while ((count += destinationChannel.transferFrom(sourceChannel, 0, size - count)) < size) ; } finally { if (sourceChannel != null) sourceChannel.close(); if (destinationChannel != null) destinationChannel.close(); } }
00
Code Sample 1: private String readLine(final String urlStr) { BufferedReader reader; String line = null; try { URL url = new URL(urlStr); reader = new BufferedReader(new InputStreamReader(url.openStream())); line = reader.readLine(); } catch (MalformedURLException e) { log.error(e, e); } catch (IOException e) { log.error(e, e); } return line; } Code Sample 2: public void save() { final JFileChooser fc = new JFileChooser(); fc.setFileFilter(new FileFilter() { public String getDescription() { return "PDF File"; } public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".pdf"); } }); if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) { return; } File targetFile = fc.getSelectedFile(); if (!targetFile.getName().toLowerCase().endsWith(".pdf")) { targetFile = new File(targetFile.getParentFile(), targetFile.getName() + ".pdf"); } if (targetFile.exists()) { if (JOptionPane.showConfirmDialog(this, "Do you want to overwrite the file?") != JOptionPane.YES_OPTION) { return; } } try { final InputStream is = new FileInputStream(filename); try { final OutputStream os = new FileOutputStream(targetFile); try { final byte[] buffer = new byte[32768]; for (int read; (read = is.read(buffer)) != -1; ) { os.write(buffer, 0, read); } } finally { os.close(); } } finally { is.close(); } } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static void copyFile(File sourceFile, File destinationFile) throws IOException { if (!destinationFile.exists()) { destinationFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public void actionPerformed(ActionEvent e) { if (saveForWebChooser == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("HTML files"); fileFilter.addExtension("html"); saveForWebChooser = new JFileChooser(); saveForWebChooser.setFileFilter(fileFilter); saveForWebChooser.setDialogTitle("Save for Web..."); saveForWebChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentSaveForWebDirectory"))); } if (saveForWebChooser.showSaveDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentSaveForWebDirectory", saveForWebChooser.getCurrentDirectory().getAbsolutePath()); File pathFile = saveForWebChooser.getSelectedFile().getParentFile(); String name = saveForWebChooser.getSelectedFile().getName(); if (!name.toLowerCase().endsWith(".html") && name.indexOf('.') == -1) { name = name + ".html"; } String resource = MIDletClassLoader.getClassResourceName(this.getClass().getName()); URL url = this.getClass().getClassLoader().getResource(resource); String path = url.getPath(); int prefix = path.indexOf(':'); String mainJarFileName = path.substring(prefix + 1, path.length() - resource.length()); File appletJarDir = new File(new File(mainJarFileName).getParent(), "lib"); File appletJarFile = new File(appletJarDir, "microemu-javase-applet.jar"); if (!appletJarFile.exists()) { appletJarFile = null; } if (appletJarFile == null) { } if (appletJarFile == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("JAR packages"); fileFilter.addExtension("jar"); JFileChooser appletChooser = new JFileChooser(); appletChooser.setFileFilter(fileFilter); appletChooser.setDialogTitle("Select MicroEmulator applet jar package..."); appletChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentAppletJarDirectory"))); if (appletChooser.showOpenDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentAppletJarDirectory", appletChooser.getCurrentDirectory().getAbsolutePath()); appletJarFile = appletChooser.getSelectedFile(); } else { return; } } JadMidletEntry jadMidletEntry; Iterator it = common.jad.getMidletEntries().iterator(); if (it.hasNext()) { jadMidletEntry = (JadMidletEntry) it.next(); } else { Message.error("MIDlet Suite has no entries"); return; } String midletInput = common.jad.getJarURL(); DeviceEntry deviceInput = selectDevicePanel.getSelectedDeviceEntry(); if (deviceInput != null && deviceInput.getDescriptorLocation().equals(DeviceImpl.DEFAULT_LOCATION)) { deviceInput = null; } File htmlOutputFile = new File(pathFile, name); if (!allowOverride(htmlOutputFile)) { return; } File appletPackageOutputFile = new File(pathFile, "microemu-javase-applet.jar"); if (!allowOverride(appletPackageOutputFile)) { return; } File midletOutputFile = new File(pathFile, midletInput.substring(midletInput.lastIndexOf("/") + 1)); if (!allowOverride(midletOutputFile)) { return; } File deviceOutputFile = null; String deviceDescriptorLocation = null; if (deviceInput != null) { deviceOutputFile = new File(pathFile, deviceInput.getFileName()); if (!allowOverride(deviceOutputFile)) { return; } deviceDescriptorLocation = deviceInput.getDescriptorLocation(); } try { AppletProducer.createHtml(htmlOutputFile, (DeviceImpl) DeviceFactory.getDevice(), jadMidletEntry.getClassName(), midletOutputFile, appletPackageOutputFile, deviceOutputFile); AppletProducer.createMidlet(new URL(midletInput), midletOutputFile); IOUtils.copyFile(appletJarFile, appletPackageOutputFile); if (deviceInput != null) { IOUtils.copyFile(new File(Config.getConfigPath(), deviceInput.getFileName()), deviceOutputFile); } } catch (IOException ex) { Logger.error(ex); } } }
00
Code Sample 1: @Override public void run() { try { status = UploadStatus.INITIALISING; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://www.filedropper.com"); httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2 GTBDFff GTB7.0"); HttpResponse httpresponse = httpclient.execute(httpget); httpresponse.getEntity().consumeContent(); httppost = new HttpPost("http://www.filedropper.com/index.php?xml=true"); httppost.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2 GTBDFff GTB7.0"); MultipartEntity requestEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); requestEntity.addPart("file", new MonitoredFileBody(file, uploadProgress)); requestEntity.addPart("Upload", new StringBody("Submit Query")); httppost.setEntity(requestEntity); status = UploadStatus.UPLOADING; httpresponse = httpclient.execute(httppost); String strResponse = EntityUtils.toString(httpresponse.getEntity()); status = UploadStatus.GETTINGLINK; downURL = "http://www.filedropper.com/" + strResponse.substring(strResponse.lastIndexOf("=") + 1); NULogger.getLogger().info(downURL); uploadFinished(); } catch (Exception ex) { ex.printStackTrace(); NULogger.getLogger().severe(ex.toString()); uploadFailed(); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { String name = metadata.get(Metadata.RESOURCE_NAME_KEY); if (name != null && wanted.containsKey(name)) { FileOutputStream out = new FileOutputStream(wanted.get(name)); IOUtils.copy(stream, out); out.close(); } else { if (downstreamParser != null) { downstreamParser.parse(stream, handler, metadata, context); } } } Code Sample 2: public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
00
Code Sample 1: public DialogueSymbole(final JFrame jframe, final Element el, final String srcAttr) { super(jframe, JaxeResourceBundle.getRB().getString("symbole.Insertion"), true); this.jframe = jframe; this.el = el; final String nomf = el.getAttribute(srcAttr); boolean applet = false; try { final File dossierSymboles = new File("symboles"); if (!dossierSymboles.exists()) { JOptionPane.showMessageDialog(jframe, JaxeResourceBundle.getRB().getString("erreur.SymbolesNonTrouve"), JaxeResourceBundle.getRB().getString("erreur.Erreur"), JOptionPane.ERROR_MESSAGE); return; } liste = chercherImages(dossierSymboles); } catch (AccessControlException ex) { applet = true; try { final URL urlListe = DialogueSymbole.class.getClassLoader().getResource("symboles/liste.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(urlListe.openStream())); final ArrayList<File> listeImages = new ArrayList<File>(); String ligne = null; while ((ligne = in.readLine()) != null) { if (!"".equals(ligne.trim())) listeImages.add(new File("symboles/" + ligne.trim())); } liste = listeImages.toArray(new File[listeImages.size()]); } catch (IOException ex2) { LOG.error(ex2); } } final JPanel cpane = new JPanel(new BorderLayout()); setContentPane(cpane); final GridLayout grille = new GridLayout((int) Math.ceil(liste.length / 13.0), 13, 10, 10); final JPanel spane = new JPanel(grille); cpane.add(spane, BorderLayout.CENTER); ichoix = 0; final MyMouseListener ecouteur = new MyMouseListener(); labels = new JLabel[liste.length]; for (int i = 0; i < liste.length; i++) { if (nomf != null && !"".equals(nomf) && nomf.equals(liste[i].getPath())) ichoix = i; URL urlIcone; try { if (applet) { final URL urlListe = DialogueSymbole.class.getClassLoader().getResource("symboles/liste.txt"); final String baseURL = urlListe.toString().substring(0, urlListe.toString().indexOf("symboles/liste.txt")); urlIcone = new URL(baseURL + liste[i].getPath()); } else urlIcone = liste[i].toURL(); } catch (MalformedURLException ex) { LOG.error(ex); break; } final Icon ic = new ImageIcon(urlIcone); final JLabel label = new JLabel(ic); label.addMouseListener(ecouteur); labels[i] = label; spane.add(label); } final JPanel bpane = new JPanel(new FlowLayout(FlowLayout.RIGHT)); final JButton boutonAnnuler = new JButton(JaxeResourceBundle.getRB().getString("bouton.Annuler")); boutonAnnuler.addActionListener(this); boutonAnnuler.setActionCommand("Annuler"); bpane.add(boutonAnnuler); final JButton boutonOK = new JButton(JaxeResourceBundle.getRB().getString("bouton.OK")); boutonOK.addActionListener(this); boutonOK.setActionCommand("OK"); bpane.add(boutonOK); cpane.add(bpane, BorderLayout.SOUTH); getRootPane().setDefaultButton(boutonOK); choix(ichoix); pack(); if (jframe != null) { final Rectangle r = jframe.getBounds(); setLocation(r.x + r.width / 4, r.y + r.height / 4); } else { final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screen.width - getSize().width) / 3, (screen.height - getSize().height) / 3); } } Code Sample 2: @SuppressWarnings("finally") private void compress(File src) throws IOException { if (this.switches.contains(Switch.test)) return; checkSourceFile(src); if (src.getPath().endsWith(".bz2")) { this.log.println("WARNING: skipping file because it already has .bz2 suffix:").println(src); return; } final File dst = new File(src.getPath() + ".bz2").getAbsoluteFile(); if (!checkDestFile(dst)) return; FileChannel inChannel = null; FileChannel outChannel = null; FileOutputStream fileOut = null; BZip2OutputStream bzOut = null; FileLock inLock = null; FileLock outLock = null; try { inChannel = new FileInputStream(src).getChannel(); final long inSize = inChannel.size(); inLock = inChannel.tryLock(0, inSize, true); if (inLock == null) throw error("source file locked by another process: " + src); fileOut = new FileOutputStream(dst); outChannel = fileOut.getChannel(); bzOut = new BZip2OutputStream( new BufferedXOutputStream(fileOut, 8192), Math.min( (this.blockSize == -1) ? BZip2OutputStream.MAX_BLOCK_SIZE : this.blockSize, BZip2OutputStream.chooseBlockSize(inSize) ) ); outLock = outChannel.tryLock(); if (outLock == null) throw error("destination file locked by another process: " + dst); final boolean showProgress = this.switches.contains(Switch.showProgress); long pos = 0; int progress = 0; if (showProgress || this.verbose) { this.log.print("source: " + src).print(": size=").println(inSize); this.log.println("target: " + dst); } while (true) { final long maxStep = showProgress ? Math.max(8192, (inSize - pos) / MAX_PROGRESS) : (inSize - pos); if (maxStep <= 0) { if (showProgress) { for (int i = progress; i < MAX_PROGRESS; i++) this.log.print('#'); this.log.println(" done"); } break; } else { final long step = inChannel.transferTo(pos, maxStep, bzOut); if ((step == 0) && (inChannel.size() != inSize)) throw error("file " + src + " has been modified concurrently by another process"); pos += step; if (showProgress) { final double p = (double) pos / (double) inSize; final int newProgress = (int) (MAX_PROGRESS * p); for (int i = progress; i < newProgress; i++) this.log.print('#'); progress = newProgress; } } } inLock.release(); inChannel.close(); bzOut.closeInstance(); final long outSize = outChannel.position(); outChannel.truncate(outSize); outLock.release(); fileOut.close(); if (this.verbose) { final double ratio = (inSize == 0) ? (outSize * 100) : ((double) outSize / (double) inSize); this.log.print("raw size: ").print(inSize) .print("; compressed size: ").print(outSize) .print("; compression ratio: ").print(ratio).println('%'); } if (!this.switches.contains(Switch.keep)) { if (!src.delete()) throw error("unable to delete sourcefile: " + src); } } catch (final IOException ex) { IO.tryClose(inChannel); IO.tryClose(bzOut); IO.tryClose(fileOut); IO.tryRelease(inLock); IO.tryRelease(outLock); try { this.log.println(); } finally { throw ex; } } }
11
Code Sample 1: public static boolean copy(File source, File target, boolean owrite) { if (!source.exists()) { log.error("Invalid input to copy: source " + source + "doesn't exist"); return false; } else if (!source.isFile()) { log.error("Invalid input to copy: source " + source + "isn't a file."); return false; } else if (target.exists() && !owrite) { log.error("Invalid input to copy: target " + target + " exists."); return false; } try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target)); byte buffer[] = new byte[1024]; int read = -1; while ((read = in.read(buffer, 0, 1024)) != -1) out.write(buffer, 0, read); out.flush(); out.close(); in.close(); return true; } catch (IOException e) { log.error("Copy failed: ", e); return false; } } Code Sample 2: PackageFileImpl(PackageDirectoryImpl dir, String name, InputStream data) throws IOException { this.dir = dir; this.name = name; this.updates = dir.getUpdates(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); IOUtils.copy(data, stream); updates.setNewData(getFullName(), stream.toByteArray()); stream.close(); }
11
Code Sample 1: 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; } Code Sample 2: public static void main(String[] args) { try { boolean readExp = Utils.getFlag('l', args); final boolean writeExp = Utils.getFlag('s', args); final String expFile = Utils.getOption('f', args); if ((readExp || writeExp) && (expFile.length() == 0)) { throw new Exception("A filename must be given with the -f option"); } Experiment exp = null; if (readExp) { FileInputStream fi = new FileInputStream(expFile); ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(fi)); exp = (Experiment) oi.readObject(); oi.close(); } else { exp = new Experiment(); } System.err.println("Initial Experiment:\n" + exp.toString()); final JFrame jf = new JFrame("Weka Experiment Setup"); jf.getContentPane().setLayout(new BorderLayout()); final SetupPanel sp = new SetupPanel(); jf.getContentPane().add(sp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.err.println("\nFinal Experiment:\n" + sp.m_Exp.toString()); if (writeExp) { try { FileOutputStream fo = new FileOutputStream(expFile); ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(fo)); oo.writeObject(sp.m_Exp); oo.close(); } catch (Exception ex) { ex.printStackTrace(); System.err.println("Couldn't write experiment to: " + expFile + '\n' + ex.getMessage()); } } jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); System.err.println("Short nap"); Thread.currentThread().sleep(3000); System.err.println("Done"); sp.setExperiment(exp); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } }
00
Code Sample 1: public static void main(String[] args) { FTPClient client = new FTPClient(); try { File l_file = new File("C:/temp/testLoribel.html"); String l_url = "http://www.loribel.com/index.html"; GB_HttpTools.loadUrlToFile(l_url, l_file, ENCODING.ISO_8859_1); System.out.println("Try to connect..."); client.connect("ftp://ftp.phpnet.org"); System.out.println("Connected to server"); System.out.println("Try to connect..."); boolean b = client.login("fff", "ddd"); System.out.println("Login: " + b); String[] l_names = client.listNames(); GB_DebugTools.debugArray(GB_FtpDemo2.class, "names", l_names); b = client.makeDirectory("test02/toto"); System.out.println("Mkdir: " + b); String l_remote = "test02/test.xml"; InputStream l_local = new StringInputStream("Test111111111111111"); b = client.storeFile(l_remote, l_local); System.out.println("Copy file: " + b); } catch (Exception ex) { ex.printStackTrace(); } } Code Sample 2: public static String md5(String plainText) { String ret = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } ret = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ret; }
11
Code Sample 1: public void updateUserInfo(AuthSession authSession, AuthUserExtendedInfo infoAuth) { log.info("Start update auth"); PreparedStatement ps = null; DatabaseAdapter db = null; try { db = DatabaseAdapter.getInstance(); String sql = "update WM_AUTH_USER " + "set " + "ID_FIRM=?, IS_USE_CURRENT_FIRM=?, " + "ID_HOLDING=?, IS_HOLDING=? " + "WHERE ID_AUTH_USER=? "; ps = db.prepareStatement(sql); if (infoAuth.getAuthInfo().getCompanyId() == null) { ps.setNull(1, Types.INTEGER); ps.setInt(2, 0); } else { ps.setLong(1, infoAuth.getAuthInfo().getCompanyId()); ps.setInt(2, infoAuth.getAuthInfo().isCompany() ? 1 : 0); } if (infoAuth.getAuthInfo().getHoldingId() == null) { ps.setNull(3, Types.INTEGER); ps.setInt(4, 0); } else { ps.setLong(3, infoAuth.getAuthInfo().getHoldingId()); ps.setInt(4, infoAuth.getAuthInfo().isHolding() ? 1 : 0); } ps.setLong(5, infoAuth.getAuthInfo().getAuthUserId()); ps.executeUpdate(); processDeletedRoles(db, infoAuth); processNewRoles(db, infoAuth.getRoles(), infoAuth.getAuthInfo().getAuthUserId()); db.commit(); } catch (Throwable e) { try { if (db != null) db.rollback(); } catch (Exception e001) { } final String es = "Error add user auth"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(db, ps); ps = null; db = null; log.info("End update auth"); } } Code Sample 2: void execute(Connection conn, Component parent, String context, final ProgressMonitor progressMonitor, ProgressWrapper progressWrapper) throws Exception { int noOfComponents = m_components.length; Statement statement = null; StringBuffer pmNoteBuf = new StringBuffer(m_update ? "Updating " : "Creating "); pmNoteBuf.append(m_itemNameAbbrev); pmNoteBuf.append(" "); pmNoteBuf.append(m_itemNameValue); final String pmNote = pmNoteBuf.toString(); progressMonitor.setNote(pmNote); try { conn.setAutoCommit(false); int id = -1; if (m_update) { statement = conn.createStatement(); String sql = getUpdateSql(noOfComponents, m_id); statement.executeUpdate(sql); id = m_id; if (m_indexesChanged) deleteComponents(conn, id); } else { PreparedStatement pStmt = getInsertPrepStmt(conn, noOfComponents); pStmt.executeUpdate(); Integer res = DbCommon.getAutoGenId(parent, context, pStmt); if (res == null) return; id = res.intValue(); } if (!m_update || m_indexesChanged) { PreparedStatement insertCompPrepStmt = conn.prepareStatement(getInsertComponentPrepStmtSql()); for (int i = 0; i < noOfComponents; i++) { createComponent(progressMonitor, m_components, pmNote, id, i, insertCompPrepStmt); } } conn.commit(); m_itemTable.getPrimaryId().setVal(m_item, id); m_itemCache.updateCache(m_item, id); } catch (SQLException ex) { try { conn.rollback(); } catch (SQLException e) { e.printStackTrace(); } throw ex; } finally { if (statement != null) { statement.close(); } } }
00
Code Sample 1: public void deleteUser(User portalUserBean, AuthSession authSession) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (portalUserBean.getUserId() == null) throw new IllegalArgumentException("id of portal user is null"); String sql = "update WM_LIST_USER " + "set is_deleted=1 " + "where ID_USER=? and is_deleted = 0 and ID_FIRM in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedCompanyId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_FIRM from v$_read_list_firm z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); int num = 1; ps.setLong(num++, portalUserBean.getUserId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(num++, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) { dbDyn.rollback(); } } catch (Exception e001) { } String es = "Error delete of portal user"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } Code Sample 2: public static ISimpleChemObjectReader createReader(URL url, String urlString, String type) throws CDKException { if (type == null) { type = "mol"; } ISimpleChemObjectReader cor = null; try { Reader input = new BufferedReader(getReader(url)); FormatFactory formatFactory = new FormatFactory(8192); IChemFormat format = formatFactory.guessFormat(input); if (format != null) { if (format instanceof RGroupQueryFormat) { cor = new RGroupQueryReader(); cor.setReader(input); } else if (format instanceof CMLFormat) { cor = new CMLReader(urlString); cor.setReader(url.openStream()); } else if (format instanceof MDLV2000Format) { cor = new MDLV2000Reader(getReader(url)); cor.setReader(input); } } } catch (Exception exc) { exc.printStackTrace(); } if (cor == null) { if (type.equals(JCPFileFilter.cml) || type.equals(JCPFileFilter.xml)) { cor = new CMLReader(urlString); } else if (type.equals(JCPFileFilter.sdf)) { cor = new MDLV2000Reader(getReader(url)); } else if (type.equals(JCPFileFilter.mol)) { cor = new MDLV2000Reader(getReader(url)); } else if (type.equals(JCPFileFilter.inchi)) { try { cor = new INChIReader(new URL(urlString).openStream()); } catch (Exception e) { e.printStackTrace(); } } else if (type.equals(JCPFileFilter.rxn)) { cor = new MDLRXNV2000Reader(getReader(url)); } else if (type.equals(JCPFileFilter.smi)) { cor = new SMILESReader(getReader(url)); } } if (cor == null) { throw new CDKException(GT._("Could not determine file format")); } if (cor instanceof MDLV2000Reader) { try { BufferedReader in = new BufferedReader(getReader(url)); String line; while ((line = in.readLine()) != null) { if (line.equals("$$$$")) { String message = GT._("It seems you opened a mol or sdf" + " file containing several molecules. " + "Only the first one will be shown"); JOptionPane.showMessageDialog(null, message, GT._("sdf-like file"), JOptionPane.INFORMATION_MESSAGE); break; } } } catch (IOException ex) { ex.printStackTrace(); } } return cor; }
00
Code Sample 1: public static boolean verifyPassword(String digest, String password) { String alg = null; int size = 0; if (digest.regionMatches(true, 0, "{SHA}", 0, 5)) { digest = digest.substring(5); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{SSHA}", 0, 6)) { digest = digest.substring(6); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{MD5}", 0, 5)) { digest = digest.substring(5); alg = "MD5"; size = 16; } else if (digest.regionMatches(true, 0, "{SMD5}", 0, 6)) { digest = digest.substring(6); alg = "MD5"; size = 16; } try { MessageDigest sha = MessageDigest.getInstance(alg); if (sha == null) { return false; } byte[][] hs = split(Base64.decode(digest), size); byte[] hash = hs[0]; byte[] salt = hs[1]; sha.reset(); sha.update(password.getBytes()); sha.update(salt); byte[] pwhash = sha.digest(); return MessageDigest.isEqual(hash, pwhash); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException("failed to find " + "algorithm for password hashing.", nsae); } } Code Sample 2: private void outputSignedOpenDocument(byte[] signatureData) throws IOException { LOG.debug("output signed open document"); OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream(); if (null == signedOdfOutputStream) { throw new NullPointerException("signedOpenDocumentOutputStream is null"); } ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream); ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream()); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { zipOutputStream.putNextEntry(zipEntry); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
11
Code Sample 1: public static void sendSimpleHTMLMessage(Map<String, String> recipients, String object, String htmlContent, String from) { String message; try { File webinfDir = ClasspathUtils.getClassesDir().getParentFile(); File mailDir = new File(webinfDir, "mail"); File templateFile = new File(mailDir, "HtmlMessageTemplate.html"); StringWriter sw = new StringWriter(); Reader r = new BufferedReader(new FileReader(templateFile)); IOUtils.copy(r, sw); sw.close(); message = sw.getBuffer().toString(); message = message.replaceAll("%MESSAGE_HTML%", htmlContent).replaceAll("%APPLICATION_URL%", FGDSpringUtils.getExternalServerURL()); } catch (IOException e) { throw new RuntimeException(e); } Properties prop = getRealSMTPServerProperties(); if (prop != null) { try { MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(message, "text/html"); multipart.addBodyPart(messageBodyPart); sendHTML(recipients, object, multipart, from); } catch (MessagingException e) { throw new RuntimeException(e); } } else { StringBuffer contenuCourriel = new StringBuffer(); for (Entry<String, String> recipient : recipients.entrySet()) { if (recipient.getValue() == null) { contenuCourriel.append("À : " + recipient.getKey()); } else { contenuCourriel.append("À : " + recipient.getValue() + "<" + recipient.getKey() + ">"); } contenuCourriel.append("\n"); } contenuCourriel.append("Sujet : " + object); contenuCourriel.append("\n"); contenuCourriel.append("Message : "); contenuCourriel.append("\n"); contenuCourriel.append(message); } } Code Sample 2: protected void copyFile(String inputFilePath, String outputFilePath) throws GenerationException { String from = getTemplateDir() + inputFilePath; try { logger.debug("Copying from " + from + " to " + outputFilePath); InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(from); if (inputStream == null) { throw new GenerationException("Source file not found: " + from); } FileOutputStream outputStream = new FileOutputStream(new File(outputFilePath)); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (Exception e) { throw new GenerationException("Error while copying file: " + from, e); } }
11
Code Sample 1: public XmldbURI createFile(String newName, InputStream is, Long length, String contentType) throws IOException, PermissionDeniedException, CollectionDoesNotExistException { if (LOG.isDebugEnabled()) LOG.debug("Create '" + newName + "' in '" + xmldbUri + "'"); XmldbURI newNameUri = XmldbURI.create(newName); MimeType mime = MimeTable.getInstance().getContentTypeFor(newName); if (mime == null) { mime = MimeType.BINARY_TYPE; } DBBroker broker = null; Collection collection = null; BufferedInputStream bis = new BufferedInputStream(is); VirtualTempFile vtf = new VirtualTempFile(); BufferedOutputStream bos = new BufferedOutputStream(vtf); IOUtils.copy(bis, bos); bis.close(); bos.close(); vtf.close(); if (mime.isXMLType() && vtf.length() == 0L) { if (LOG.isDebugEnabled()) LOG.debug("Creating dummy XML file for null resource lock '" + newNameUri + "'"); vtf = new VirtualTempFile(); IOUtils.write("<null_resource/>", vtf); vtf.close(); } TransactionManager transact = brokerPool.getTransactionManager(); Txn txn = transact.beginTransaction(); try { broker = brokerPool.get(subject); collection = broker.openCollection(xmldbUri, Lock.WRITE_LOCK); if (collection == null) { LOG.debug("Collection " + xmldbUri + " does not exist"); transact.abort(txn); throw new CollectionDoesNotExistException(xmldbUri + ""); } if (mime.isXMLType()) { if (LOG.isDebugEnabled()) LOG.debug("Inserting XML document '" + mime.getName() + "'"); VirtualTempFileInputSource vtfis = new VirtualTempFileInputSource(vtf); IndexInfo info = collection.validateXMLResource(txn, broker, newNameUri, vtfis); DocumentImpl doc = info.getDocument(); doc.getMetadata().setMimeType(mime.getName()); collection.store(txn, broker, info, vtfis, false); } else { if (LOG.isDebugEnabled()) LOG.debug("Inserting BINARY document '" + mime.getName() + "'"); InputStream fis = vtf.getByteStream(); bis = new BufferedInputStream(fis); DocumentImpl doc = collection.addBinaryResource(txn, broker, newNameUri, bis, mime.getName(), length.longValue()); bis.close(); } transact.commit(txn); if (LOG.isDebugEnabled()) LOG.debug("Document created sucessfully"); } catch (EXistException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (TriggerException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (SAXException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (LockException e) { LOG.error(e); transact.abort(txn); throw new PermissionDeniedException(xmldbUri + ""); } catch (IOException e) { LOG.error(e); transact.abort(txn); throw e; } catch (PermissionDeniedException e) { LOG.error(e); transact.abort(txn); throw e; } finally { if (vtf != null) { vtf.delete(); } if (collection != null) { collection.release(Lock.WRITE_LOCK); } brokerPool.release(broker); if (LOG.isDebugEnabled()) LOG.debug("Finished creation"); } XmldbURI newResource = xmldbUri.append(newName); return newResource; } Code Sample 2: protected boolean downloadFile(TestThread thread, ActionResult result) { result.setRequestString("download file " + remoteFile); InputStream input = null; OutputStream output = null; OutputStream target = null; boolean status = false; ftpClient.enterLocalPassiveMode(); try { if (localFile != null) { File lcFile = new File(localFile); if (lcFile.exists() && lcFile.isDirectory()) output = new FileOutputStream(new File(lcFile, remoteFile)); else output = new FileOutputStream(lcFile); target = output; } else { target = new FileOutputStream(remoteFile); } input = ftpClient.retrieveFileStream(remoteFile); long bytes = IOUtils.copy(input, target); status = bytes > 0; if (status) { result.setResponseLength(bytes); } } catch (Exception e) { result.setException(new TestActionException(config, e)); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } return status; }
00
Code Sample 1: private static String hashPassword(String password) { try { String hashword = null; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); return hashword; } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } } Code Sample 2: public void store(String path, InputStream stream) throws IOException { toIgnore.add(normalizePath(path)); ZipEntry entry = new ZipEntry(path); zipOutput.putNextEntry(entry); IOUtils.copy(stream, zipOutput); zipOutput.closeEntry(); }
00
Code Sample 1: 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!"); } Code Sample 2: public static String copy(URL url, File dest) throws IOException { if (log.isDebugEnabled()) { log.debug("Fetching: " + url); } IOException error = null; for (int retries = 0; retries < MAX_RETRIES; retries++) { try { OutputStream out = null; InputStream is = null; try { out = new FileOutputStream(dest); if (url.getProtocol().equals("http")) { is = new WebFileInputStream(url); } else { is = url.openStream(); } MessageDigest md = MessageDigest.getInstance("MD5"); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) > 0) { out.write(buf, 0, len); md.update(buf, 0, len); } out.flush(); return bytesToHexString(md.digest()); } catch (ConnectException e) { if (error == null) { error = e; } if (retries < MAX_RETRIES - 1) { log.error(MessageFormat.format("Unable to fetch URL {0}, connection timed out. Will retry...", url.toExternalForm())); try { Thread.sleep(FileHelper.RETRY_SLEEP_TIME); } catch (InterruptedException e2) { } } } catch (SocketTimeoutException e) { if (error == null) { error = e; } if (retries < MAX_RETRIES - 1) { log.error(MessageFormat.format("Unable to fetch URL {0}, timed out. Will retry...", url.toExternalForm())); try { Thread.sleep(FileHelper.RETRY_SLEEP_TIME); } catch (InterruptedException e2) { } } } catch (IOException e) { if (dest.exists()) { try { FileHelper.delete(dest); } catch (IOException e1) { log.error(MessageFormat.format(Messages.getString("FileHelper.UNABLE_DELETE_FILE"), dest), e1); } } throw e; } finally { if (is != null) { try { is.close(); } catch (IOException e) { log.error(Messages.getString("FileHelper.UNABLE_CLOSE_STREAM"), e); } } if (out != null) { try { out.close(); } catch (IOException e) { log.error(Messages.getString("FileHelper.UNABLE_CLOSE_STREAM"), e); } } } } catch (NoSuchAlgorithmException e) { throw new IOException(MessageFormat.format(Messages.getString("FileHelper.UNABLE_DOWNLOAD_URL"), url), e); } } throw error; }
00
Code Sample 1: protected void find(final String pckgname, final boolean recursive) { URL url; String name = pckgname; name = name.replace('.', '/'); url = ResourceLocatorTool.getClassPathResource(ExampleRunner.class, name); File directory; try { directory = new File(URLDecoder.decode(url.getFile(), "UTF-8")); } catch (final UnsupportedEncodingException e) { throw new RuntimeException(e); } if (directory.exists()) { logger.info("Searching for examples in \"" + directory.getPath() + "\"."); addAllFilesInDirectory(directory, pckgname, recursive); } else { try { logger.info("Searching for Demo classes in \"" + url + "\"."); final URLConnection urlConnection = url.openConnection(); if (urlConnection instanceof JarURLConnection) { final JarURLConnection conn = (JarURLConnection) urlConnection; final JarFile jfile = conn.getJarFile(); final Enumeration<JarEntry> e = jfile.entries(); while (e.hasMoreElements()) { final ZipEntry entry = e.nextElement(); final Class<?> result = load(entry.getName()); if (result != null) { addClassForPackage(result); } } } } catch (final IOException e) { logger.logp(Level.SEVERE, this.getClass().toString(), "find(pckgname, recursive, classes)", "Exception", e); } catch (final Exception e) { logger.logp(Level.SEVERE, this.getClass().toString(), "find(pckgname, recursive, classes)", "Exception", e); } } } Code Sample 2: public boolean validatePassword(UserType nameMatch, String password) { try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.reset(); md.update(nameMatch.getSalt().getBytes("UTF-8")); md.update(password.getBytes("UTF-8")); String encodedString = new String(Base64.encode(md.digest())); return encodedString.equals(nameMatch.getPassword()); } catch (UnsupportedEncodingException ex) { logger.fatal("Your computer does not have UTF-8 support for Java installed.", ex); logger.fatal("Shutting down..."); GlobalUITools.displayFatalExceptionMessage(null, "UTF-8 for Java not installed", ex, true); assert false : "This should never happen"; return false; } catch (NoSuchAlgorithmException ex) { String errorMessage = "Could not use algorithm " + HASH_ALGORITHM; logger.fatal(ex.getMessage()); logger.fatal(errorMessage); GlobalUITools.displayFatalExceptionMessage(null, "Could not use algorithm " + HASH_ALGORITHM, ex, true); assert false : "This could should never be reached"; return false; } }
11
Code Sample 1: private synchronized boolean createOrganization(String organizationName, HttpServletRequest req) { if ((organizationName == null) || (organizationName.equals(""))) { message = "invalid new_organization_name."; return false; } String tmpxml = TextUtil.xmlEscape(organizationName); String tmpdb = DBAccess.SQLEscape(organizationName); if ((!organizationName.equals(tmpxml)) || (!organizationName.equals(tmpdb)) || (!TextUtil.isValidFilename(organizationName))) { message = "invalid new_organization_name."; return false; } if ((organizationName.indexOf('-') > -1) || (organizationName.indexOf(' ') > -1)) { message = "invalid new_organization_name."; return false; } String[] orgnames = ServerConsoleServlet.getOrganizationNames(); for (int i = 0; i < orgnames.length; i++) { if (orgnames.equals(organizationName)) { message = "already exists."; return false; } } message = "create new organization: " + organizationName; File newOrganizationDirectory = new File(ServerConsoleServlet.RepositoryLocalDirectory.getAbsolutePath() + File.separator + organizationName); if (!newOrganizationDirectory.mkdir()) { message = "cannot create directory."; return false; } File cacheDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("CacheDirName")); cacheDir.mkdir(); File confDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ConfDirName")); confDir.mkdir(); File rdfDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("RDFDirName")); rdfDir.mkdir(); File resourceDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ResourceDirName")); resourceDir.mkdir(); File obsoleteDir = new File(resourceDir.getAbsolutePath() + File.separator + "obsolete"); obsoleteDir.mkdir(); File schemaDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("SchemaDirName")); schemaDir.mkdir(); String organization_temp_dir = ServerConsoleServlet.convertToAbsolutePath(ServerConsoleServlet.getConfigByTagName("OrganizationTemplate")); File templ = new File(organization_temp_dir); File[] confFiles = templ.listFiles(); for (int i = 0; i < confFiles.length; i++) { try { FileReader fr = new FileReader(confFiles[i]); FileWriter fw = new FileWriter(confDir.getAbsolutePath() + File.separator + confFiles[i].getName()); int c = -1; while ((c = fr.read()) != -1) fw.write(c); fw.flush(); fw.close(); fr.close(); } catch (IOException e) { } } SchemaModelHolder.reloadSchemaModel(organizationName); ResourceModelHolder.reloadResourceModel(organizationName); UserLogServlet.initializeUserLogDB(organizationName); MetaEditServlet.createNewProject(organizationName, "standard", MetaEditServlet.convertProjectIdToProjectUri(organizationName, "standard", req), this.username); ResourceModelHolder.reloadResourceModel(organizationName); message = organizationName + " is created. Restart Tomcat to activate this organization."; return true; } 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: public static final String MD5(String value) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(value.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); String newValue = hash.toString(16); return newValue; } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return null; } } Code Sample 2: public void copyImage(String from, String to) { File inputFile = new File(from); File outputFile = new File(to); try { if (inputFile.canRead()) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); byte[] buf = new byte[65536]; int c; while ((c = in.read(buf)) > 0) out.write(buf, 0, c); in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } }
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 String unJar(String jarPath, String jarEntry) { String path; if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/")); String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/")); try { new File(path + "/" + relPath).mkdirs(); JarFile jar = new JarFile(jarPath); ZipEntry ze = jar.getEntry(jarEntry); File bin = new File(path + "/" + jarEntry); IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin)); } catch (Exception e) { e.printStackTrace(); } return path + "/" + jarEntry; }
00
Code Sample 1: public static void runDBUpdate() { if (!updateRunning) { if (updateJob != null) updateJob.cancel(); updateJob = new Job("Worm Database Update") { protected IStatus run(IProgressMonitor monitor) { try { updateRunning = true; distributor = getFromFile("[SERVER]", "csz", getAppPath() + "/server.ini"); MAC = getFromFile("[SPECIFICINFO]", "MAC", getAppPath() + "/register.ini"); serial = getFromFile("[SPECIFICINFO]", "serial", getAppPath() + "/register.ini"); if (MAC.equals("not_found") || serial.equals("not_found") || !serial.startsWith(distributor)) { try { MAC = getFromFile("[SPECIFICINFO]", "MAC", getAppPath() + "/register.ini"); serial = getFromFile("[SPECIFICINFO]", "serial", getAppPath() + "/register.ini"); } catch (Exception e) { System.out.println(e); } } else { try { url = new URL("http://" + getFromFile("[SERVER]", "url", getAppPath() + "/server.ini")); } catch (MalformedURLException e) { System.out.println(e); } download = "/download2.php?distributor=" + distributor + "&&mac=" + MAC + "&&serial=" + serial; readXML(); if (htmlMessage.contains("error")) { try { PrintWriter pw = new PrintWriter(getAppPath() + "/register.ini"); pw.write(""); pw.close(); } catch (IOException e) { System.out.println(e); } setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults2(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2()); } } else { if (!getDBVersion().equals(latestVersion)) { try { OutputStream out = null; HttpURLConnection conn = null; InputStream in = null; int size; try { URL url = new URL(fileLoc); String outFile = getAppPath() + "/temp/" + getFileName(url); File oFile = new File(outFile); oFile.delete(); out = new BufferedOutputStream(new FileOutputStream(outFile)); monitor.beginTask("Connecting to NWD Server", 100); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(20000); conn.connect(); if (conn.getResponseCode() / 100 != 2) { System.out.println("Error: " + conn.getResponseCode()); return null; } monitor.worked(100); monitor.done(); size = conn.getContentLength(); monitor.beginTask("Download Worm Definition", size); in = conn.getInputStream(); byte[] buffer; String downloadedSize; long numWritten = 0; boolean status = true; while (status) { if (size - numWritten > 1024) { buffer = new byte[1024]; } else { buffer = new byte[(int) (size - numWritten)]; } int read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); numWritten += read; downloadedSize = Long.toString(numWritten / 1024) + " KB"; monitor.worked(read); monitor.subTask(downloadedSize + " of " + Integer.toString(size / 1024) + " KB"); if (size == numWritten) { status = false; } if (monitor.isCanceled()) return Status.CANCEL_STATUS; } if (in != null) { in.close(); } if (out != null) { out.close(); } try { ZipFile zFile = new ZipFile(outFile); Enumeration all = zFile.entries(); while (all.hasMoreElements()) { ZipEntry zEntry = (ZipEntry) all.nextElement(); long zSize = zEntry.getSize(); if (zSize > 0) { if (zEntry.getName().endsWith("script")) { InputStream instream = zFile.getInputStream(zEntry); FileOutputStream fos = new FileOutputStream(oldLoc[0]); int ch; while ((ch = instream.read()) != -1) { fos.write(ch); } instream.close(); fos.close(); } else if (zEntry.getName().endsWith("data")) { InputStream instream = zFile.getInputStream(zEntry); FileOutputStream fos = new FileOutputStream(oldLoc[1]); int ch; while ((ch = instream.read()) != -1) { fos.write(ch); } instream.close(); fos.close(); } } } File xFile = new File(outFile); xFile.deleteOnExit(); } catch (Exception e) { e.printStackTrace(); } try { monitor.done(); monitor.beginTask("Install Worm Definition", 10000); monitor.worked(2500); CorePlugin.getDefault().getRawPacketHandler().removeRawPacketListener(p); p = null; if (!wormDB.getConn().isClosed()) { shutdownDB(); } System.out.println(wormDB.getConn().isClosed()); for (int i = 0; i < 2; i++) { try { Process pid = Runtime.getRuntime().exec("cmd /c copy \"" + oldLoc[i].replace("/", "\\") + "\" \"" + newLoc[i].replace("/", "\\") + "\"/y"); } catch (Exception e) { e.printStackTrace(); } new File(oldLoc[i]).deleteOnExit(); } monitor.worked(2500); initialArray(); p = new PacketPrinter(); CorePlugin.getDefault().getRawPacketHandler().addRawPacketListener(p); monitor.worked(2500); monitor.done(); setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction()); } } catch (Exception e) { setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults2(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2()); } System.out.println(e); } finally { } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults2(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2()); } e.printStackTrace(); } } else { cancel(); setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults1(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction1()); } } } } return Status.OK_STATUS; } catch (Exception e) { showResults2(); return Status.OK_STATUS; } finally { lock.release(); updateRunning = false; if (getValue("AUTO_UPDATE")) schedule(10800000); } } }; updateJob.schedule(); } } Code Sample 2: public String getWebPage(String url) { String content = ""; URL urlObj = null; try { urlObj = new URL(url); } catch (MalformedURLException urlEx) { urlEx.printStackTrace(); throw new Error("URL creation failed."); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream())); String line; while ((line = reader.readLine()) != null) { content += line; } } catch (IOException e) { e.printStackTrace(); throw new Error("Page retrieval failed."); } return content; }
11
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.closeQuietly(output); } } finally { IOUtils.closeQuietly(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: @Override public void render(Output output) throws IOException { output.setStatus(headersFile.getStatusCode(), headersFile.getStatusMessage()); for (Entry<String, Set<String>> header : headersFile.getHeadersMap().entrySet()) { Set<String> values = header.getValue(); for (String value : values) { output.addHeader(header.getKey(), value); } } if (file != null) { InputStream inputStream = new FileInputStream(file); try { output.open(); OutputStream out = output.getOutputStream(); IOUtils.copy(inputStream, out); } finally { inputStream.close(); output.close(); } } }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } 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 IBiopaxModel read(URL url) throws ReactionException, IOException { IBiopaxModel model = null; InputStream in = null; try { in = url.openStream(); model = read(in); } catch (IOException e) { LOGGER.error("Unable to read from URL " + url, e); } finally { if (in != null) in.close(); } return model; } Code Sample 2: private void documentFileChooserActionPerformed(java.awt.event.ActionEvent evt) { if (evt.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) { File selectedFile = documentFileChooser.getSelectedFile(); File collectionCopyFile; String newDocumentName = selectedFile.getName(); Document newDocument = new Document(newDocumentName); if (activeCollection.containsDocument(newDocument)) { int matchingFilenameDistinguisher = 1; StringBuilder distinguisherReplacer = new StringBuilder(); newDocumentName = newDocumentName.concat("(" + matchingFilenameDistinguisher + ")"); newDocument.setDocumentName(newDocumentName); while (activeCollection.containsDocument(newDocument)) { matchingFilenameDistinguisher++; newDocumentName = distinguisherReplacer.replace(newDocumentName.length() - 2, newDocumentName.length() - 1, new Integer(matchingFilenameDistinguisher).toString()).toString(); newDocument.setDocumentName(newDocumentName); } } Scanner tokenizer = null; FileChannel fileSource = null; FileChannel collectionDestination = null; HashMap<String, Integer> termHashMap = new HashMap<String, Integer>(); Index collectionIndex = activeCollection.getIndex(); int documentTermMaxFrequency = 0; int currentTermFrequency; try { tokenizer = new Scanner(new BufferedReader(new FileReader(selectedFile))); tokenizer.useDelimiter(Pattern.compile("\\p{Space}|\\p{Punct}|\\p{Cntrl}")); String nextToken; while (tokenizer.hasNext()) { nextToken = tokenizer.next().toLowerCase(); if (!nextToken.isEmpty()) if (termHashMap.containsKey(nextToken)) termHashMap.put(nextToken, termHashMap.get(nextToken) + 1); else termHashMap.put(nextToken, 1); } Term newTerm; for (String term : termHashMap.keySet()) { newTerm = new Term(term); if (!collectionIndex.termExists(newTerm)) collectionIndex.addTerm(newTerm); currentTermFrequency = termHashMap.get(term); if (currentTermFrequency > documentTermMaxFrequency) documentTermMaxFrequency = currentTermFrequency; collectionIndex.addOccurence(newTerm, newDocument, currentTermFrequency); } activeCollection.addDocument(newDocument); String userHome = System.getProperty("user.home"); String fileSeparator = System.getProperty("file.separator"); collectionCopyFile = new File(userHome + fileSeparator + "Infrared" + fileSeparator + activeCollection.getDocumentCollectionName() + fileSeparator + newDocumentName); collectionCopyFile.createNewFile(); fileSource = new FileInputStream(selectedFile).getChannel(); collectionDestination = new FileOutputStream(collectionCopyFile).getChannel(); collectionDestination.transferFrom(fileSource, 0, fileSource.size()); } catch (FileNotFoundException e) { System.err.println(e.getMessage() + " This error should never occur! The file was just selected!"); return; } catch (IOException e) { JOptionPane.showMessageDialog(this, "An I/O error occured during file transfer!", "File transfer I/O error", JOptionPane.WARNING_MESSAGE); return; } finally { try { if (tokenizer != null) tokenizer.close(); if (fileSource != null) fileSource.close(); if (collectionDestination != null) collectionDestination.close(); } catch (IOException e) { System.err.println(e.getMessage()); } } processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); } else if (evt.getActionCommand().equalsIgnoreCase(JFileChooser.CANCEL_SELECTION)) processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); }
11
Code Sample 1: private void checkRoundtrip(byte[] content) throws Exception { InputStream in = new ByteArrayInputStream(content); ByteArrayOutputStream out = new ByteArrayOutputStream(); CodecUtil.encodeQuotedPrintableBinary(in, out); in = new QuotedPrintableInputStream(new ByteArrayInputStream(out.toByteArray())); out = new ByteArrayOutputStream(); IOUtils.copy(in, out); assertEquals(content, out.toByteArray()); } Code Sample 2: public static boolean copyFile(File from, File tu) { final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(tu); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { return false; } return true; }
11
Code Sample 1: public static URL toFileUrl(URL location) throws IOException { String protocol = location.getProtocol().intern(); if (protocol != "jar") throw new IOException("cannot explode " + location); JarURLConnection juc = (JarURLConnection) location.openConnection(); String path = juc.getEntryName(); String parentPath = parentPathOf(path); File tempDir = createTempDir("jartemp"); JarFile jarFile = juc.getJarFile(); for (Enumeration<JarEntry> en = jarFile.entries(); en.hasMoreElements(); ) { ZipEntry entry = en.nextElement(); if (entry.isDirectory()) continue; String entryPath = entry.getName(); if (entryPath.startsWith(parentPath)) { File dest = new File(tempDir, entryPath); dest.getParentFile().mkdirs(); InputStream in = jarFile.getInputStream(entry); OutputStream out = new FileOutputStream(dest); IOUtils.copy(in, out); dest.deleteOnExit(); } } File realFile = new File(tempDir, path); return realFile.toURL(); } Code Sample 2: private File uploadToTmp() { if (fileFileName == null) { return null; } File tmpFile = dataDir.tmpFile(shortname, fileFileName); log.debug("Uploading dwc archive file for new resource " + shortname + " to " + tmpFile.getAbsolutePath()); InputStream input = null; OutputStream output = null; try { input = new FileInputStream(file); output = new FileOutputStream(tmpFile); IOUtils.copy(input, output); output.flush(); log.debug("Uploaded file " + fileFileName + " with content-type " + fileContentType); } catch (IOException e) { log.error(e); return null; } finally { if (output != null) { IOUtils.closeQuietly(output); } if (input != null) { IOUtils.closeQuietly(input); } } return tmpFile; }
11
Code Sample 1: private String digestPassword(String password) { StringBuffer hexString = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes()); byte[] messageDigest = algorithm.digest(); for (byte b : messageDigest) { hexString.append(Integer.toHexString(0xFF & b)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hexString.toString(); } Code Sample 2: @Override public String encryptString(String passphrase, String message) throws Exception { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes("UTF-8")); byte digest[] = md.digest(); String digestString = base64encode(digest); System.out.println(digestString); SecureRandom sr = new SecureRandom(digestString.getBytes()); KeyGenerator kGen = KeyGenerator.getInstance("AES"); kGen.init(128, sr); Key key = kGen.generateKey(); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] bIn = cipher.doFinal(message.getBytes("UTF-8")); String base64Encoded = base64encode(bIn); return base64Encoded; }
00
Code Sample 1: public void login(String a_username, String a_password) throws GB_SecurityException { Exception l_exception = null; try { if (clientFtp == null) { clientFtp = new FTPClient(); clientFtp.connect("ftp://" + ftp); } boolean b = clientFtp.login(a_username, a_password); if (b) { username = a_username; password = a_password; return; } } catch (Exception ex) { l_exception = ex; } String l_msg = "Cannot login to ftp server with user [{1}], {2}"; String[] l_replaces = new String[] { a_username, ftp }; l_msg = STools.replace(l_msg, l_replaces); throw new GB_SecurityException(l_msg, l_exception); } Code Sample 2: protected void innerProcess(ProcessorURI curi) throws InterruptedException { Pattern regexpr = curi.get(this, STRIP_REG_EXPR); ReplayCharSequence cs = null; try { cs = curi.getRecorder().getReplayCharSequence(); } catch (Exception e) { curi.getNonFatalFailures().add(e); logger.warning("Failed get of replay char sequence " + curi.toString() + " " + e.getMessage() + " " + Thread.currentThread().getName()); return; } MessageDigest digest = null; try { try { digest = MessageDigest.getInstance(SHA1); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); return; } digest.reset(); String s = null; if (regexpr != null) { s = cs.toString(); } else { Matcher m = regexpr.matcher(cs); s = m.replaceAll(" "); } digest.update(s.getBytes()); byte[] newDigestValue = digest.digest(); curi.setContentDigest(SHA1, newDigestValue); } finally { if (cs != null) { try { cs.close(); } catch (IOException ioe) { logger.warning(TextUtils.exceptionToString("Failed close of ReplayCharSequence.", ioe)); } } } }
11
Code Sample 1: private static void copy(String srcFilename, String dstFilename, boolean override) throws IOException, XPathFactoryConfigurationException, SAXException, ParserConfigurationException, XPathExpressionException { File fileToCopy = new File(rootDir + "test-output/" + srcFilename); if (fileToCopy.exists()) { File newFile = new File(rootDir + "test-output/" + dstFilename); if (!newFile.exists() || override) { try { FileChannel srcChannel = new FileInputStream(rootDir + "test-output/" + srcFilename).getChannel(); FileChannel dstChannel = new FileOutputStream(rootDir + "test-output/" + dstFilename).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: 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(); } } 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); } }
11
Code Sample 1: public void execute(File tsvFile, File xmlFile) { BufferedReader reader = null; Writer writer = null; Boolean isFileSuccessfullyConverted = Boolean.TRUE; TableConfiguration tableConfig = null; try { xmlFile.getParentFile().mkdirs(); reader = new BufferedReader(new InputStreamReader(new FileInputStream(tsvFile), INPUT_ENCODING)); writer = new OutputStreamWriter(new FileOutputStream(xmlFile), OUTPUT_ENCODING); tableConfig = Tsv2DocbookConverter.convert2(tableConfigManager, idScanner.extractIdentification(tsvFile), reader, writer, inputPolisher); isFileSuccessfullyConverted = (tableConfig != null); } catch (UnsupportedEncodingException e) { logger.error("Failed to create reader with UTF-8 encoding: " + e.getMessage(), e); } catch (FileNotFoundException fnfe) { logger.error("Failed to open tsv input file '" + tsvFile + "'. " + fnfe.getMessage()); } catch (Throwable cause) { logger.error("Failed to convert input tsv file '" + tsvFile + "'.", cause); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { logger.warn("Unable to close input file.", ioe); } } if (writer != null) { try { writer.close(); } catch (IOException ioe) { logger.warn("Unable to close output file.", ioe); } } } if (isFileSuccessfullyConverted) { String newOutputFileName = tableConfig.getFileName(idScanner.extractIdentification(tsvFile)); if (newOutputFileName != null) { File newOutputFile = new File(xmlFile.getParentFile(), newOutputFileName); if (!xmlFile.renameTo(newOutputFile)) { logger.warn("Unable to rename '" + xmlFile + "' to '" + newOutputFile + "'."); logger.info("Created successfully '" + xmlFile + "'."); } else { logger.info("Created successfully '" + newOutputFileName + "'."); } } else { logger.info("Created successfully '" + xmlFile + "'."); } } else { logger.warn("Unable to convert input tsv file '" + Tsv2DocBookApplication.trimPath(sourceDir, tsvFile) + "' to docbook."); if (xmlFile.exists() && !xmlFile.delete()) { logger.warn("Unable to remove (empty) output file '" + xmlFile + "', which was created as target for the docbook table."); } } } Code Sample 2: @Override protected void copyContent(String filename) throws IOException { InputStream in = null; try { String resourceDir = System.getProperty("resourceDir"); File resource = new File(resourceDir, filename); ByteArrayOutputStream out = new ByteArrayOutputStream(); if (resource.exists()) { in = new FileInputStream(resource); } else { in = LOADER.getResourceAsStream(RES_PKG + filename); } IOUtils.copy(in, out); setResponseData(out.toByteArray()); } finally { if (in != null) { in.close(); } } }
00
Code Sample 1: private static boolean extractFromJarUsingClassLoader(String searchString, String filename, String destinationDirectory) { ClassLoader cl = null; try { Class clClass = Class.forName("com.simontuffs.onejar.JarClassLoader"); Constructor[] constructor = clClass.getConstructors(); cl = (ClassLoader) constructor[1].newInstance(ClassLoader.getSystemClassLoader()); System.out.println("Loaded JarClassLoader. cl=" + cl.toString()); } catch (Throwable e) { cl = ClassLoader.getSystemClassLoader(); } URL liburl = cl.getResource(filename); if (liburl == null) { return false; } if (!destinationDirectory.endsWith(File.separator)) { destinationDirectory = destinationDirectory + File.separator; } try { File destFile = new File(destinationDirectory + filename); if (destFile.exists()) { destFile.delete(); } InputStream is; is = liburl.openStream(); OutputStream os = new FileOutputStream(destinationDirectory + filename); byte[] buf = new byte[4096]; int cnt = is.read(buf); while (cnt > 0) { os.write(buf, 0, cnt); cnt = is.read(buf); } os.close(); is.close(); destFile.deleteOnExit(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } Code Sample 2: private void buildBundle() { if (targetProject == null) { MessageDialog.openError(getShell(), "Error", "No target SPAB project selected!"); return; } if (projectProcessDirSelector.getText().trim().length() == 0) { MessageDialog.openError(getShell(), "Error", "No process directory selected for project " + targetProject.getName() + "!"); return; } deleteBundleFile(); try { File projectDir = targetProject.getLocation().toFile(); File projectProcessesDir = new File(projectDir, projectProcessDirSelector.getText()); boolean bpmoCopied = IOUtils.copyProcessFilesSecure(getBPMOFile(), projectProcessesDir); boolean sbpelCopied = IOUtils.copyProcessFilesSecure(getSBPELFile(), projectProcessesDir); boolean xmlCopied = IOUtils.copyProcessFilesSecure(getBPEL4SWSFile(), projectProcessesDir); bundleFile = IOUtils.archiveBundle(projectDir, Activator.getDefault().getStateLocation().toFile()); if (bpmoCopied) { new File(projectProcessesDir, getBPMOFile().getName()).delete(); } if (sbpelCopied) { new File(projectProcessesDir, getSBPELFile().getName()).delete(); } if (xmlCopied) { new File(projectProcessesDir, getBPEL4SWSFile().getName()).delete(); } } catch (Throwable anyError) { LogManager.logError(anyError); MessageDialog.openError(getShell(), "Error", "Error building SPAB :\n" + anyError.getMessage()); updateBundleUI(); return; } bpmoFile = getBPMOFile(); sbpelFile = getSBPELFile(); xmlFile = getBPEL4SWSFile(); updateBundleUI(); getWizard().getContainer().updateButtons(); }
00
Code Sample 1: protected void copyFile(File source, File destination) throws ApplicationException { try { OutputStream out = new FileOutputStream(destination); DataInputStream in = new DataInputStream(new FileInputStream(source)); byte[] buf = new byte[8192]; for (int nread = in.read(buf); nread > 0; nread = in.read(buf)) { out.write(buf, 0, nread); } in.close(); out.close(); } catch (IOException e) { throw new ApplicationException("Can't copy file " + source + " to " + destination); } } Code Sample 2: public static Reader createReader(TreeLogger logger, URL url) throws UnableToCompleteException { try { return new InputStreamReader(url.openStream()); } catch (IOException e) { logger.log(TreeLogger.ERROR, "Unable to open resource: " + url, e); throw new UnableToCompleteException(); } }
00
Code Sample 1: public static StringBuffer getCachedFile(String url) throws Exception { File urlCache = new File("tmp-cache/" + url.replace('/', '-')); new File("tmp-cache/").mkdir(); if (urlCache.exists()) { BufferedReader in = new BufferedReader(new FileReader(urlCache)); StringBuffer buffer = new StringBuffer(); String input; while ((input = in.readLine()) != null) { buffer.append(input + "\n"); } in.close(); return buffer; } else { URL url2 = new URL(url.replace(" ", "%20")); BufferedReader in = new BufferedReader(new InputStreamReader(url2.openStream())); BufferedWriter cacheWriter = new BufferedWriter(new FileWriter(urlCache)); StringBuffer buffer = new StringBuffer(); String input; while ((input = in.readLine()) != null) { buffer.append(input + "\n"); cacheWriter.write(input + "\n"); } cacheWriter.close(); in.close(); return buffer; } } Code Sample 2: public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; }
00
Code Sample 1: private void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); if (zShareAccount.loginsuccessful) { httppost.setHeader("Cookie", zShareAccount.getSidcookie() + ";" + zShareAccount.getMysessioncookie()); } else { httppost.setHeader("Cookie", sidcookie + ";" + mysessioncookie); } generateZShareID(); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("", new MonitoredFileBody(file, uploadProgress)); mpEntity.addPart("TOS", new StringBody("1")); httppost.setEntity(mpEntity); NULogger.getLogger().log(Level.INFO, "executing request {0}", httppost.getRequestLine()); status = UploadStatus.UPLOADING; NULogger.getLogger().info("Now uploading your file into zshare.net"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); NULogger.getLogger().info(response.getStatusLine().toString()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } uploadresponse = uploadresponse.replaceAll("\n", ""); uploadresponse = uploadresponse.substring(uploadresponse.indexOf("index2.php")); uploadresponse = uploadresponse.substring(0, uploadresponse.indexOf("\">here")); uploadresponse = uploadresponse.replaceAll("amp;", ""); if (zShareAccount.loginsuccessful) { uploadresponse = zShareAccount.getZsharelink() + uploadresponse; } else { uploadresponse = zsharelink + uploadresponse; } uploadresponse = uploadresponse.replaceAll(" ", "%20"); NULogger.getLogger().log(Level.INFO, "resp : {0}", uploadresponse); httpclient.getConnectionManager().shutdown(); } Code Sample 2: private void loadOperatorsXML() { startwindow.setMessage("Loading Operators..."); try { URL url = Application.class.getClassLoader().getResource(Resources.getString("OPERATORS_XML")); InputStream input = url.openStream(); OperatorsReader.registerOperators(Resources.getString("OPERATORS_XML"), input); } catch (FileNotFoundException e) { Logger.logException("File '" + Resources.getString("OPERATORS_XML") + "' not found.", e); } catch (IOException error) { Logger.logException(error.getMessage(), error); } }
11
Code Sample 1: private static boolean hasPackageInfo(URL url) { if (url == null) return false; BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null) { if (line.startsWith("Specification-Title: ") || line.startsWith("Specification-Version: ") || line.startsWith("Specification-Vendor: ") || line.startsWith("Implementation-Title: ") || line.startsWith("Implementation-Version: ") || line.startsWith("Implementation-Vendor: ")) return true; } } catch (IOException ioe) { } finally { if (br != null) try { br.close(); } catch (IOException e) { } } return false; } Code Sample 2: private void fetchTree() throws IOException { String urlString = BASE_URL + TREE_URL + DATASET_URL + "&family=" + mFamily; URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String toParse = in.readLine(); while (in.ready()) { String add = in.readLine(); if (add == null) break; toParse += add; } if (toParse != null && !toParse.startsWith("No tree available")) mProteinTree = new PTree(this, toParse); }
11
Code Sample 1: public void unlock(String oid, String key) throws PersisterException { String lock = getLock(oid); if (lock == null) { throw new PersisterException("Object does not exist: OID = " + oid); } else if (!NULL.equals(lock) && (!lock.equals(key))) { throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key); } Connection conn = null; PreparedStatement ps = null; try { conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("update " + _table_name + " set " + _key_col + " = NULL, " + _ts_col + " = ? where " + _oid_col + " = ?"); ps.setLong(1, System.currentTimeMillis()); ps.setString(2, oid); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to unlock object: OID = " + oid + ", KEY = " + key, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } } Code Sample 2: public synchronized void insertMessage(FrostUnsentMessageObject mo) throws SQLException { AttachmentList files = mo.getAttachmentsOfType(Attachment.FILE); AttachmentList boards = mo.getAttachmentsOfType(Attachment.BOARD); Connection conn = AppLayerDatabase.getInstance().getPooledConnection(); try { conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("INSERT INTO UNSENDMESSAGES (" + "primkey,messageid,inreplyto,board,sendafter,idlinepos,idlinelen,fromname,subject,recipient,msgcontent," + "hasfileattachment,hasboardattachment,timeAdded" + ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); Long identity = null; Statement stmt = AppLayerDatabase.getInstance().createStatement(); ResultSet rs = stmt.executeQuery("select UNIQUEKEY('UNSENDMESSAGES')"); if (rs.next()) { identity = new Long(rs.getLong(1)); } else { logger.log(Level.SEVERE, "Could not retrieve a new unique key!"); } rs.close(); stmt.close(); mo.setMsgIdentity(identity.longValue()); int i = 1; ps.setLong(i++, mo.getMsgIdentity()); ps.setString(i++, mo.getMessageId()); ps.setString(i++, mo.getInReplyTo()); ps.setInt(i++, mo.getBoard().getPrimaryKey().intValue()); ps.setLong(i++, 0); ps.setInt(i++, mo.getIdLinePos()); ps.setInt(i++, mo.getIdLineLen()); ps.setString(i++, mo.getFromName()); ps.setString(i++, mo.getSubject()); ps.setString(i++, mo.getRecipientName()); ps.setString(i++, mo.getContent()); ps.setBoolean(i++, (files.size() > 0)); ps.setBoolean(i++, (boards.size() > 0)); ps.setLong(i++, mo.getTimeAdded()); int inserted = 0; try { inserted = ps.executeUpdate(); } finally { ps.close(); } if (inserted == 0) { logger.log(Level.SEVERE, "message insert returned 0 !!!"); return; } mo.setMsgIdentity(identity.longValue()); if (files.size() > 0) { PreparedStatement p = conn.prepareStatement("INSERT INTO UNSENDFILEATTACHMENTS" + " (msgref,filename,filesize,filekey)" + " VALUES (?,?,?,?)"); for (Iterator it = files.iterator(); it.hasNext(); ) { FileAttachment fa = (FileAttachment) it.next(); int ix = 1; p.setLong(ix++, mo.getMsgIdentity()); p.setString(ix++, fa.getInternalFile().getPath()); p.setLong(ix++, fa.getFileSize()); p.setString(ix++, fa.getKey()); int ins = p.executeUpdate(); if (ins == 0) { logger.log(Level.SEVERE, "fileattachment insert returned 0 !!!"); } } p.close(); } if (boards.size() > 0) { PreparedStatement p = conn.prepareStatement("INSERT INTO UNSENDBOARDATTACHMENTS" + " (msgref,boardname,boardpublickey,boardprivatekey,boarddescription)" + " VALUES (?,?,?,?,?)"); for (Iterator it = boards.iterator(); it.hasNext(); ) { BoardAttachment ba = (BoardAttachment) it.next(); Board b = ba.getBoardObj(); int ix = 1; p.setLong(ix++, mo.getMsgIdentity()); p.setString(ix++, b.getNameLowerCase()); p.setString(ix++, b.getPublicKey()); p.setString(ix++, b.getPrivateKey()); p.setString(ix++, b.getDescription()); int ins = p.executeUpdate(); if (ins == 0) { logger.log(Level.SEVERE, "boardattachment insert returned 0 !!!"); } } p.close(); } conn.commit(); conn.setAutoCommit(true); } catch (Throwable t) { logger.log(Level.SEVERE, "Exception during insert of unsent message", t); try { conn.rollback(); } catch (Throwable t1) { logger.log(Level.SEVERE, "Exception during rollback", t1); } try { conn.setAutoCommit(true); } catch (Throwable t1) { } } finally { AppLayerDatabase.getInstance().givePooledConnection(conn); } }
00
Code Sample 1: private static InputStream download(String url) { try { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse httpresponse = httpclient.execute(httpget); HttpEntity httpentity = httpresponse.getEntity(); if (httpentity != null) { return httpentity.getContent(); } } catch (Exception e) { Log.e("Android", e.getMessage()); } return null; } Code Sample 2: public static String hexSHA1(String value) { try { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); md.update(value.getBytes("utf-8")); byte[] digest = md.digest(); return byteToHexString(digest); } catch (Exception ex) { throw new UnexpectedException(ex); } }
00
Code Sample 1: public static boolean loadTestProperties(Properties props, Class<?> callingClazz, Class<?> hierarchyRootClazz, String resourceBaseName) { if (!hierarchyRootClazz.isAssignableFrom(callingClazz)) { throw new IllegalArgumentException("Class " + callingClazz + " is not derived from " + hierarchyRootClazz); } if (null == resourceBaseName) { throw new NullPointerException("resourceBaseName is null"); } String fqcn = callingClazz.getName(); String uqcn = fqcn.substring(fqcn.lastIndexOf('.') + 1); String callingClassResource = uqcn + ".properties"; String globalCallingClassResource = "/" + callingClassResource; String baseClassResource = resourceBaseName + "-" + uqcn + ".properties"; String globalBaseClassResource = "/" + baseClassResource; String pkgResource = resourceBaseName + ".properties"; String globalResource = "/" + pkgResource; boolean loaded = false; final String[] resources = { baseClassResource, globalBaseClassResource, callingClassResource, globalCallingClassResource, pkgResource, globalResource }; List<URL> urls = new ArrayList<URL>(); Class<?> clazz = callingClazz; do { for (String res : resources) { URL url = clazz.getResource(res); if (null != url && !urls.contains(url)) { urls.add(url); } } if (hierarchyRootClazz.equals(clazz)) { clazz = null; } else { clazz = clazz.getSuperclass(); } } while (null != clazz); ListIterator<URL> it = urls.listIterator(urls.size()); while (it.hasPrevious()) { URL url = it.previous(); InputStream in = null; try { LOG.info("Loading test properties from resource: " + url); in = url.openStream(); props.load(in); loaded = true; } catch (IOException ex) { LOG.warn("Failed to load properties from resource: " + url, ex); } IOUtil.closeSilently(in); } return loaded; } Code Sample 2: protected boolean writeFile(Interest outstandingInterest) throws IOException { File fileToWrite = ccnNameToFilePath(outstandingInterest.name()); Log.info("CCNFileProxy: extracted request for file: " + fileToWrite.getAbsolutePath() + " exists? ", fileToWrite.exists()); if (!fileToWrite.exists()) { Log.warning("File {0} does not exist. Ignoring request.", fileToWrite.getAbsoluteFile()); return false; } FileInputStream fis = null; try { fis = new FileInputStream(fileToWrite); } catch (FileNotFoundException fnf) { Log.warning("Unexpected: file we expected to exist doesn't exist: {0}!", fileToWrite.getAbsolutePath()); return false; } CCNTime modificationTime = new CCNTime(fileToWrite.lastModified()); ContentName versionedName = VersioningProfile.addVersion(new ContentName(_prefix, outstandingInterest.name().postfix(_prefix).components()), modificationTime); CCNFileOutputStream ccnout = new CCNFileOutputStream(versionedName, _handle); ccnout.addOutstandingInterest(outstandingInterest); byte[] buffer = new byte[BUF_SIZE]; int read = fis.read(buffer); while (read >= 0) { ccnout.write(buffer, 0, read); read = fis.read(buffer); } fis.close(); ccnout.close(); return true; }
11
Code Sample 1: public static void decompressFile(File orig) throws IOException { File file = new File(INPUT + orig.toString()); File target = new File(OUTPUT + orig.toString().replaceAll(".xml.gz", ".xml")); System.out.println(" Decompressing \"" + file.getName() + "\" into \"" + target + "\""); long l = file.length(); GZIPInputStream gzipinputstream = new GZIPInputStream(new FileInputStream(file)); FileOutputStream fileoutputstream = new FileOutputStream(target); byte abyte0[] = new byte[1024]; int i; while ((i = gzipinputstream.read(abyte0)) != -1) fileoutputstream.write(abyte0, 0, i); fileoutputstream.close(); gzipinputstream.close(); long l1 = target.length(); System.out.println(" Initial size: " + l + "; Decompressed size: " + l1 + "."); System.out.println(" Done."); System.out.println(); } Code Sample 2: private String loadSchemas() { StringWriter writer = new StringWriter(); try { IOUtils.copy(CoreOdfValidator.class.getResourceAsStream("schema_list.properties"), writer); } catch (IOException e) { e.printStackTrace(); } return writer.toString(); }
11
Code Sample 1: public static void main(String[] args) { Option optHelp = new Option("h", "help", false, "print this message"); Option optCerts = new Option("c", "cert", true, "use external semicolon separated X.509 certificate files"); optCerts.setArgName("certificates"); Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); Option optExtract = new Option("e", "extract", true, "extract signed PDF revisions to given folder"); optExtract.setArgName("folder"); Option optListKs = new Option("lk", "list-keystore-types", false, "list keystore types provided by java"); Option optListCert = new Option("lc", "list-certificates", false, "list certificate aliases in a KeyStore"); Option optKsType = new Option("kt", "keystore-type", true, "use keystore type with given name"); optKsType.setArgName("keystore_type"); Option optKsFile = new Option("kf", "keystore-file", true, "use given keystore file"); optKsFile.setArgName("file"); Option optKsPass = new Option("kp", "keystore-password", true, "password for keystore file (look on -kf option)"); optKsPass.setArgName("password"); Option optFailFast = new Option("ff", "fail-fast", true, "flag which sets the Verifier to exit with error code on the first validation failure"); final Options options = new Options(); options.addOption(optHelp); options.addOption(optCerts); options.addOption(optPasswd); options.addOption(optExtract); options.addOption(optListKs); options.addOption(optListCert); options.addOption(optKsType); options.addOption(optKsFile); options.addOption(optKsPass); options.addOption(optFailFast); CommandLine line = null; try { CommandLineParser parser = new PosixParser(); line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Illegal command used: " + exp.getMessage()); System.exit(-1); } final boolean failFast = line.hasOption("ff"); final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar Verifier.jar [file1.pdf [file2.pdf ...]]", "JSignPdf Verifier is a command line tool for verifying signed PDF documents.", options, null, true); } else if (line.hasOption("lk")) { for (String tmpKsType : KeyStoreUtils.getKeyStores()) { System.out.println(tmpKsType); } } else if (line.hasOption("lc")) { for (String tmpCert : KeyStoreUtils.getCertAliases(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp"))) { System.out.println(tmpCert); } } else { final VerifierLogic tmpLogic = new VerifierLogic(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp")); tmpLogic.setFailFast(failFast); if (line.hasOption("c")) { String tmpCertFiles = line.getOptionValue("c"); for (String tmpCFile : tmpCertFiles.split(";")) { tmpLogic.addX509CertFile(tmpCFile); } } byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } String tmpExtractDir = null; if (line.hasOption("e")) { tmpExtractDir = new File(line.getOptionValue("e")).getPath(); } for (String tmpFilePath : tmpArgs) { System.out.println("Verifying " + tmpFilePath); final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { System.err.println("Couln't read the file. Check the path and permissions."); if (failFast) { System.exit(-1); } continue; } final VerificationResult tmpResult = tmpLogic.verify(tmpFilePath, tmpPasswd); if (tmpResult.getException() != null) { tmpResult.getException().printStackTrace(); System.exit(-1); } else { System.out.println("Total revisions: " + tmpResult.getTotalRevisions()); for (SignatureVerification tmpSigVer : tmpResult.getVerifications()) { System.out.println(tmpSigVer.toString()); if (tmpExtractDir != null) { try { File tmpExFile = new File(tmpExtractDir + "/" + tmpFile.getName() + "_" + tmpSigVer.getRevision() + ".pdf"); System.out.println("Extracting to " + tmpExFile.getCanonicalPath()); FileOutputStream tmpFOS = new FileOutputStream(tmpExFile.getCanonicalPath()); InputStream tmpIS = tmpLogic.extractRevision(tmpFilePath, tmpPasswd, tmpSigVer.getName()); IOUtils.copy(tmpIS, tmpFOS); tmpIS.close(); tmpFOS.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } if (failFast && SignatureVerification.isError(tmpResult.getVerificationResultCode())) { System.exit(tmpResult.getVerificationResultCode()); } } } } } Code Sample 2: private void createImageArchive() throws Exception { imageArchive = new File(resoutFolder, "images.CrAr"); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(imageArchive))); out.writeInt(toNativeEndian(imageFiles.size())); for (int i = 0; i < imageFiles.size(); i++) { File f = imageFiles.get(i); out.writeLong(toNativeEndian(f.length())); out.writeLong(toNativeEndian(new File(resFolder, f.getName().substring(0, f.getName().length() - 5)).length())); } for (int i = 0; i < imageFiles.size(); i++) { BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageFiles.get(i))); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); } out.close(); }
11
Code Sample 1: public void maj(String titre, String num_version) { int res = 2; String content_xml = ""; try { URL url = new URL("http://code.google.com/feeds/p/tux-team/downloads/basic"); InputStreamReader ipsr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(ipsr); String line = null; StringBuffer buffer = new StringBuffer(); while ((line = br.readLine()) != null) { buffer.append(line).append('\n'); } br.close(); content_xml = buffer.toString(); res = lecture_xml(titre, num_version, content_xml); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } switch(res) { case 0: ihm.jl_maj.setText("Pas de mises à jour disponible. (" + num_version + ")"); ihm.jl_maj.setIcon(Resources.getImageIcon("images/valide.png", IHM_AProposDe.class)); break; case 1: ihm.jl_maj.setText("Une mise à jour est diponible. (" + maj_file_version + ")"); ihm.jl_maj.setIcon(Resources.getImageIcon("images/warning.png", IHM_AProposDe.class)); ihm.jb_maj.setVisible(true); break; default: ihm.jl_maj.setText("Serveur de mise à jour non disponible."); ihm.jl_maj.setIcon(Resources.getImageIcon("images/erreur.png", IHM_AProposDe.class)); } } Code Sample 2: @Deprecated public static Collection<SearchKeyResult> searchKey(String iText, String iKeyServer) throws Exception { List<SearchKeyResult> outVec = new ArrayList<SearchKeyResult>(); String uri = iKeyServer + "/pks/lookup?search=" + URLEncoder.encode(iText, UTF8); URL url = new URL(uri); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); Pattern regex = Pattern.compile("pub.*?<a\\s+href\\s*=\"(.*?)\".*?>\\s*(\\w+)\\s*</a>.*?(\\d+-\\d+-\\d+).*?<a\\s+href\\s*=\".*?\".*?>\\s*(.+?)\\s*</a>", Pattern.CANON_EQ); String line; while ((line = input.readLine()) != null) { Matcher regexMatcher = regex.matcher(line); while (regexMatcher.find()) { String id = regexMatcher.group(2); String downUrl = iKeyServer + regexMatcher.group(1); String downDate = regexMatcher.group(3); String name = decodeHTML(regexMatcher.group(4)); outVec.add(new SearchKeyResult(id, name, downDate, downUrl)); } } IOUtils.closeQuietly(input); return outVec; }
11
Code Sample 1: public void markAsCachedHelper(Item item, Date from, Date to, Map<String, Boolean> properties) { if (properties.size() == 0) { return; } Connection conn = null; Iterable<Integer> props = representer.getInternalReps(properties.keySet()); Integer hostIndex = representer.lookUpInternalRep(item.getResolved().getHost()); HashMap<Integer, long[]> periods = new HashMap<Integer, long[]>(); for (Map.Entry<String, Boolean> e : properties.entrySet()) { periods.put(representer.lookUpInternalRep(e.getKey()), new long[] { from.getTime(), to.getTime(), e.getValue() ? 1 : 0 }); } try { conn = getConnection(); conn.setAutoCommit(false); conn.setSavepoint(); PreparedStatement stmt = null; try { stmt = conn.prepareStatement("SELECT MIN(starttime), MAX(endtime), MAX(hasvalues) FROM cachedperiods WHERE " + "id = ? AND host = ? AND prop = ? AND " + "starttime <= ? AND endtime >= ?"); stmt.setString(1, item.getResolved().getId()); stmt.setInt(2, hostIndex); stmt.setLong(4, to.getTime()); stmt.setLong(5, from.getTime()); for (Map.Entry<Integer, long[]> e1 : periods.entrySet()) { stmt.setInt(3, e1.getKey()); ResultSet rs = stmt.executeQuery(); if (rs.next()) { e1.getValue()[0] = Math.min(rs.getLong(1), e1.getValue()[0]); e1.getValue()[1] = Math.max(rs.getLong(2), e1.getValue()[1]); e1.getValue()[2] = Math.max(rs.getInt(3), e1.getValue()[2]); } StorageUtils.close(rs); } StorageUtils.close(stmt); stmt = conn.prepareStatement("DELETE FROM cachedperiods WHERE " + "id = ? AND host = ? AND " + "starttime <= ? AND endtime >= ? AND " + "prop IN (" + StringUtils.join(props.iterator(), ",") + ")"); stmt.setString(1, item.getResolved().getId()); stmt.setInt(2, hostIndex); stmt.setLong(3, to.getTime()); stmt.setLong(4, from.getTime()); stmt.executeUpdate(); StorageUtils.close(stmt); stmt = conn.prepareStatement("INSERT INTO cachedperiods (id, host, prop, starttime, endtime, hasvalues) VALUES (?, ?, ?, ?, ?, ?)"); stmt.setString(1, item.getResolved().getId()); stmt.setInt(2, hostIndex); for (Map.Entry<Integer, long[]> e2 : periods.entrySet()) { stmt.setInt(3, e2.getKey()); stmt.setLong(4, e2.getValue()[0]); stmt.setLong(5, e2.getValue()[1]); stmt.setInt(6, (int) e2.getValue()[2]); stmt.executeUpdate(); } } finally { StorageUtils.close(stmt); } conn.commit(); } catch (SQLException ex) { Logger.getLogger(MetaDataStoragerImpl.class.getName()).log(Level.SEVERE, "Cannot update cachedperiods table.", ex); try { conn.rollback(); } catch (SQLException ex1) { Logger.getLogger(MetaDataStoragerImpl.class.getName()).log(Level.SEVERE, "Could not roll back database, please consult system administrator.", ex1); } } finally { StorageUtils.close(conn); } } Code Sample 2: @Override public void run() { while (true) { StringBuilder buffer = new StringBuilder(128); buffer.append("insert into DOMAIN ( ").append(LS); buffer.append(" DOMAIN_ID, TOP_DOMAIN_ID, DOMAIN_HREF, ").append(LS); buffer.append(" DOMAIN_RANK, DOMAIN_TYPE, DOMAIN_STATUS, ").append(LS); buffer.append(" DOMAIN_ICO_CREATED, DOMAIN_CDATE ").append(LS); buffer.append(") values ( ").append(LS); buffer.append(" null ,null, ?,").append(LS); buffer.append(" 1, 2, 1, ").append(LS); buffer.append(" 0, now() ").append(LS); buffer.append(") ").append(LS); String sqlInsert = buffer.toString(); boolean isAutoCommit = false; int i = 0; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = ConnHelper.getConnection(); conn.setAutoCommit(isAutoCommit); pstmt = conn.prepareStatement(sqlInsert); for (i = 0; i < 10; i++) { String lock = "" + ((int) (Math.random() * 100000000)) % 100; pstmt.setString(1, lock); pstmt.executeUpdate(); } if (!isAutoCommit) conn.commit(); rs = pstmt.executeQuery("select max(DOMAIN_ID) from DOMAIN"); if (rs.next()) { String str = System.currentTimeMillis() + " " + rs.getLong(1); } } catch (Exception e) { try { if (!isAutoCommit) conn.rollback(); } catch (SQLException ex) { ex.printStackTrace(System.out); } String msg = System.currentTimeMillis() + " " + Thread.currentThread().getName() + " - " + i + " " + e.getMessage() + LS; FileIO.writeToFile("D:/DEAD_LOCK.txt", msg, true, "GBK"); } finally { ConnHelper.close(conn, pstmt, rs); } } }
11
Code Sample 1: public static String getHash(String password) { try { MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(password.getBytes()); return new String(digest.digest()); } catch (NoSuchAlgorithmException e) { log.error("Hashing algorithm not found"); return password; } } Code Sample 2: public String getDigest(String s) throws Exception { MessageDigest md = MessageDigest.getInstance(hashName); md.update(s.getBytes()); byte[] dig = md.digest(); return Base16.toHexString(dig); }
11
Code Sample 1: 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); } }); } } Code Sample 2: PackageFileImpl(PackageDirectoryImpl dir, String name, InputStream data) throws IOException { this.dir = dir; this.name = name; this.updates = dir.getUpdates(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); IOUtils.copy(data, stream); updates.setNewData(getFullName(), stream.toByteArray()); stream.close(); }
00
Code Sample 1: public static void copyFile(File destFile, File src) throws IOException { File destDir = destFile.getParentFile(); File tempFile = new File(destFile + "_tmp"); destDir.mkdirs(); InputStream is = new FileInputStream(src); try { FileOutputStream os = new FileOutputStream(tempFile); try { byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); } finally { os.close(); } } finally { is.close(); } destFile.delete(); if (!tempFile.renameTo(destFile)) throw new IOException("Unable to rename " + tempFile + " to " + destFile); } Code Sample 2: private static void checkForUpgrade() { try { Log.out("Checking for updates..."); URL u = ClassLoader.getSystemResource(Settings.readme); if (u == null) { u = HImage.class.getResource("/" + Settings.readme); } DataInputStream i = new DataInputStream(u.openStream()); String tmp = i.readLine(); tmp = tmp.substring(tmp.lastIndexOf(">")); tmp = tmp.substring(tmp.indexOf(".") + 1); tmp = tmp.substring(0, tmp.indexOf("<")); int x = Integer.parseInt(tmp) + 1; String nextVersion = "jftp-1."; if (x < 10) { nextVersion = nextVersion + "0"; } nextVersion = nextVersion + x + ".tar.gz"; File dl = new File(nextVersion); if (!dl.exists() || (dl.length() <= 0)) { URL url = new URL("http://osdn.dl.sourceforge.net/sourceforge/j-ftp/" + nextVersion); BufferedOutputStream f = new BufferedOutputStream(new FileOutputStream(dl)); BufferedInputStream in = new BufferedInputStream(url.openStream()); byte[] buf = new byte[4096]; int stat = 1; Log.out("\ndownloading update: " + dl.getAbsolutePath() + "\n\n"); while (stat > 0) { stat = in.read(buf); if (stat == -1) { break; } f.write(buf, 0, stat); System.out.print("."); } f.flush(); f.close(); in.close(); } Log.out("\n\n\na newer version was found!\nplease install the File " + dl.getAbsolutePath() + " or even better visit the homepage to download the latest version...\n" + "you can turn this feature off if you don't like it (view readme for details)\n\nStarting anyway...\n\n"); } catch (Exception ex) { } Log.out("finished check..."); }
00
Code Sample 1: public void actionPerformed(ActionEvent e) { final File inputFile = KeyboardHero.midiFile(); try { if (inputFile == null) return; final File dir = (new File(Util.DATA_FOLDER + MidiSong.MIDI_FILES_DIR)); if (dir.exists()) { if (!dir.isDirectory()) { Util.error(Util.getMsg("Err_MidiFilesDirNotDirectory"), dir.getParent()); return; } } else if (!dir.mkdirs()) { Util.error(Util.getMsg("Err_CouldntMkDir"), dir.getParent()); return; } File outputFile = new File(dir.getPath() + File.separator + inputFile.getName()); if (!outputFile.exists() || KeyboardHero.confirm("Que_FileExistsOverwrite")) { final FileChannel inChannel = new FileInputStream(inputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), new FileOutputStream(outputFile).getChannel()); } } catch (Exception ex) { Util.getMsg(Util.getMsg("Err_CouldntImportSong"), ex.toString()); } SongSelector.refresh(); } Code Sample 2: protected Properties load(URL url) { try { InputStream i = url.openStream(); Properties p = new Properties(); p.load(i); i.close(); return p; } catch (IOException e) { throw new RuntimeException(e); } }
00
Code Sample 1: public void execute() throws MojoExecutionException, MojoFailureException { try { this.getLog().info("copy source web.xml - " + this.getWebXml() + " to build dir (source web.xml required if mergewebxml execution is enabled)"); File destination = new File(this.getBuildDir(), "web.xml"); if (!destination.exists()) { destination.getParentFile().mkdirs(); destination.createNewFile(); } FileIOUtils.copyFile(this.getWebXml(), destination); for (int i = 0; i < this.getCompileTarget().length; i++) { File moduleFile = null; for (Iterator it = this.getProject().getCompileSourceRoots().iterator(); it.hasNext() && moduleFile == null; ) { File check = new File(it.next().toString() + "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"); getLog().debug("Looking for file: " + check.getAbsolutePath()); if (check.exists()) { moduleFile = check; } } for (Iterator it = this.getProject().getResources().iterator(); it.hasNext(); ) { Resource r = (Resource) it.next(); File check = new File(r.getDirectory() + "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"); getLog().debug("Looking for file: " + check.getAbsolutePath()); if (check.exists()) { moduleFile = check; } } ClassLoader loader = this.fixThreadClasspath(); if (moduleFile == null) { try { String classpath = "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"; InputStream is = loader.getResourceAsStream(classpath); System.out.println("Looking for classpath: " + classpath + "(" + (is != null) + ")"); if (is != null) { File temp = new File(this.getBuildDir(), this.getCompileTarget()[i].concat(".gwt.xml")); FileOutputStream fos = new FileOutputStream(temp); FileIOUtils.copyStream(is, fos); moduleFile = temp; } } catch (IOException e) { this.getLog().info(e); } } GwtWebInfProcessor processor = null; try { if (moduleFile != null) { getLog().info("Module file: " + moduleFile.getAbsolutePath()); processor = new GwtWebInfProcessor(this.getCompileTarget()[i], moduleFile, destination.getAbsolutePath(), destination.getAbsolutePath(), this.isWebXmlServletPathAsIs()); processor.process(); } else { throw new MojoExecutionException("module file null"); } } catch (ExitException e) { this.getLog().info(e.getMessage()); } } } catch (Exception e) { throw new MojoExecutionException("Unable to merge web.xml", e); } } Code Sample 2: public Music(URL url, boolean streamingHint) throws SlickException { SoundStore.get().init(); String ref = url.getFile(); try { if (ref.toLowerCase().endsWith(".ogg")) { if (streamingHint) { sound = SoundStore.get().getOggStream(url); } else { sound = SoundStore.get().getOgg(url.openStream()); } } else if (ref.toLowerCase().endsWith(".wav")) { sound = SoundStore.get().getWAV(url.openStream()); } else if (ref.toLowerCase().endsWith(".xm") || ref.toLowerCase().endsWith(".mod")) { sound = SoundStore.get().getMOD(url.openStream()); } else if (ref.toLowerCase().endsWith(".aif") || ref.toLowerCase().endsWith(".aiff")) { sound = SoundStore.get().getAIF(url.openStream()); } else { throw new SlickException("Only .xm, .mod, .ogg, and .aif/f are currently supported."); } } catch (Exception e) { Log.error(e); throw new SlickException("Failed to load sound: " + url); } }
00
Code Sample 1: private static String getData(String myurl) throws Exception { URL url = new URL(myurl); uc = (HttpURLConnection) url.openConnection(); if (login) { uc.setRequestProperty("Cookie", usercookie + ";" + pwdcookie); } br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String temp = "", k = ""; while ((temp = br.readLine()) != null) { k += temp; } br.close(); return k; } Code Sample 2: private void copia(FileInputStream input, FileOutputStream output) throws ErrorException { if (input == null || output == null) { throw new ErrorException("Param null"); } FileChannel inChannel = input.getChannel(); FileChannel outChannel = output.getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (IOException e) { throw new ErrorException("Casino nella copia del file"); } }
11
Code Sample 1: private void exportJar(File root, List<File> list, Manifest manifest) throws Exception { JarOutputStream jarOut = null; FileInputStream fin = null; try { jarOut = new JarOutputStream(new FileOutputStream(jarFile), manifest); for (int i = 0; i < list.size(); i++) { String filename = list.get(i).getAbsolutePath(); filename = filename.substring(root.getAbsolutePath().length() + 1); fin = new FileInputStream(list.get(i)); JarEntry entry = new JarEntry(filename.replace('\\', '/')); jarOut.putNextEntry(entry); byte[] buf = new byte[4096]; int read; while ((read = fin.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); jarOut.flush(); } } finally { if (fin != null) { try { fin.close(); } catch (Exception e) { ExceptionOperation.operate(e); } } if (jarOut != null) { try { jarOut.close(); } catch (Exception e) { } } } } Code Sample 2: private void initialize() { if (!initialized) { if (context.getJavadocLinks() != null) { for (String url : context.getJavadocLinks()) { if (!url.endsWith("/")) { url += "/"; } StringWriter writer = new StringWriter(); try { IOUtils.copy(new URL(url + "package-list").openStream(), writer); } catch (Exception e) { e.printStackTrace(); continue; } StringTokenizer tokenizer2 = new StringTokenizer(writer.toString()); while (tokenizer2.hasMoreTokens()) { javadocByPackage.put(tokenizer2.nextToken(), url); } } } initialized = true; } }
00
Code Sample 1: public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GUnzip source"); return; } String zipname, source; if (args[0].endsWith(".gz")) { zipname = args[0]; source = args[0].substring(0, args[0].length() - 3); } else { zipname = args[0] + ".gz"; source = args[0]; } GZIPInputStream zipin; try { FileInputStream in = new FileInputStream(zipname); zipin = new GZIPInputStream(in); } catch (IOException e) { System.out.println("Couldn't open " + zipname + "."); return; } byte[] buffer = new byte[sChunk]; try { FileOutputStream out = new FileOutputStream(source); int length; while ((length = zipin.read(buffer, 0, sChunk)) != -1) out.write(buffer, 0, length); out.close(); } catch (IOException e) { System.out.println("Couldn't decompress " + args[0] + "."); } try { zipin.close(); } catch (IOException e) { } } Code Sample 2: public static DBData resolveDBasURL(java.net.URL url) throws Exception { DBData data = null; InputStream fi = null; EnhancedStreamTokenizer tokenizer = null; try { fi = url.openStream(); tokenizer = new EnhancedStreamTokenizer(new BufferedReader(new InputStreamReader(fi))); initializeTokenizer(tokenizer); } catch (Exception e) { Console.getInstance().println("\nError occured while opening URL '" + url.toString() + "'"); Console.getInstance().println(e); return null; } if (tokenizer != null) { try { } finally { System.gc(); } } return data; }
11
Code Sample 1: public boolean copy(File fromFile) throws IOException { FileUtility toFile = this; if (!fromFile.exists()) { abort("FileUtility: no such source file: " + fromFile.getAbsolutePath()); return false; } if (!fromFile.isFile()) { abort("FileUtility: can't copy directory: " + fromFile.getAbsolutePath()); return false; } if (!fromFile.canRead()) { abort("FileUtility: source file is unreadable: " + fromFile.getAbsolutePath()); return false; } if (this.isDirectory()) toFile = (FileUtility) (new File(this, fromFile.getName())); if (toFile.exists()) { if (!toFile.canWrite()) { abort("FileUtility: destination file is unwriteable: " + pathName); return false; } } else { String parent = toFile.getParent(); File dir = new File(parent); if (!dir.exists()) { abort("FileUtility: destination directory doesn't exist: " + parent); return false; } if (dir.isFile()) { abort("FileUtility: destination is not a directory: " + parent); return false; } if (!dir.canWrite()) { abort("FileUtility: destination directory is unwriteable: " + parent); return false; } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } return true; } Code Sample 2: public static Image loadImage(String path) { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = mainFrame.getClass().getResourceAsStream(path); if (in == null) throw new RuntimeException("Ressource " + path + " not found"); try { IOUtils.copy(in, out); in.close(); out.flush(); } catch (IOException e) { e.printStackTrace(); new RuntimeException("Error reading ressource " + path, e); } return Toolkit.getDefaultToolkit().createImage(out.toByteArray()); }
11
Code Sample 1: protected void removeMessage(ReplicationMessage message) { logger.info(String.format("remove replication message: %d", message.getId())); ConnectionProvider cp = null; Connection conn = null; PreparedStatement ps = null; try { SessionFactoryImplementor impl = (SessionFactoryImplementor) portalDao.getSessionFactory(); cp = impl.getConnectionProvider(); conn = cp.getConnection(); conn.setAutoCommit(false); ps = conn.prepareStatement("delete from light_replication_message where id=?"); ps.setLong(1, message.getId()); ps.executeUpdate(); conn.commit(); ps.close(); conn.close(); } catch (Exception e) { try { conn.rollback(); ps.close(); conn.close(); } catch (Exception se) { } } } Code Sample 2: protected static void clearTables() throws SQLException { Connection conn = null; Statement stmt = null; try { conn = FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); ClearData.clearTables(stmt); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (2, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (3, '')"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } }
00
Code Sample 1: private static String processRequest(String request, HttpMethod method) { SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory(); URI uri = null; try { uri = new URI(request); ClientHttpRequest clientHttpRequest = simpleClientHttpRequestFactory.createRequest(uri, method); ClientHttpResponse response = clientHttpRequest.execute(); InputStream bodyInputStream = response.getBody(); String body = org.apache.commons.io.IOUtils.toString(bodyInputStream); return body; } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } Code Sample 2: private void handleUpload(CommonsMultipartFile file, String newFileName, String uploadDir) throws IOException, FileNotFoundException { File dirPath = new File(uploadDir); if (!dirPath.exists()) { dirPath.mkdirs(); } InputStream stream = file.getInputStream(); OutputStream bos = new FileOutputStream(uploadDir + newFileName); IOUtils.copy(stream, bos); }
00
Code Sample 1: public int executeBatch(String[] commands, String applicationid) throws Exception { Statement statement = null; int errors = 0; int commandCount = 0; Connection conn = null; try { conn = getConnection(applicationid); conn.setAutoCommit(false); statement = conn.createStatement(); for (int i = 0; i < commands.length; i++) { String command = commands[i]; if (command.trim().length() == 0) { continue; } commandCount++; try { log.info("executing SQL: " + command); int results = statement.executeUpdate(command); log.info("After execution, " + results + " row(s) have been changed"); } catch (SQLException ex) { throw ex; } } conn.commit(); log.info("Executed " + commandCount + " SQL command(s) with " + errors + " error(s)"); } catch (SQLException ex) { if (conn != null) { conn.rollback(); } throw ex; } catch (Exception e) { if (conn != null) { conn.rollback(); } throw e; } finally { statement.close(); } return errors; } Code Sample 2: protected byte[] getHashedID(String ID) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(ID.getBytes()); byte[] digest = md5.digest(); byte[] bytes = new byte[WLDB_ID_SIZE]; for (int i = 0; i < bytes.length; i++) { bytes[i] = digest[i]; } return bytes; } catch (NoSuchAlgorithmException exception) { System.err.println("Java VM is not compatible"); exit(); return null; } }
11
Code Sample 1: private void publishZip(LWMap map) { try { if (map.getFile() == null) { VueUtil.alert(VueResources.getString("dialog.mapsave.message"), VueResources.getString("dialog.mapsave.title")); return; } File savedCMap = PublishUtil.createZip(map, Publisher.resourceVector); InputStream istream = new BufferedInputStream(new FileInputStream(savedCMap)); OutputStream ostream = new BufferedOutputStream(new FileOutputStream(ActionUtil.selectFile("Export to Zip File", "zip"))); int fileLength = (int) savedCMap.length(); byte bytes[] = new byte[fileLength]; while (istream.read(bytes, 0, fileLength) != -1) ostream.write(bytes, 0, fileLength); istream.close(); ostream.close(); } catch (Exception ex) { System.out.println(ex); VueUtil.alert(VUE.getDialogParent(), VueResources.getString("dialog.export.message") + ex.getMessage(), VueResources.getString("dialog.export.title"), JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { File inputFile = src; File outputFile = dst; FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
00
Code Sample 1: public static byte[] readFile(String filePath) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); FileInputStream is = new FileInputStream(filePath); try { IOUtils.copy(is, os); return os.toByteArray(); } finally { is.close(); } } Code Sample 2: public boolean check(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(username.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(realm.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(password.getBytes("ISO-8859-1")); byte[] ha1 = md.digest(); String hexHa1 = new String(Hex.encodeHex(ha1)); md.reset(); md.update(method.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(uri.getBytes("ISO-8859-1")); byte[] ha2 = md.digest(); String hexHa2 = new String(Hex.encodeHex(ha2)); md.reset(); md.update(hexHa1.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(nonce.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(nc.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(cnonce.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(qop.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(hexHa2.getBytes("ISO-8859-1")); byte[] digest = md.digest(); String hexDigest = new String(Hex.encodeHex(digest)); return (hexDigest.equalsIgnoreCase(response)); }
11
Code Sample 1: public void save(InputStream is) throws IOException { File dest = Config.getDataFile(getInternalDate(), getPhysMessageID()); OutputStream os = null; try { os = new FileOutputStream(dest); IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } } 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: public void doActionOn(TomcatProject prj) throws Exception { String path = TomcatLauncherPlugin.getDefault().getManagerAppUrl(); try { path += "/reload?path=" + prj.getWebPath(); URL url = new URL(path); Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { String user = TomcatLauncherPlugin.getDefault().getManagerAppUser(); String password = TomcatLauncherPlugin.getDefault().getManagerAppPassword(); return new PasswordAuthentication(user, password.toCharArray()); } }); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.getContent(); connection.disconnect(); Authenticator.setDefault(null); } catch (Exception e) { throw new Exception("The following url was used : \n" + path + "\n\nCheck manager app settings (username and password)\n\n"); } } 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; }
00
Code Sample 1: Object execute(String method, Vector params) throws XmlRpcException, IOException { fault = false; long now = 0; if (XmlRpc.debug) { System.err.println("Client calling procedure '" + method + "' with parameters " + params); now = System.currentTimeMillis(); } try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); if (buffer == null) { buffer = new ByteArrayOutputStream(); } else { buffer.reset(); } XmlWriter writer = new XmlWriter(buffer); writeRequest(writer, method, params); writer.flush(); byte[] request = buffer.toByteArray(); URLConnection con = url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setAllowUserInteraction(false); con.setRequestProperty("Content-Length", Integer.toString(request.length)); con.setRequestProperty("Content-Type", "text/xml"); if (auth != null) { con.setRequestProperty("Authorization", "Basic " + auth); } OutputStream out = con.getOutputStream(); out.write(request); out.flush(); out.close(); InputStream in = con.getInputStream(); parse(in); } catch (Exception x) { if (XmlRpc.debug) { x.printStackTrace(); } throw new IOException(x.getMessage()); } if (fault) { XmlRpcException exception = null; try { Hashtable f = (Hashtable) result; String faultString = (String) f.get("faultString"); int faultCode = Integer.parseInt(f.get("faultCode").toString()); exception = new XmlRpcException(faultCode, faultString.trim()); } catch (Exception x) { throw new XmlRpcException(0, "Invalid fault response"); } throw exception; } if (XmlRpc.debug) { System.err.println("Spent " + (System.currentTimeMillis() - now) + " in request"); } return result; } Code Sample 2: private boolean downloadBlacklist() { boolean blacklist_updated = false; try { mLogger.debug("Attempting to download MT blacklist"); URL url = new URL(blacklistURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); if (this.lastModified != null) { connection.setRequestProperty("If-Modified-Since", DateUtil.formatRfc822(this.lastModified)); } int responseCode = connection.getResponseCode(); mLogger.debug("HttpConnection response = " + responseCode); if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) { mLogger.debug("MT blacklist site says we are current"); return false; } long lastModifiedLong = connection.getHeaderFieldDate("Last-Modified", -1); if (responseCode == HttpURLConnection.HTTP_OK && (this.lastModified == null || this.lastModified.getTime() < lastModifiedLong)) { mLogger.debug("my last modified = " + this.lastModified.getTime()); mLogger.debug("MT last modified = " + lastModifiedLong); InputStream instream = connection.getInputStream(); String uploadDir = RollerConfig.getProperty("uploads.dir"); String path = uploadDir + File.separator + blacklistFile; FileOutputStream outstream = new FileOutputStream(path); mLogger.debug("writing updated MT blacklist to " + path); byte[] buf = new byte[4096]; int length = 0; while ((length = instream.read(buf)) > 0) outstream.write(buf, 0, length); outstream.close(); instream.close(); blacklist_updated = true; mLogger.debug("MT blacklist download completed."); } else { mLogger.debug("blacklist *NOT* saved, assuming we are current"); } } catch (Exception e) { mLogger.error("error downloading blacklist", e); } return blacklist_updated; }
00
Code Sample 1: private void addJarToPackages(URL jarurl, File jarfile, boolean cache) { try { boolean caching = this.jarfiles != null; URLConnection jarconn = null; boolean localfile = true; if (jarfile == null) { jarconn = jarurl.openConnection(); if (jarconn.getURL().getProtocol().equals("file")) { String jarfilename = jarurl.getFile(); jarfilename = jarfilename.replace('/', File.separatorChar); jarfile = new File(jarfilename); } else { localfile = false; } } if (localfile && !jarfile.exists()) { return; } Hashtable zipPackages = null; long mtime = 0; String jarcanon = null; JarXEntry entry = null; boolean brandNew = false; if (caching) { if (localfile) { mtime = jarfile.lastModified(); jarcanon = jarfile.getCanonicalPath(); } else { mtime = jarconn.getLastModified(); jarcanon = jarurl.toString(); } entry = (JarXEntry) this.jarfiles.get(jarcanon); if ((entry == null || !(new File(entry.cachefile).exists())) && cache) { message("processing new jar, '" + jarcanon + "'"); String jarname; if (localfile) { jarname = jarfile.getName(); } else { jarname = jarurl.getFile(); int slash = jarname.lastIndexOf('/'); if (slash != -1) jarname = jarname.substring(slash + 1); } jarname = jarname.substring(0, jarname.length() - 4); entry = new JarXEntry(jarname); this.jarfiles.put(jarcanon, entry); brandNew = true; } if (mtime != 0 && entry != null && entry.mtime == mtime) { zipPackages = readCacheFile(entry, jarcanon); } } if (zipPackages == null) { caching = caching && cache; if (caching) { this.indexModified = true; if (entry.mtime != 0) { message("processing modified jar, '" + jarcanon + "'"); } entry.mtime = mtime; } InputStream jarin; if (jarconn == null) { jarin = new BufferedInputStream(new FileInputStream(jarfile)); } else { jarin = jarconn.getInputStream(); } zipPackages = getZipPackages(jarin); if (caching) { writeCacheFile(entry, jarcanon, zipPackages, brandNew); } } addPackages(zipPackages, jarcanon); } catch (IOException ioe) { ioe.printStackTrace(); warning("skipping bad jar, '" + (jarfile != null ? jarfile.toString() : jarurl.toString()) + "'"); } } Code Sample 2: @Test public void testImageshackUpload() throws Exception { request.setUrl("http://www.imageshack.us/index.php"); request.addParameter("xml", "yes"); request.setFile("fileupload", file); HttpResponse response = httpClient.execute(request); assertTrue(response.is2xxSuccess()); assertTrue(response.getResponseHeaders().size() > 0); String body = IOUtils.toString(response.getResponseBody()); assertTrue(body.contains("<image_link>")); assertTrue(body.contains("<thumb_link>")); assertTrue(body.contains("<image_location>")); assertTrue(body.contains("<image_name>")); response.close(); }
00
Code Sample 1: @Test public void testValidLogConfiguration() throws IOException, IllegalArgumentException { URL url = ClassLoader.getSystemResource(PROPERTIES_FILE_NAME); if (url == null) { throw new IOException("Could not find configuration file " + PROPERTIES_FILE_NAME + " in class path"); } Properties properties = new Properties(); properties.load(url.openStream()); LogLevel logLevel = LogLevel.valueOf((String) properties.get(PROPERTY_KEY_LOGLEVEL)); if (logLevel == null) { throw new IOException("Invalid configuration file " + PROPERTIES_FILE_NAME + ": no entry for " + PROPERTY_KEY_LOGLEVEL); } String loggerIdentifier = "Test logger"; Logger logger = LoggerFactory.getLogger(loggerIdentifier); assertEquals("Logger has wrong log level", logLevel, logger.getLogLevel()); } Code Sample 2: @Override public final byte[] getDigest() { try { final MessageDigest hashing = MessageDigest.getInstance("SHA-256"); final Charset utf16 = Charset.forName("UTF-16"); for (final CollationKey wordKey : this.words) { hashing.update(wordKey.toByteArray()); } hashing.update(this.locale.toString().getBytes(utf16)); hashing.update(ByteUtils.toBytesLE(this.collator.getStrength())); hashing.update(ByteUtils.toBytesLE(this.collator.getDecomposition())); return hashing.digest(); } catch (final NoSuchAlgorithmException e) { FileBasedDictionary.LOG.severe(e.toString()); return new byte[0]; } }
11
Code Sample 1: private void writeJar() { try { File outJar = new File(currentProjectDir + DEPLOYDIR + fileSeparator + currentProjectName + ".jar"); jarSize = (int) outJar.length(); File tempJar = File.createTempFile("hipergps" + currentProjectName, ".jar"); tempJar.deleteOnExit(); File preJar = new File(currentProjectDir + "/res/wtj2me.jar"); JarInputStream preJarInStream = new JarInputStream(new FileInputStream(preJar)); Manifest mFest = preJarInStream.getManifest(); java.util.jar.Attributes atts = mFest.getMainAttributes(); if (hiperGeoId != null) { atts.putValue("hiperGeoId", hiperGeoId); } jad.updateAttributes(atts); JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(tempJar), mFest); byte[] buffer = new byte[WalkingtoolsInformation.BUFFERSIZE]; JarEntry jarEntry = null; while ((jarEntry = preJarInStream.getNextJarEntry()) != null) { if (jarEntry.getName().contains("net/") || jarEntry.getName().contains("org/")) { try { jarOutStream.putNextEntry(jarEntry); } catch (ZipException ze) { continue; } int read; while ((read = preJarInStream.read(buffer)) != -1) { jarOutStream.write(buffer, 0, read); } jarOutStream.closeEntry(); } } File[] icons = { new File(currentProjectDir + WalkingtoolsInformation.IMAGEDIR + fileSeparator + "icon_" + WalkingtoolsInformation.MEDIAUUID + ".png"), new File(currentProjectDir + WalkingtoolsInformation.IMAGEDIR + fileSeparator + "loaderIcon_" + WalkingtoolsInformation.MEDIAUUID + ".png"), new File(currentProjectDir + WalkingtoolsInformation.IMAGEDIR + fileSeparator + "mygps_" + WalkingtoolsInformation.MEDIAUUID + ".png") }; for (int i = 0; i < icons.length; i++) { jarEntry = new JarEntry("img/" + icons[i].getName()); try { jarOutStream.putNextEntry(jarEntry); } catch (ZipException ze) { continue; } FileInputStream in = new FileInputStream(icons[i]); while (true) { int read = in.read(buffer, 0, buffer.length); if (read <= 0) { break; } jarOutStream.write(buffer, 0, read); } in.close(); } for (int i = 0; i < imageFiles.size(); i++) { jarEntry = new JarEntry("img/" + imageFiles.get(i).getName()); try { jarOutStream.putNextEntry(jarEntry); } catch (ZipException ze) { continue; } FileInputStream in = new FileInputStream(imageFiles.get(i)); while (true) { int read = in.read(buffer, 0, buffer.length); if (read <= 0) { break; } jarOutStream.write(buffer, 0, read); } in.close(); } for (int i = 0; i < audioFiles.size(); i++) { jarEntry = new JarEntry("audio/" + audioFiles.get(i).getName()); try { jarOutStream.putNextEntry(jarEntry); } catch (ZipException ze) { continue; } FileInputStream in = new FileInputStream(audioFiles.get(i)); while (true) { int read = in.read(buffer, 0, buffer.length); if (read <= 0) { break; } jarOutStream.write(buffer, 0, read); } in.close(); } File gpx = new File(currentProjectDir + WalkingtoolsInformation.GPXDIR + "/hipergps.gpx"); jarEntry = new JarEntry("gpx/" + gpx.getName()); jarOutStream.putNextEntry(jarEntry); FileInputStream in = new FileInputStream(gpx); while (true) { int read = in.read(buffer, 0, buffer.length); if (read <= 0) { break; } jarOutStream.write(buffer, 0, read); } in.close(); jarOutStream.flush(); jarOutStream.close(); jarSize = (int) tempJar.length(); preJarInStream = new JarInputStream(new FileInputStream(tempJar)); mFest = preJarInStream.getManifest(); atts = mFest.getMainAttributes(); atts.putValue("MIDlet-Jar-Size", "" + jarSize + 1); jarOutStream = new JarOutputStream(new FileOutputStream(outJar), mFest); while ((jarEntry = preJarInStream.getNextJarEntry()) != null) { try { jarOutStream.putNextEntry(jarEntry); } catch (ZipException ze) { continue; } int read; while ((read = preJarInStream.read(buffer)) != -1) { jarOutStream.write(buffer, 0, read); } jarOutStream.closeEntry(); } jarOutStream.flush(); preJarInStream.close(); jarOutStream.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } Code Sample 2: private void exportJar(File root, List<File> list, Manifest manifest) throws Exception { JarOutputStream jarOut = null; FileInputStream fin = null; try { jarOut = new JarOutputStream(new FileOutputStream(jarFile), manifest); for (int i = 0; i < list.size(); i++) { String filename = list.get(i).getAbsolutePath(); filename = filename.substring(root.getAbsolutePath().length() + 1); fin = new FileInputStream(list.get(i)); JarEntry entry = new JarEntry(filename.replace('\\', '/')); jarOut.putNextEntry(entry); byte[] buf = new byte[4096]; int read; while ((read = fin.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); jarOut.flush(); } } finally { if (fin != null) { try { fin.close(); } catch (Exception e) { ExceptionOperation.operate(e); } } if (jarOut != null) { try { jarOut.close(); } catch (Exception e) { } } } }
00
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: protected static File UrlToFile(String urlSt) throws CaughtException { try { logger.info("copy from url: " + urlSt); URL url = new URL(urlSt); InputStream input = url.openStream(); File dir = tempDir; File tempFile = new File(tempDir + File.separator + fileName(url)); logger.info("created: " + tempFile.getAbsolutePath()); copyFile(tempFile, input); return tempFile; } catch (IOException e) { throw new CaughtException(e, logger); } }
11
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.closeQuietly(output); } } finally { IOUtils.closeQuietly(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: public void copyTo(File folder) { if (!isNewFile()) { return; } if (!folder.exists()) { folder.mkdir(); } File dest = new File(folder, name); try { FileInputStream in = new FileInputStream(currentPath); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; long totalCopiedSize = 0; boolean canceled = false; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); if (canceled) { dest.delete(); } else { currentPath = dest; newFile = false; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public static String hash(String str) { if (str == null || str.length() == 0) { throw new CaptureSecurityException("String to encript cannot be null or zero length"); } StringBuilder hexString = new StringBuilder(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (byte element : hash) { if ((0xff & element) < 0x10) { hexString.append('0').append(Integer.toHexString((0xFF & element))); } else { hexString.append(Integer.toHexString(0xFF & element)); } } } catch (NoSuchAlgorithmException e) { throw new CaptureSecurityException(e); } return hexString.toString(); } Code Sample 2: protected BufferedImage handleNLIBException() { if (params.uri.startsWith("http://digar.nlib.ee/otsing/") || params.uri.startsWith("http://digar.nlib.ee/show")) try { String url = "http://digar.nlib.ee/gmap/nd" + params.uri.substring(params.uri.indexOf(":") + 1, params.uri.lastIndexOf("&")) + "-tiles/z0x0y0.jpeg"; URLConnection connection = new URL(url).openConnection(); return processNewUri(connection); } catch (Exception e) { try { if (params.uri.startsWith("http://digar.nlib.ee/show")) params.uri = "http://digar.nlib.ee/otsing/?pid=" + params.uri.substring(params.uri.lastIndexOf("/") + 1) + "&show"; URLConnection connection = new URL(params.uri).openConnection(); String url = params.uri; if (url.endsWith("&show")) url = url.substring(0, url.length() - 5); int index = url.lastIndexOf("?"); url = "stream" + url.substring(index); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String aux = null; while ((aux = reader.readLine()) != null) { index = aux.indexOf(url); if (index != -1) { url = "http://digar.nlib.ee/otsing/" + aux.substring(index); index = url.indexOf('>'); if (index == -1) index = url.indexOf("\""); url = url.substring(0, index); break; } } connection = new URL(url).openConnection(); return processNewUri(connection); } catch (Exception e2) { } } return null; }
00
Code Sample 1: public void getFile(String url, String filepath) throws BggException { System.out.println(url); int retry = retryCount + 1; lastURL = url; for (retriedCount = 0; retriedCount < retry; retriedCount++) { int responseCode = -1; try { HttpURLConnection con = null; BufferedInputStream bis = null; OutputStream osw = null; try { con = (HttpURLConnection) new URL(url).openConnection(); con.setDoInput(true); setHeaders(con); con.setRequestMethod("GET"); responseCode = con.getResponseCode(); bis = new BufferedInputStream(con.getInputStream()); int data; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filepath)); while ((data = bis.read()) != -1) bos.write(data); bos.flush(); bos.close(); break; } finally { try { bis.close(); } catch (Exception ignore) { } try { osw.close(); } catch (Exception ignore) { } try { con.disconnect(); } catch (Exception ignore) { } } } catch (IOException ioe) { if (responseCode == UNAUTHORIZED || responseCode == FORBIDDEN) { throw new BggException(ioe.getMessage(), responseCode); } if (retriedCount == retryCount) { throw new BggException(ioe.getMessage(), responseCode); } } try { Thread.sleep(retryIntervalMillis); } catch (InterruptedException ignore) { } } } Code Sample 2: public byte[] getResponseContent() throws IOException { if (responseContent == null) { InputStream is = getResponseStream(); if (is == null) { responseContent = new byte[0]; } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); IOUtils.copy(is, baos); responseContent = baos.toByteArray(); } } return responseContent; }
11
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 { 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: protected static IFile createTempFile(CodeFile codeFile) { IPath path = Util.getAbsolutePathFromCodeFile(codeFile); File file = new File(path.toOSString()); String[] parts = codeFile.getName().split("\\."); String extension = parts[parts.length - 1]; IPath ext = path.addFileExtension(extension); File tempFile = new File(ext.toOSString()); if (tempFile.exists()) { boolean deleted = tempFile.delete(); System.out.println("deleted: " + deleted); } try { boolean created = tempFile.createNewFile(); if (created) { FileOutputStream fos = new FileOutputStream(tempFile); FileInputStream fis = new FileInputStream(file); while (fis.available() > 0) { fos.write(fis.read()); } fis.close(); fos.close(); IFile iFile = Util.getFileFromPath(ext); return iFile; } } catch (IOException e) { e.printStackTrace(); } return null; }
11
Code Sample 1: public static boolean copyFile(String fileIn, String fileOut) { FileChannel in = null; FileChannel out = null; boolean retour = false; try { in = new FileInputStream(fileIn).getChannel(); out = new FileOutputStream(fileOut).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); retour = true; } catch (IOException e) { System.err.println("File : " + fileIn); e.printStackTrace(); } return retour; } Code Sample 2: public void onMessage(Message message) { try { ExchangeImpl ex = new ExchangeImpl(); ex.setInMessage(message); Conduit backChannel = message.getDestination().getBackChannel(message, null, null); MessageImpl res = new MessageImpl(); res.put(Message.CONTENT_TYPE, "text/html"); backChannel.prepare(res); OutputStream out = res.getContent(OutputStream.class); FileInputStream is = new FileInputStream("test.html"); IOUtils.copy(is, out, 2048); out.flush(); out.close(); is.close(); backChannel.close(res); } catch (Exception e) { e.printStackTrace(); } }