label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public static void main(final String[] args) throws RecognitionException, TokenStreamException, IOException, IllegalOptionValueException, UnknownOptionException { try { CmdLineParser cmdLineParser = new CmdLineParser(); Option formatOption = cmdLineParser.addStringOption('f', "format"); Option encodingOption = cmdLineParser.addStringOption('c', "charset"); cmdLineParser.parse(args); String format = (String) cmdLineParser.getOptionValue(formatOption); String encoding = (String) cmdLineParser.getOptionValue(encodingOption); if (encoding == null || encoding.trim().equals("")) { encoding = "utf-8"; System.out.println("Defaulting to output charset utf-8 as argument -c is missing or not valid."); } String[] remainingArgs = cmdLineParser.getRemainingArgs(); if (remainingArgs.length != 2) { printUsage("Input and output file are not specified correctly. "); } File inputFile = new File(remainingArgs[0]); if (!inputFile.exists()) { printUsage("Input file " + remainingArgs[0] + " does not exist. "); } File outputFile = new File(remainingArgs[1]); if (!outputFile.exists()) { outputFile.createNewFile(); } if (format == null || format.trim().equals("")) { format = (String) FileUtil.cutExtension(outputFile.getName()).getValue(); } if ("tex".equals(format)) { Reader reader = new LatexEncoderReader(new FileReader(inputFile)); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(outputFile), encoding); char[] buffer = new char[1024]; int read; do { read = reader.read(buffer); if (read > 0) { out.write(buffer, 0, read); } } while (read != -1); out.flush(); out.close(); } else { printUsage("Format not specified via argument -f. Also guessing for the extension of output file " + outputFile.getName() + " failed"); } } catch (Exception ex) { ex.printStackTrace(); printUsage(ex.getMessage()); } } 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) { } } } }
11
Code Sample 1: @Override public boolean copyFile(String srcRootPath, String srcDir, String srcFileName, String destRootPath, String destDir, String destFileName) { File srcPath = new File(srcRootPath + separator() + Database.getDomainName() + separator() + srcDir); if (!srcPath.exists()) { try { srcPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + srcPath); return false; } } File destPath = new File(destRootPath + separator() + Database.getDomainName() + separator() + destDir); if (!destPath.exists()) { try { destPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + destPath); return false; } } File from = new File(srcPath + separator() + srcFileName); File to = new File(destPath + separator() + destFileName); boolean res = true; FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(from).getChannel(); destChannel = new FileOutputStream(to).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (Exception ex) { logger.error("Exception", ex); res = false; } finally { if (destChannel != null) { try { destChannel.close(); } catch (IOException ex) { logger.error("Exception", ex); res = false; } } if (srcChannel != null) { try { srcChannel.close(); } catch (IOException ex) { logger.error("Exception", ex); res = false; } } } return res; } Code Sample 2: private void invokeTest(String queryfile, String target) { try { String query = IOUtils.toString(XPathMarkBenchmarkTest.class.getResourceAsStream(queryfile)).trim(); String args = EXEC_CMD + " \"" + query + "\" \"" + target + '"'; System.out.println("Invoke command: \n " + args); Process proc = Runtime.getRuntime().exec(args, null, benchmarkDir); InputStream is = proc.getInputStream(); File outFile = new File(outDir, queryfile + ".result"); IOUtils.copy(is, new FileOutputStream(outFile)); is.close(); int ret = proc.waitFor(); if (ret != 0) { System.out.println("process exited with value : " + ret); } } catch (IOException ioe) { throw new IllegalStateException(ioe); } catch (InterruptedException irre) { throw new IllegalStateException(irre); } }
11
Code Sample 1: public static void resourceToFile(final String resource, final String filePath) throws IOException { log.debug("Classloader is " + IOCopyUtils.class.getClassLoader()); InputStream in = IOCopyUtils.class.getResourceAsStream(resource); if (in == null) { log.warn("Resource not '" + resource + "' found. Try to prefix with '/'"); in = IOCopyUtils.class.getResourceAsStream("/" + resource); } if (in == null) { throw new IOException("Resource not '" + resource + "' found."); } final File file = new File(filePath); final OutputStream out = FileUtils.openOutputStream(file); final int bytes = IOUtils.copy(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); log.debug("Copied resource '" + resource + "' to file " + filePath + " (" + bytes + " bytes)"); } Code Sample 2: public void unzip(String zipFileName, String outputDirectory) throws Exception { ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName)); ZipEntry z; while ((z = in.getNextEntry()) != null) { System.out.println("unziping " + z.getName()); if (z.isDirectory()) { String name = z.getName(); name = name.substring(0, name.length() - 1); File f = new File(outputDirectory + File.separator + name); f.mkdir(); System.out.println("mkdir " + outputDirectory + File.separator + name); } else { File f = new File(outputDirectory + File.separator + z.getName()); f.createNewFile(); FileOutputStream out = new FileOutputStream(f); int b; while ((b = in.read()) != -1) out.write(b); out.close(); } } in.close(); }
00
Code Sample 1: private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri, ClientConnectionManager connectionManager) { InputStream contentInput = null; if (connectionManager == null) { try { URL url = new URI(uri).toURL(); URLConnection conn = url.openConnection(); conn.connect(); contentInput = conn.getInputStream(); } catch (Exception e) { Log.w(TAG, "Request failed: " + uri); e.printStackTrace(); return null; } } else { final DefaultHttpClient mHttpClient = new DefaultHttpClient(connectionManager, HTTP_PARAMS); HttpUriRequest request = new HttpGet(uri); HttpResponse httpResponse = null; try { httpResponse = mHttpClient.execute(request); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { contentInput = entity.getContent(); } } catch (Exception e) { Log.w(TAG, "Request failed: " + request.getURI()); return null; } } if (contentInput != null) { return new BufferedInputStream(contentInput, 4096); } else { return null; } } Code Sample 2: protected Object doExecute() throws Exception { if (args.size() == 1 && "-".equals(args.get(0))) { log.info("Printing STDIN"); cat(new BufferedReader(io.in), io); } else { for (String filename : args) { BufferedReader reader; try { URL url = new URL(filename); log.info("Printing URL: " + url); reader = new BufferedReader(new InputStreamReader(url.openStream())); } catch (MalformedURLException ignore) { File file = new File(filename); log.info("Printing file: " + file); reader = new BufferedReader(new FileReader(file)); } try { cat(reader, io); } finally { IOUtil.close(reader); } } } return SUCCESS; }
00
Code Sample 1: private String generateHash(String key, String data) throws ChiropteraException { try { MessageDigest md = MessageDigest.getInstance(Constants.Connection.Auth.MD5); md.update(key.getBytes()); byte[] raw = md.digest(); String s = toHexString(raw); SecretKey skey = new SecretKeySpec(s.getBytes(), Constants.Connection.Auth.HMACMD5); Mac mac = Mac.getInstance(skey.getAlgorithm()); mac.init(skey); byte digest[] = mac.doFinal(data.getBytes()); String digestB64 = BaculaBase64.binToBase64(digest); return digestB64.substring(0, digestB64.length()); } catch (NoSuchAlgorithmException e) { throw new ChiropteraException(Constants.Chiroptera.Errors.HASH, e.getMessage(), e); } catch (InvalidKeyException e) { throw new ChiropteraException(Constants.Chiroptera.Errors.HASH, e.getMessage(), e); } } Code Sample 2: 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); } }
11
Code Sample 1: public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } } Code Sample 2: private void copyFile(File source, File target) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
11
Code Sample 1: public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: private void copyFile(File source, File target) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
00
Code Sample 1: private static void executeSQLScript() { File f = new File(System.getProperty("user.dir") + "/resources/umc.sql"); if (f.exists()) { Connection con = null; PreparedStatement pre_stmt = null; try { Class.forName("org.sqlite.JDBC"); con = DriverManager.getConnection("jdbc:sqlite:database/umc.db", "", ""); BufferedReader br = new BufferedReader(new FileReader(f)); String line = ""; con.setAutoCommit(false); while ((line = br.readLine()) != null) { if (!line.equals("") && !line.startsWith("--") && !line.contains("--")) { log.debug(line); pre_stmt = con.prepareStatement(line); pre_stmt.executeUpdate(); } } con.commit(); File dest = new File(f.getAbsolutePath() + ".executed"); if (dest.exists()) dest.delete(); f.renameTo(dest); f.delete(); } catch (Throwable exc) { log.error("Fehler bei Ausführung der SQL Datei", exc); try { con.rollback(); } catch (SQLException exc1) { } } finally { try { if (pre_stmt != null) pre_stmt.close(); if (con != null) con.close(); } catch (SQLException exc2) { log.error("Fehler bei Ausführung von SQL Datei", exc2); } } } } Code Sample 2: public void run() { try { ThreadGroup transfers = new ThreadGroup("transfers"); URL url = new URL("jar:http://jopenrpg.sourceforge.net/files/dev/pythonlib.jar!/"); JarURLConnection juc = (JarURLConnection) url.openConnection(); File top = new File(System.getProperty("user.home"), "jopenrpg"); final JarFile jarfile = juc.getJarFile(); Enumeration enumer = jarfile.entries(); while (enumer.hasMoreElements()) { final JarEntry entry = (JarEntry) enumer.nextElement(); final File f = new File(top, entry.getName()); if (entry.isDirectory()) { f.mkdirs(); } else { if (!entry.getName().startsWith("META-INF")) new Thread(transfers, new Runnable() { public void run() { try { BufferedReader br = new BufferedReader(new InputStreamReader(jarfile.getInputStream(entry))); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f))); StringBuffer buf = new StringBuffer(); while (br.ready()) { buf.append(br.read()); } bw.write(buf.toString(), 0, buf.length()); bw.close(); br.close(); } catch (Exception ex) { System.out.println(ex); } } }).start(); } } while (transfers.activeCount() > 0) yield(); SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(ReferenceManager.getInstance().getMainFrame(), "Jython libraries installed."); } }); } catch (Exception ex) { ex.printStackTrace(); } }
11
Code Sample 1: private void updateUser(AddEditUserForm addform, HttpServletRequest request) throws Exception { Session hbsession = HibernateUtil.currentSession(); try { Transaction tx = hbsession.beginTransaction(); NvUsers user = (NvUsers) hbsession.load(NvUsers.class, addform.getLogin()); if (!addform.getPassword().equalsIgnoreCase("")) { MessageDigest md = (MessageDigest) MessageDigest.getInstance("MD5").clone(); md.update(addform.getPassword().getBytes("UTF-8")); byte[] pd = md.digest(); StringBuffer app = new StringBuffer(); for (int i = 0; i < pd.length; i++) { String s2 = Integer.toHexString(pd[i] & 0xFF); app.append((s2.length() == 1) ? "0" + s2 : s2); } user.setPassword(app.toString()); } ActionErrors errors = new ActionErrors(); HashMap cAttrs = addform.getCustomAttrs(); Query q1 = hbsession.createQuery("from org.nodevision.portal.hibernate.om.NvCustomAttrs as a"); Iterator attrs = q1.iterate(); HashMap attrInfos = new HashMap(); while (attrs.hasNext()) { NvCustomAttrs element = (NvCustomAttrs) attrs.next(); attrInfos.put(element.getAttrName(), element.getAttrType()); NvCustomValuesId id = new NvCustomValuesId(); id.setNvUsers(user); NvCustomValues value = new NvCustomValues(); id.setNvCustomAttrs(element); value.setId(id); if (element.getAttrType().equalsIgnoreCase("String")) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream serializer = new ObjectOutputStream(bout); serializer.writeObject(cAttrs.get(element.getAttrName()).toString()); value.setAttrValue(Hibernate.createBlob(bout.toByteArray())); } else if (element.getAttrType().equalsIgnoreCase("Boolean")) { Boolean valueBoolean = Boolean.FALSE; if (cAttrs.get(element.getAttrName()) != null) { valueBoolean = Boolean.TRUE; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream serializer = new ObjectOutputStream(bout); serializer.writeObject(valueBoolean); value.setAttrValue(Hibernate.createBlob(bout.toByteArray())); } else if (element.getAttrType().equalsIgnoreCase("Date")) { Date date = new Date(0); if (!cAttrs.get(element.getAttrName()).toString().equalsIgnoreCase("")) { String bdate = cAttrs.get(element.getAttrName()).toString(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); date = df.parse(bdate); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream serializer = new ObjectOutputStream(bout); serializer.writeObject(date); value.setAttrValue(Hibernate.createBlob(bout.toByteArray())); } hbsession.saveOrUpdate(value); hbsession.flush(); } String bdate = addform.getUser_bdate(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); Date parsedDate = df.parse(bdate); user.setTimezone(addform.getTimezone()); user.setLocale(addform.getLocale()); user.setBdate(new BigDecimal(parsedDate.getTime())); user.setGender(addform.getUser_gender()); user.setEmployer(addform.getEmployer()); user.setDepartment(addform.getDepartment()); user.setJobtitle(addform.getJobtitle()); user.setNamePrefix(addform.getName_prefix()); user.setNameGiven(addform.getName_given()); user.setNameFamily(addform.getName_famliy()); user.setNameMiddle(addform.getName_middle()); user.setNameSuffix(addform.getName_suffix()); user.setHomeName(addform.getHome_name()); user.setHomeStreet(addform.getHome_street()); user.setHomeStateprov(addform.getHome_stateprov()); user.setHomePostalcode(addform.getHome_postalcode().equalsIgnoreCase("") ? new Integer(0) : new Integer(addform.getHome_postalcode())); user.setHomeOrganization(addform.getHome_organization_name()); user.setHomeCountry(addform.getHome_country()); user.setHomeCity(addform.getHome_city()); user.setHomePhoneIntcode((addform.getHome_phone_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_intcode())); user.setHomePhoneLoccode((addform.getHome_phone_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_loccode())); user.setHomePhoneNumber((addform.getHome_phone_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_number())); user.setHomePhoneExt((addform.getHome_phone_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_ext())); user.setHomePhoneComment(addform.getHome_phone_commment()); user.setHomeFaxIntcode((addform.getHome_fax_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_intcode())); user.setHomeFaxLoccode((addform.getHome_fax_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_loccode())); user.setHomeFaxNumber((addform.getHome_fax_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_number())); user.setHomeFaxExt((addform.getHome_fax_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_ext())); user.setHomeFaxComment(addform.getHome_fax_commment()); user.setHomeMobileIntcode((addform.getHome_mobile_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_intcode())); user.setHomeMobileLoccode((addform.getHome_mobile_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_loccode())); user.setHomeMobileNumber((addform.getHome_mobile_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_number())); user.setHomeMobileExt((addform.getHome_mobile_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_ext())); user.setHomeMobileComment(addform.getHome_mobile_commment()); user.setHomePagerIntcode((addform.getHome_pager_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_intcode())); user.setHomePagerLoccode((addform.getHome_pager_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_loccode())); user.setHomePagerNumber((addform.getHome_pager_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_number())); user.setHomePagerExt((addform.getHome_pager_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_ext())); user.setHomePagerComment(addform.getHome_pager_commment()); user.setHomeUri(addform.getHome_uri()); user.setHomeEmail(addform.getHome_email()); user.setBusinessName(addform.getBusiness_name()); user.setBusinessStreet(addform.getBusiness_street()); user.setBusinessStateprov(addform.getBusiness_stateprov()); user.setBusinessPostalcode((addform.getBusiness_postalcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_postalcode())); user.setBusinessOrganization(addform.getBusiness_organization_name()); user.setBusinessCountry(addform.getBusiness_country()); user.setBusinessCity(addform.getBusiness_city()); user.setBusinessPhoneIntcode((addform.getBusiness_phone_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_intcode())); user.setBusinessPhoneLoccode((addform.getBusiness_phone_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_loccode())); user.setBusinessPhoneNumber((addform.getBusiness_phone_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_number())); user.setBusinessPhoneExt((addform.getBusiness_phone_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_ext())); user.setBusinessPhoneComment(addform.getBusiness_phone_commment()); user.setBusinessFaxIntcode((addform.getBusiness_fax_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_intcode())); user.setBusinessFaxLoccode((addform.getBusiness_fax_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_loccode())); user.setBusinessFaxNumber((addform.getBusiness_fax_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_number())); user.setBusinessFaxExt((addform.getBusiness_fax_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_ext())); user.setBusinessFaxComment(addform.getBusiness_fax_commment()); user.setBusinessMobileIntcode((addform.getBusiness_mobile_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_intcode())); user.setBusinessMobileLoccode((addform.getBusiness_mobile_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_loccode())); user.setBusinessMobileNumber((addform.getBusiness_mobile_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_number())); user.setBusinessMobileExt((addform.getBusiness_mobile_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_ext())); user.setBusinessMobileComment(addform.getBusiness_mobile_commment()); user.setBusinessPagerIntcode((addform.getBusiness_pager_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_intcode())); user.setBusinessPagerLoccode((addform.getBusiness_pager_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_loccode())); user.setBusinessPagerNumber((addform.getBusiness_pager_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_number())); user.setBusinessPagerExt((addform.getBusiness_pager_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_ext())); user.setBusinessPagerComment(addform.getBusiness_pager_commment()); user.setBusinessUri(addform.getBusiness_uri()); user.setBusinessEmail(addform.getBusiness_email()); String hqlDelete = "delete org.nodevision.portal.hibernate.om.NvUserRoles where login = :login"; int deletedEntities = hbsession.createQuery(hqlDelete).setString("login", user.getLogin()).executeUpdate(); String[] selectedGroups = addform.getSelectedGroups(); Set newGroups = new HashSet(); for (int i = 0; i < selectedGroups.length; i++) { NvUserRolesId userroles = new NvUserRolesId(); userroles.setNvUsers(user); userroles.setNvRoles((NvRoles) hbsession.load(NvRoles.class, selectedGroups[i])); NvUserRoles newRole = new NvUserRoles(); newRole.setId(userroles); newGroups.add(newRole); } user.setSetOfNvUserRoles(newGroups); hbsession.update(user); hbsession.flush(); if (!hbsession.connection().getAutoCommit()) { tx.commit(); } } finally { HibernateUtil.closeSession(); } } Code Sample 2: public static String convertToSha1(final 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); }
00
Code Sample 1: private void startOpening(final URL url) { final WebAccessor wa = this; openerThread = new Thread() { public void run() { iStream = null; try { tryProxy = false; URLConnection connection = url.openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection htc = (HttpURLConnection) connection; contentLength = htc.getContentLength(); } InputStream i = connection.getInputStream(); iStream = new LoggedInputStream(i, wa); } catch (ConnectException x) { tryProxy = true; exception = x; } catch (Exception x) { exception = x; } finally { if (dialog != null) { Thread.yield(); dialog.setVisible(false); } } } }; openerThread.start(); } Code Sample 2: private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; }
00
Code Sample 1: private 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: 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); }
00
Code Sample 1: private long getLastModified(Set resourcePaths, Map jarPaths) throws Exception { long lastModified = 0; Iterator paths = resourcePaths.iterator(); while (paths.hasNext()) { String path = (String) paths.next(); URL url = context.getServletContext().getResource(path); if (url == null) { log.debug("Null url " + path); break; } long lastM = url.openConnection().getLastModified(); if (lastM > lastModified) lastModified = lastM; if (log.isDebugEnabled()) { log.debug("Last modified " + path + " " + lastM); } } if (jarPaths != null) { paths = jarPaths.values().iterator(); while (paths.hasNext()) { File jarFile = (File) paths.next(); long lastM = jarFile.lastModified(); if (lastM > lastModified) lastModified = lastM; if (log.isDebugEnabled()) { log.debug("Last modified " + jarFile.getAbsolutePath() + " " + lastM); } } } return lastModified; } Code Sample 2: public static InputStream download(String endereco, ProxyConfig proxy) { if (proxy != null) { System.getProperties().put("proxySet", "true"); System.getProperties().put("proxyPort", proxy.getPorta()); System.getProperties().put("proxyHost", proxy.getHost()); Authenticator.setDefault(new ProxyAuthenticator(proxy.getUsuario(), proxy.getSenha())); } try { URL url = new URL(endereco); ; URLConnection connection = url.openConnection(); InputStream bis = new BufferedInputStream(connection.getInputStream()); return bis; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
00
Code Sample 1: public void loadSourceCode() { int length = MAX_SOURCE_LENGTH; try { File file = new File(filename); length = (int) file.length(); } catch (SecurityException ex) { } char[] buff = new char[length]; InputStream is; InputStreamReader isr; CodeViewer cv = new CodeViewer(); URL url; try { url = getClass().getResource(filename); is = url.openStream(); isr = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isr); sourceCode = new String("<html><pre>"); String line = reader.readLine(); while (line != null) { sourceCode += cv.syntaxHighlight(line) + " \n "; line = reader.readLine(); } sourceCode += "</pre></html>"; } catch (Exception ex) { sourceCode = getString("SourceCode.error"); } } Code Sample 2: public static ArrayList<AnalyzeDefinition> read(ArrayList<String> supportedCommands, File analyzeCommands, String programAnalyzeCommands) throws ErrorMessage { if (analyzeCommands != null) { try { Reader fileReader = new FileReader(analyzeCommands); BufferedReader reader = new BufferedReader(fileReader); return readConfig(reader, analyzeCommands.getName(), null); } catch (FileNotFoundException e) { throw new ErrorMessage("File \"" + analyzeCommands + "\" not found"); } } else if (programAnalyzeCommands != null) { Reader stringReader = new StringReader(programAnalyzeCommands); BufferedReader reader = new BufferedReader(stringReader); return readConfig(reader, "program response to gogui-analyze_commands", null); } else { String resource = "net/sf/gogui/gui/analyze-commands"; URL url = ClassLoader.getSystemClassLoader().getResource(resource); if (url == null) return new ArrayList<AnalyzeDefinition>(); try { InputStream inputStream = url.openStream(); Reader inputStreamReader = new InputStreamReader(inputStream); BufferedReader reader = new BufferedReader(inputStreamReader); return readConfig(reader, "builtin default commands", supportedCommands); } catch (IOException e) { throw new ErrorMessage(e.getMessage()); } } }
00
Code Sample 1: private String fetchCompareContent() throws IOException { URL url = new URL(compareTo); StringWriter sw = new StringWriter(); IOUtils.copy(url.openStream(), sw); return sw.getBuffer().toString(); } Code Sample 2: private static String encode(String str, String method) { MessageDigest md = null; String dstr = null; try { md = MessageDigest.getInstance(method); md.update(str.getBytes()); dstr = new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return dstr; }
00
Code Sample 1: public String getDataAsString(String url) throws RuntimeException { try { String responseBody = ""; URLConnection urlc; if (!url.toUpperCase().startsWith("HTTP://") && !url.toUpperCase().startsWith("HTTPS://")) { urlc = tryOpenConnection(url); } else { urlc = new URL(url).openConnection(); } urlc.setUseCaches(false); urlc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlc.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-GB; rv:1.9.1.9) Gecko/20100414 Iceweasel/3.5.9 (like Firefox/3.5.9)"); urlc.setRequestProperty("Accept-Encoding", "gzip"); InputStreamReader re = new InputStreamReader(urlc.getInputStream()); BufferedReader rd = new BufferedReader(re); String line = ""; while ((line = rd.readLine()) != null) { responseBody += line; responseBody += "\n"; line = null; } rd.close(); re.close(); return responseBody; } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public void copyAffix(MailAffix affix, long mailId1, long mailId2) throws Exception { File file = new File(this.getResDir(mailId1) + affix.getAttachAlias()); if (file.exists()) { File file2 = new File(this.getResDir(mailId2) + affix.getAttachAlias()); if (!file2.exists()) { file2.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); in.close(); out.close(); } } else { log.debug(file.getAbsolutePath() + file.getName() + "�����ڣ������ļ�ʧ�ܣ���������"); } }
11
Code Sample 1: @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; } } } Code Sample 2: public static boolean copyFile(File sourceFile, File destinationFile) { boolean copySuccessfull = false; FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); long transferedBytes = destination.transferFrom(source, 0, source.size()); copySuccessfull = transferedBytes == source.size() ? true : false; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (source != null) { try { source.close(); } catch (IOException e) { e.printStackTrace(); } } if (destination != null) { try { destination.close(); } catch (IOException e) { e.printStackTrace(); } } } return copySuccessfull; }
11
Code Sample 1: public static void unzipAndRemove(final String file) { String destination = file.substring(0, file.length() - 3); InputStream is = null; OutputStream os = null; try { is = new GZIPInputStream(new FileInputStream(file)); os = new FileOutputStream(destination); byte[] buffer = new byte[8192]; for (int length; (length = is.read(buffer)) != -1; ) os.write(buffer, 0, length); } catch (IOException e) { System.err.println("Fehler: Kann nicht entpacken " + file); } finally { if (os != null) try { os.close(); } catch (IOException e) { } if (is != null) try { is.close(); } catch (IOException e) { } } deleteFile(file); } Code Sample 2: private long generateUnixInstallShell(File unixShellFile, String instTemplate, File instClassFile) throws IOException { FileOutputStream byteWriter = new FileOutputStream(unixShellFile); InputStream is = getClass().getResourceAsStream("/" + instTemplate); InputStreamReader isr = new InputStreamReader(is); LineNumberReader reader = new LineNumberReader(isr); String content = ""; String installClassStartStr = "000000000000"; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassStartStr.length()); int installClassStartPos = 0; long installClassOffset = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallShell")); String line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassStart"))) { content += line + "\n"; line = reader.readLine(); } content += "InstallClassStart=" + installClassStartStr + "\n"; installClassStartPos = content.length() - 1 - 1 - installClassStartStr.length(); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassSize"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassSize=" + instClassFile.length() + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassName"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassName=" + instClassName_ + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# Install class"))) { content += line + "\n"; line = reader.readLine(); } if (line != null) content += line + "\n"; byteWriter.write(content.substring(0, installClassStartPos + 1).getBytes()); byteWriter.write(nf.format(content.length()).getBytes()); byteWriter.write(content.substring(installClassStartPos + 1 + installClassStartStr.length()).getBytes()); installClassOffset = content.length(); content = null; FileInputStream classStream = new FileInputStream(instClassFile); byte[] buf = new byte[2048]; int read = classStream.read(buf); while (read > 0) { byteWriter.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); reader.close(); byteWriter.close(); return installClassOffset; }
11
Code Sample 1: private void makeDailyBackup() throws CacheOperationException, ConfigurationException { final int MAX_DAILY_BACKUPS = 5; File cacheFolder = getBackupFolder(); cacheLog.debug("Making a daily backup of current Beehive archive..."); try { File oldestDaily = new File(DAILY_BACKUP_PREFIX + "." + MAX_DAILY_BACKUPS); if (oldestDaily.exists()) { moveToWeeklyBackup(oldestDaily); } for (int index = MAX_DAILY_BACKUPS - 1; index > 0; index--) { File daily = new File(cacheFolder, DAILY_BACKUP_PREFIX + "." + index); File target = new File(cacheFolder, DAILY_BACKUP_PREFIX + "." + (index + 1)); if (!daily.exists()) { cacheLog.debug("Daily backup file ''{0}'' was not present. Skipping...", daily.getAbsolutePath()); continue; } if (!daily.renameTo(target)) { sortBackups(); throw new CacheOperationException("There was an error moving ''{0}'' to ''{1}''.", daily.getAbsolutePath(), target.getAbsolutePath()); } else { cacheLog.debug("Moved " + daily.getAbsolutePath() + " to " + target.getAbsolutePath()); } } } catch (SecurityException e) { throw new ConfigurationException("Security Manager has denied read/write access to daily backup files in ''{0}'' : {1}" + e, cacheFolder.getAbsolutePath(), e.getMessage()); } File beehiveArchive = getCachedArchive(); File tempBackupArchive = new File(cacheFolder, BEEHIVE_ARCHIVE_NAME + ".tmp"); BufferedInputStream archiveReader = null; BufferedOutputStream tempBackupWriter = null; try { archiveReader = new BufferedInputStream(new FileInputStream(beehiveArchive)); tempBackupWriter = new BufferedOutputStream(new FileOutputStream(tempBackupArchive)); int len, bytecount = 0; final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; while ((len = archiveReader.read(buffer, 0, BUFFER_SIZE)) != -1) { tempBackupWriter.write(buffer, 0, len); bytecount += len; } tempBackupWriter.flush(); long originalFileSize = beehiveArchive.length(); if (originalFileSize != bytecount) { throw new CacheOperationException("Original archive size was {0} bytes but only {1} were copied.", originalFileSize, bytecount); } cacheLog.debug("Finished copying ''{0}'' to ''{1}''.", beehiveArchive.getAbsolutePath(), tempBackupArchive.getAbsolutePath()); } catch (FileNotFoundException e) { throw new CacheOperationException("Files required for copying a backup of Beehive archive could not be found, opened " + "or created : {1}", e, e.getMessage()); } catch (IOException e) { throw new CacheOperationException("Error while making a copy of the Beehive archive : {0}", e, e.getMessage()); } finally { if (archiveReader != null) { try { archiveReader.close(); } catch (Throwable t) { cacheLog.warn("Failed to close stream to ''{0}'' : {1}", t, beehiveArchive.getAbsolutePath(), t.getMessage()); } } if (tempBackupWriter != null) { try { tempBackupWriter.close(); } catch (Throwable t) { cacheLog.warn("Failed to close stream to ''{0}'' : {1}", t, tempBackupArchive.getAbsolutePath(), t.getMessage()); } } } validateArchive(tempBackupArchive); File newestDaily = getNewestDailyBackupFile(); try { if (!tempBackupArchive.renameTo(newestDaily)) { throw new CacheOperationException("Error moving ''{0}'' to ''{1}''.", tempBackupArchive.getAbsolutePath(), newestDaily.getAbsolutePath()); } else { cacheLog.info("Backup complete. Saved in ''{0}''", newestDaily.getAbsolutePath()); } } catch (SecurityException e) { throw new ConfigurationException("Security Manager has denied write access to ''{0}'' : {1}", e, newestDaily.getAbsolutePath(), e.getMessage()); } } Code Sample 2: private void serveCGI(TinyCGI script) throws IOException, TinyWebThreadException { parseHTTPHeaders(); OutputStream cgiOut = null; File tempFile = null; try { if (script == null) sendError(500, "Internal Error", "Couldn't load script."); if (script instanceof TinyCGIHighVolume) { tempFile = File.createTempFile("cgi", null); cgiOut = new FileOutputStream(tempFile); } else { cgiOut = new ByteArrayOutputStream(); } script.service(inputStream, cgiOut, env); } catch (Exception cgie) { this.exceptionEncountered = cgie; if (tempFile != null) tempFile.delete(); if (clientSocket == null) { return; } else if (cgie instanceof TinyCGIException) { TinyCGIException tce = (TinyCGIException) cgie; sendError(tce.getStatus(), tce.getTitle(), tce.getText(), tce.getOtherHeaders()); } else { StringWriter w = new StringWriter(); cgie.printStackTrace(new PrintWriter(w)); sendError(500, "CGI Error", "Error running script: " + "<PRE>" + w.toString() + "</PRE>"); } } finally { if (script != null) doneWithScript(script); } InputStream cgiResults = null; long totalSize = 0; if (tempFile == null) { byte[] results = ((ByteArrayOutputStream) cgiOut).toByteArray(); totalSize = results.length; cgiResults = new ByteArrayInputStream(results); } else { cgiOut.close(); totalSize = tempFile.length(); cgiResults = new FileInputStream(tempFile); } String contentType = null, statusString = "OK", line, header; StringBuffer otherHeaders = new StringBuffer(); StringBuffer text = new StringBuffer(); int status = 200; int headerLength = 0; while (true) { line = readLine(cgiResults, true); headerLength += line.length(); if (line.charAt(0) == '\r' || line.charAt(0) == '\n') break; header = parseHeader(line, text); if (header.toUpperCase().equals("STATUS")) { statusString = text.toString(); status = Integer.parseInt(statusString.substring(0, 3)); statusString = statusString.substring(4); } else if (header.toUpperCase().equals("CONTENT-TYPE")) contentType = text.toString(); else { if (header.toUpperCase().equals("LOCATION")) status = 302; otherHeaders.append(header).append(": ").append(text.toString()).append(CRLF); } } sendHeaders(status, statusString, contentType, totalSize - headerLength, -1, otherHeaders.toString()); byte[] buf = new byte[2048]; int bytesRead; while ((bytesRead = cgiResults.read(buf)) != -1) outputStream.write(buf, 0, bytesRead); outputStream.flush(); try { cgiResults.close(); if (tempFile != null) tempFile.delete(); } catch (IOException ioe) { } }
11
Code Sample 1: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { Logger.error(FileUtil.class, ioe.getMessage(), ioe); } } 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: public static void TestDBStore() throws PDException, Exception { StoreDDBB StDB = new StoreDDBB("jdbc:derby://localhost:1527/Prodoc", "Prodoc", "Prodoc", "org.apache.derby.jdbc.ClientDriver;STBLOB"); System.out.println("Driver[" + StDB.getDriver() + "] Tabla [" + StDB.getTable() + "]"); StDB.Connect(); FileInputStream in = new FileInputStream("/tmp/readme.htm"); StDB.Insert("12345678-1", "1.0", in); int TAMBUFF = 1024 * 64; byte Buffer[] = new byte[TAMBUFF]; InputStream Bytes; Bytes = StDB.Retrieve("12345678-1", "1.0"); FileOutputStream fo = new FileOutputStream("/tmp/12345679.htm"); int readed = Bytes.read(Buffer); while (readed != -1) { fo.write(Buffer, 0, readed); readed = Bytes.read(Buffer); } Bytes.close(); fo.close(); StDB.Delete("12345678-1", "1.0"); StDB.Disconnect(); } Code Sample 2: public static boolean isODF(URL url) throws IOException { InputStream resStream = ODFUtil.findDataInputStream(url.openStream(), ODFUtil.MIMETYPE_FILE); if (null == resStream) { LOG.debug("mimetype stream not found in ODF package"); return false; } String mimetypeContent = IOUtils.toString(resStream); return mimetypeContent.startsWith(ODFUtil.MIMETYPE_START); }
00
Code Sample 1: private void innerJob(String inFrom, String inTo, String line, Map<String, Match> result) throws UnsupportedEncodingException, IOException { String subline = line.substring(line.indexOf(inTo) + inTo.length()); String tempStr = subline.substring(subline.indexOf(inFrom) + inFrom.length(), subline.indexOf(inTo)); String inURL = "http://goal.2010worldcup.163.com/data/match/general/" + tempStr.substring(tempStr.indexOf("/") + 1) + ".xml"; URL url = new URL(inURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String inLine = null; String scoreFrom = "score=\""; String homeTo = "\" side=\"Home"; String awayTo = "\" side=\"Away"; String goalInclud = "Stat"; String playerFrom = "playerId=\""; String playerTo = "\" position="; String timeFrom = "time=\""; String timeTo = "\" period"; String teamFinish = "</Team>"; boolean homeStart = false; boolean awayStart = false; while ((inLine = reader.readLine()) != null) { if (inLine.indexOf(teamFinish) != -1) { homeStart = false; awayStart = false; } if (inLine.indexOf(homeTo) != -1) { result.get(key).setHomeScore(inLine.substring(inLine.indexOf(scoreFrom) + scoreFrom.length(), inLine.indexOf(homeTo))); homeStart = true; } if (homeStart && inLine.indexOf(goalInclud) != -1) { MatchEvent me = new MatchEvent(); me.setPlayerName(getPlayerName(inLine.substring(inLine.indexOf(playerFrom) + playerFrom.length(), inLine.indexOf(playerTo)))); me.setTime(inLine.substring(inLine.indexOf(timeFrom) + timeFrom.length(), inLine.indexOf(timeTo))); result.get(key).getHomeEvents().add(me); } if (inLine.indexOf(awayTo) != -1) { result.get(key).setAwayScore(inLine.substring(inLine.indexOf(scoreFrom) + scoreFrom.length(), inLine.indexOf(awayTo))); awayStart = true; } if (awayStart && inLine.indexOf(goalInclud) != -1) { MatchEvent me = new MatchEvent(); me.setPlayerName(getPlayerName(inLine.substring(inLine.indexOf(playerFrom) + playerFrom.length(), inLine.indexOf(playerTo)))); me.setTime(inLine.substring(inLine.indexOf(timeFrom) + timeFrom.length(), inLine.indexOf(timeTo))); result.get(key).getAwayEvents().add(me); } } reader.close(); } Code Sample 2: public final InputStream getStreamFromUrl(final URL url) { try { if (listener != null) { listener.openedStream(url); } return url.openStream(); } catch (IOException e) { listener.exceptionThrown(e); return null; } }
11
Code Sample 1: public OutputStream getAsOutputStream() throws IOException { OutputStream out; if (contentStream != null) { File tmp = File.createTempFile(getId(), null); out = new FileOutputStream(tmp); IOUtils.copy(contentStream, out); } else { out = new ByteArrayOutputStream(); out.write(getContent()); } return out; } Code Sample 2: static JSONObject executeMethod(HttpClient httpClient, HttpMethod method, int timeout) throws HttpRequestFailureException, HttpException, IOException, HttpRequestTimeoutException { try { method.getParams().setSoTimeout(timeout * 1000); int status = -1; JSONObject result = null; for (int i = 0; i < RETRY; i++) { System.out.println("Execute method[" + method.getURI() + "](try " + (i + 1) + ")"); status = httpClient.executeMethod(method); if (status == HttpStatus.SC_OK) { InputStream inputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(inputStream, baos); String response = new String(baos.toByteArray(), "UTF-8"); System.out.println(response); result = JSONObject.fromString(response); if (result.has("status")) { String lingrStatus = result.getString("status"); if ("ok".equals(lingrStatus)) { break; } else { try { Thread.sleep(1000); } catch (InterruptedException e) { } } } } else { throw new HttpRequestFailureException(status); } } return result; } catch (SocketTimeoutException e) { throw new HttpRequestTimeoutException(e); } finally { method.releaseConnection(); } }
00
Code Sample 1: public String getLongToken(String md5Str) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(md5Str.getBytes(JspRunConfig.charset)); } catch (Exception e) { e.printStackTrace(); } StringBuffer token = toHex(md5.digest()); return token.toString(); } Code Sample 2: private static void addFromResource(String resource, OutputStream out) { URL url = OpenOfficeDocumentCreator.class.getResource(resource); try { InputStream in = url.openStream(); byte[] buffer = new byte[256]; synchronized (in) { synchronized (out) { while (true) { int bytesRead = in.read(buffer); if (bytesRead == -1) break; out.write(buffer, 0, bytesRead); } } } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: @Before public void BeforeTheTest() throws Exception { URL url = ProfileParserTest.class.getClassLoader().getResource("ca/uhn/hl7v2/conf/parser/tests/example_ack.xml"); URLConnection conn = url.openConnection(); InputStream instream = conn.getInputStream(); if (instream == null) throw new Exception("can't find the xml file"); BufferedReader in = new BufferedReader(new InputStreamReader(instream)); int tmp = 0; StringBuffer buf = new StringBuffer(); while ((tmp = in.read()) != -1) { buf.append((char) tmp); } profileString = buf.toString(); } Code Sample 2: private static File createTempWebXml(Class portletClass, File portletDir, String appName, String portletName) throws IOException, FileNotFoundException { File pathToWebInf = new File(portletDir, "WEB-INF"); File tempWebXml = File.createTempFile("web", ".xml", pathToWebInf); tempWebXml.deleteOnExit(); OutputStream webOutputStream = new FileOutputStream(tempWebXml); PortletUnitWebXmlStream streamSource = WEB_XML_STREAM_FACTORY; IOUtils.copy(streamSource.createStream(portletClass, appName, portletName), webOutputStream); webOutputStream.close(); return tempWebXml; }
11
Code Sample 1: public void zipDocsetFiles(SaxHandler theXmlHandler, int theEventId, Attributes theAtts) throws BpsProcessException { ZipOutputStream myZipOut = null; BufferedInputStream myDocumentInputStream = null; String myFinalFile = null; String myTargetPath = null; String myTargetFileName = null; String myInputFileName = null; byte[] myBytesBuffer = null; int myLength = 0; try { myZipOut = new ZipOutputStream(new FileOutputStream(myFinalFile)); myZipOut.putNextEntry(new ZipEntry(myTargetPath + myTargetFileName)); myDocumentInputStream = new BufferedInputStream(new FileInputStream(myInputFileName)); while ((myLength = myDocumentInputStream.read(myBytesBuffer, 0, 4096)) != -1) myZipOut.write(myBytesBuffer, 0, myLength); myZipOut.closeEntry(); myZipOut.close(); } catch (FileNotFoundException e) { throw (new BpsProcessException(BpsProcessException.ERR_OPEN_FILE, "FileNotFoundException while building zip dest file")); } catch (IOException e) { throw (new BpsProcessException(BpsProcessException.ERR_OPEN_FILE, "IOException while building zip dest file")); } } Code Sample 2: public static boolean copyFile(File source, File dest) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(source).getChannel(); dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (IOException e) { return false; } finally { try { if (srcChannel != null) { srcChannel.close(); } } catch (IOException e) { } try { if (dstChannel != null) { dstChannel.close(); } } catch (IOException e) { } } return true; }
00
Code Sample 1: public String getString(String arg) throws Exception { URL url = new URL(arg); URLConnection con = url.openConnection(); con.setUseCaches(false); con.connect(); InputStreamReader src = new InputStreamReader(con.getInputStream(), "ISO-8859-1"); StringBuffer stb = new StringBuffer(); char[] buf = new char[1024]; int l; while ((l = src.read(buf, 0, 1024)) >= 0) { stb.append(buf, 0, l); } String res = stb.toString(); if (res.startsWith("<pannenleiter-exception")) { builder.start(new TreeNode((TreeWidget) null, false), false); InputSource xmlInput = new InputSource(new StringReader(res)); parser.setDocumentHandler(builder); parser.parse(xmlInput); } return res; } Code Sample 2: @Test @Ignore public void testToJson() throws IOException { JsonSerializer js = new StreamingJsonSerializer(new ObjectMapper()); BulkOperation op = js.createBulkOperation(createTestData(10000), false); IOUtils.copy(op.getData(), System.out); }
00
Code Sample 1: public static final String computeHash(String stringToCompile) { String retVal = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(stringToCompile.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString(0xFF & result[i])); } retVal = hexString.toString(); if (log.isDebugEnabled()) log.debug("MD5 hash for \"" + stringToCompile + "\" is: " + retVal); } catch (Exception exe) { log.error(exe.getMessage(), exe); } return retVal; } Code Sample 2: private void trainDepParser(byte flag, JarArchiveOutputStream zout) throws Exception { AbstractDepParser parser = null; OneVsAllDecoder decoder = null; if (flag == ShiftPopParser.FLAG_TRAIN_LEXICON) { System.out.println("\n* Save lexica"); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, s_featureXml); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, s_featureXml); } else if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE) { System.out.println("\n* Print training instances"); System.out.println("- loading lexica"); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, t_xml, ENTRY_LEXICA); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, t_xml, ENTRY_LEXICA); } else if (flag == ShiftPopParser.FLAG_TRAIN_BOOST) { System.out.println("\n* Train conditional"); decoder = new OneVsAllDecoder(m_model); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, t_xml, t_map, decoder); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, t_xml, t_map, decoder); } AbstractReader<DepNode, DepTree> reader = null; DepTree tree; int n; if (s_format.equals(AbstractReader.FORMAT_DEP)) reader = new DepReader(s_trainFile, true); else if (s_format.equals(AbstractReader.FORMAT_CONLLX)) reader = new CoNLLXReader(s_trainFile, true); parser.setLanguage(s_language); reader.setLanguage(s_language); for (n = 0; (tree = reader.nextTree()) != null; n++) { parser.parse(tree); if (n % 1000 == 0) System.out.printf("\r- parsing: %dK", n / 1000); } System.out.println("\r- parsing: " + n); if (flag == ShiftPopParser.FLAG_TRAIN_LEXICON) { System.out.println("- saving"); parser.saveTags(ENTRY_LEXICA); t_xml = parser.getDepFtrXml(); } else if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE || flag == ShiftPopParser.FLAG_TRAIN_BOOST) { a_yx = parser.a_trans; zout.putArchiveEntry(new JarArchiveEntry(ENTRY_PARSER)); PrintStream fout = new PrintStream(zout); fout.print(s_depParser); fout.flush(); zout.closeArchiveEntry(); zout.putArchiveEntry(new JarArchiveEntry(ENTRY_FEATURE)); IOUtils.copy(new FileInputStream(s_featureXml), zout); zout.closeArchiveEntry(); zout.putArchiveEntry(new JarArchiveEntry(ENTRY_LEXICA)); IOUtils.copy(new FileInputStream(ENTRY_LEXICA), zout); zout.closeArchiveEntry(); if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE) t_map = parser.getDepFtrMap(); } }
00
Code Sample 1: public RawCandidate getRawCandidate(long candId) throws BookKeeprCommunicationException { try { synchronized (httpClient) { HttpGet req = new HttpGet(remoteHost.getUrl() + "/cand/" + Long.toHexString(candId)); req.setHeader("Accept-Encoding", "gzip"); HttpResponse resp = httpClient.execute(req); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { try { InputStream in = resp.getEntity().getContent(); Header hdr = resp.getFirstHeader("Content-Encoding"); String enc = ""; if (hdr != null) { enc = resp.getFirstHeader("Content-Encoding").getValue(); } if (enc.equals("gzip")) { in = new GZIPInputStream(in); } XMLAble xmlable = XMLReader.read(in); in.close(); if (xmlable instanceof RawCandidate) { RawCandidate p = (RawCandidate) xmlable; return p; } else { throw new BookKeeprCommunicationException("BookKeepr returned the wrong thing for candId"); } } catch (SAXException ex) { Logger.getLogger(BookKeeprConnection.class.getName()).log(Level.WARNING, "Got a malformed message from the bookkeepr", ex); throw new BookKeeprCommunicationException(ex); } } else { resp.getEntity().consumeContent(); throw new BookKeeprCommunicationException("Got a " + resp.getStatusLine().getStatusCode() + " from the BookKeepr"); } } } catch (HttpException ex) { throw new BookKeeprCommunicationException(ex); } catch (IOException ex) { throw new BookKeeprCommunicationException(ex); } catch (URISyntaxException ex) { throw new BookKeeprCommunicationException(ex); } } Code Sample 2: private boolean checkTimestamp(File timestamp, URL url) { try { if (timestamp.exists()) { FileReader reader = null; Date dateLocal = null; try { reader = new FileReader(timestamp); StringWriter tmp = new StringWriter(); IOUtils.copy(reader, tmp); dateLocal = this.FORMAT.parse(tmp.toString()); } catch (ParseException e) { timestamp.delete(); } catch (IOException e) { } finally { IOUtils.closeQuietly(reader); } if (dateLocal != null) { try { URLConnection conn = url.openConnection(); Date date = this.FORMAT.parse(this.FORMAT.format(new Date(conn.getLastModified()))); return (date.compareTo(dateLocal) == 0); } catch (IOException e) { } } } } catch (Throwable t) { } return false; }
00
Code Sample 1: private String readData(URL url) { try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer responseBuffer = new StringBuffer(); String line; while ((line = in.readLine()) != null) { responseBuffer.append(line); } in.close(); return new String(responseBuffer); } catch (Exception e) { System.out.println(e); } return null; } Code Sample 2: private void saveURL(URL url, String filename) throws IOException { URLConnection connection = url.openConnection(); connection.connect(); InputStreamReader ReadIn = new InputStreamReader(connection.getInputStream()); BufferedReader BufData = new BufferedReader(ReadIn); FileWriter FWriter = new FileWriter(filename); BufferedWriter BWriter = new BufferedWriter(FWriter); String urlData = null; while ((urlData = BufData.readLine()) != null) { BWriter.write(urlData); BWriter.newLine(); } BWriter.close(); }
00
Code Sample 1: protected File compress(File orig, IWrapCompression wrapper) throws IOException { File compressed = File.createTempFile("test.", ".gz"); FileOutputStream fos = new FileOutputStream(compressed); OutputStream wos = wrapper.wrap(fos); FileInputStream fis = new FileInputStream(orig); IOUtils.copy(fis, wos); IOUtils.closeQuietly(fis); IOUtils.closeQuietly(wos); return compressed; } Code Sample 2: public int read(String name) { status = STATUS_OK; try { name = name.trim().toLowerCase(); if ((name.indexOf("file:") >= 0) || (name.indexOf(":/") > 0)) { URL url = new URL(name); in = new BufferedInputStream(url.openStream()); } else { in = new BufferedInputStream(new FileInputStream(name)); } status = read(in); } catch (IOException e) { status = STATUS_OPEN_ERROR; } return status; }
00
Code Sample 1: public static void copyFile(File oldPathFile, File newPathFile) throws IOException { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(oldPathFile)); out = new BufferedOutputStream(new FileOutputStream(newPathFile)); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; while (in.read(buffer) > 0) out.write(buffer); } finally { if (null != in) in.close(); if (null != out) out.close(); } } Code Sample 2: public byte[] getHash(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(salt.getBytes("UTF-8")); return digest.digest(plaintext.getBytes("UTF-8")); }
11
Code Sample 1: public static File copy(String inFileName, String outFileName) throws IOException { File inputFile = new File(inFileName); File outputFile = new File(outFileName); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return outputFile; } Code Sample 2: private void copyFile(String from, String to) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File inScriptFile = null; try { inScriptFile = new File(monitorCallShellScriptUrl.toURI()); } catch (URISyntaxException e) { throw e; } File outScriptFile = new File(to); FileChannel inChannel = new FileInputStream(inScriptFile).getChannel(); FileChannel outChannel = new FileOutputStream(outScriptFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } }
00
Code Sample 1: private Collection<URL> doSearch(final URL url) throws IOException { final Collection<URL> result = new ArrayList<URL>(); final InputStream is = url.openStream(); final ReadHTML parse = new ReadHTML(is); final StringBuilder buffer = new StringBuilder(); boolean capture = false; int ch; while ((ch = parse.read()) != -1) { if (ch == 0) { final Tag tag = parse.getTag(); if (tag.getName().equalsIgnoreCase("url")) { buffer.setLength(0); capture = true; } else if (tag.getName().equalsIgnoreCase("/url")) { result.add(new URL(buffer.toString())); buffer.setLength(0); capture = false; } } else { if (capture) { buffer.append((char) ch); } } } return result; } Code Sample 2: protected void execute(Context context) throws java.lang.Exception { Connection c = null; Statement s = null; Integer check = context.getValueAsInteger("Total"); System.err.println("In BuyWidget.execute()"); try { c = context.getConnection(); c.setAutoCommit(false); s = c.createStatement(); int total = computeCheckoutTotal(context, s); if (check == null) { throw new Exception("Shouldn't: No total?"); } if (check.intValue() != total) { throw new Exception("Shouldn't: Basket changed? " + "total was " + total + "; checksum was " + check); } StringBuffer q = new StringBuffer("select BIDSTATE.Bid, BIDSTATE.Amount, " + "BIDSTATE.QShipping, BIDSTATE.QInsure " + "from BID, BIDSTATE " + "where BIDSTATE.Bid = BID.Bid " + "and ( BIDSTATE.BidStatus = 0 " + "or BIDSTATE.BidStatus = 15) " + "and BID.Customer = "); q.append(context.get("customer")); q.append(" and bidstate.bidstate = " + "( select max( bidstate.bidstate) " + "from bidstate " + "where bid = bid.bid) "); System.err.println(q.toString()); Contexts rows = new RSContexts(s.executeQuery(q.toString())); Enumeration e = rows.elements(); while (e.hasMoreElements()) { Context row = (Context) e.nextElement(); row.merge((Map) context); row.put("Username", context.get(ConnectionPool.DBUSERMAGICTOKEN)); row.put("BidStatus", BidStatus.OFFER); s.executeUpdate(bidStateInsert(row)); s.execute(bidPrivateInsert(context, row)); } c.commit(); } catch (Exception any) { c.rollback(); throw new DataStoreException("Your card will not be debited: " + any.getMessage()); } finally { try { if (s != null) { s.close(); } if (c != null) { context.releaseConnection(c); } } catch (SQLException sex) { } catch (DataStoreException dse) { } } context.put(REDIRECTMAGICTOKEN, "account"); }
11
Code Sample 1: @Test public void testCopy_readerToWriter_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (Writer) null); fail(); } catch (NullPointerException ex) { } } Code Sample 2: public static void copyFile(File source, File destination) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(destination).getChannel(); long size = in.size(); MappedByteBuffer buffer = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buffer); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
00
Code Sample 1: private <T> Collection<T> loadProviders(final Class<T> providerClass) throws ModelException { try { final String providerNamePrefix = providerClass.getName() + "."; final Map<String, T> providers = new TreeMap<String, T>(new Comparator<String>() { public int compare(final String key1, final String key2) { return key1.compareTo(key2); } }); final File platformProviders = new File(this.getPlatformProviderLocation()); if (platformProviders.exists()) { if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("processing", platformProviders.getAbsolutePath()), null); } InputStream in = null; boolean suppressExceptionOnClose = true; final java.util.Properties p = new java.util.Properties(); try { in = new FileInputStream(platformProviders); p.load(in); suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (suppressExceptionOnClose) { this.log(Level.SEVERE, getMessage(e), e); } else { throw e; } } } for (Map.Entry<Object, Object> e : p.entrySet()) { if (e.getKey().toString().startsWith(providerNamePrefix)) { final String configuration = e.getValue().toString(); if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("providerInfo", platformProviders.getAbsolutePath(), providerClass.getName(), configuration), null); } providers.put(e.getKey().toString(), this.createProviderObject(providerClass, configuration, platformProviders.toURI().toURL())); } } } final Enumeration<URL> classpathProviders = this.findResources(this.getProviderLocation() + '/' + providerClass.getName()); int count = 0; final long t0 = System.currentTimeMillis(); while (classpathProviders.hasMoreElements()) { count++; final URL url = classpathProviders.nextElement(); if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("processing", url.toExternalForm()), null); } BufferedReader reader = null; boolean suppressExceptionOnClose = true; try { reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { if (line.contains("#")) { continue; } if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("providerInfo", url.toExternalForm(), providerClass.getName(), line), null); } providers.put(providerNamePrefix + providers.size(), this.createProviderObject(providerClass, line, url)); } suppressExceptionOnClose = false; } finally { try { if (reader != null) { reader.close(); } } catch (final IOException e) { if (suppressExceptionOnClose) { this.log(Level.SEVERE, getMessage(e), e); } else { throw new ModelException(getMessage(e), e); } } } } if (this.isLoggable(Level.FINE)) { this.log(Level.FINE, getMessage("contextReport", count, this.getProviderLocation() + '/' + providerClass.getName(), Long.valueOf(System.currentTimeMillis() - t0)), null); } return providers.values(); } catch (final IOException e) { throw new ModelException(getMessage(e), e); } } Code Sample 2: public static byte[] decrypt(String passphrase, byte[] data) throws Exception { byte[] dataTemp; try { Security.addProvider(new com.sun.crypto.provider.SunJCE()); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes()); DESKeySpec key = new DESKeySpec(md.digest()); SecretKeySpec DESKey = new SecretKeySpec(key.getKey(), "DES"); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, DESKey); dataTemp = cipher.doFinal(data); } catch (Exception e) { throw e; } return dataTemp; }
00
Code Sample 1: public static void readDefault() { ClassLoader l = Skeleton.class.getClassLoader(); URL url; if (l != null) { url = l.getResource(DEFAULT_LOC); } else { url = ClassLoader.getSystemResource(DEFAULT_LOC); } if (url == null) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } try { InputStreamReader reader = new InputStreamReader(url.openStream()); readSkel(new BufferedReader(reader)); } catch (IOException e) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } } Code Sample 2: private Image2D resolvePNG(URI uri) { Image2D image2D = null; if (uri.getScheme() != null) { try { URL url = new URL(uri.toString()); InputStream is = url.openStream(); BufferedImage image = PNGDecoder.decode(is); int imageType = Image2D.RGB; if (image.getType() == BufferedImage.TYPE_INT_RGB) imageType = Image2D.RGB; else if (image.getType() == BufferedImage.TYPE_INT_ARGB) imageType = Image2D.RGBA; image2D = new Image2D(imageType, image); } catch (IOException ex) { } } else { String path = uri.getPath(); File file = new File(path); if (file.getAbsoluteFile().exists()) { try { FileInputStream is = new FileInputStream(file); BufferedImage image = PNGDecoder.decode(is); int imageType = Image2D.RGB; if (image.getType() == BufferedImage.TYPE_INT_RGB) imageType = Image2D.RGB; else if (image.getType() == BufferedImage.TYPE_INT_ARGB) imageType = Image2D.RGBA; image2D = new Image2D(imageType, image); } catch (FileNotFoundException ex) { } catch (IOException ex) { } } } return image2D; }
11
Code Sample 1: private void copy(File source, File dest) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { close(in); close(out); } } Code Sample 2: public BufferedImage processUsingTemp(InputStream input, DjatokaDecodeParam params) throws DjatokaException { File in; try { in = File.createTempFile("tmp", ".jp2"); FileOutputStream fos = new FileOutputStream(in); in.deleteOnExit(); IOUtils.copyStream(input, fos); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } BufferedImage bi = process(in.getAbsolutePath(), params); if (in != null) in.delete(); return bi; }
00
Code Sample 1: public void copy(final File source, final File dest) throws IOException { final FileInputStream in = new FileInputStream(source); try { final FileOutputStream out = new FileOutputStream(dest); try { final FileChannel inChannel = in.getChannel(); final FileChannel outChannel = out.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { out.close(); } } finally { in.close(); } } Code Sample 2: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
00
Code Sample 1: public synchronized void write() throws IOException { ZipOutputStream jar = new ZipOutputStream(new FileOutputStream(jarPath)); int index = className.lastIndexOf('.'); String packageName = className.substring(0, index); String clazz = className.substring(index + 1); String directory = packageName.replace('.', '/'); ZipEntry dummyClass = new ZipEntry(directory + "/" + clazz + ".class"); jar.putNextEntry(dummyClass); ClassGen classgen = new ClassGen(getClassName(), "java.lang.Object", "<generated>", Constants.ACC_PUBLIC | Constants.ACC_SUPER, null); byte[] bytes = classgen.getJavaClass().getBytes(); jar.write(bytes); jar.closeEntry(); ZipEntry synthFile = new ZipEntry(directory + "/synth.xml"); jar.putNextEntry(synthFile); Comment comment = new Comment("Generated by SynthBuilder from L2FProd.com"); Element root = new Element("synth"); root.addAttribute(new Attribute("version", "1")); root.appendChild(comment); Element defaultStyle = new Element("style"); defaultStyle.addAttribute(new Attribute("id", "default")); Element defaultFont = new Element("font"); defaultFont.addAttribute(new Attribute("name", "SansSerif")); defaultFont.addAttribute(new Attribute("size", "12")); defaultStyle.appendChild(defaultFont); Element defaultState = new Element("state"); defaultStyle.appendChild(defaultState); root.appendChild(defaultStyle); Element bind = new Element("bind"); bind.addAttribute(new Attribute("style", "default")); bind.addAttribute(new Attribute("type", "region")); bind.addAttribute(new Attribute("key", ".*")); root.appendChild(bind); doc = new Document(root); imagesToCopy = new HashMap(); ComponentStyle[] styles = config.getStyles(); for (ComponentStyle element : styles) { write(element); } Serializer writer = new Serializer(jar); writer.setIndent(2); writer.write(doc); writer.flush(); jar.closeEntry(); for (Iterator iter = imagesToCopy.keySet().iterator(); iter.hasNext(); ) { String element = (String) iter.next(); File pathToImage = (File) imagesToCopy.get(element); ZipEntry image = new ZipEntry(directory + "/" + element); jar.putNextEntry(image); FileInputStream input = new FileInputStream(pathToImage); int read = -1; while ((read = input.read()) != -1) { jar.write(read); } input.close(); jar.flush(); jar.closeEntry(); } jar.flush(); jar.close(); } Code Sample 2: @Override public void run() { HttpGet httpGet = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); DataModel model = DataModel.getInstance(); for (City city : citiesToBeUpdated) { String preferredUnitType = PreferenceManager.getDefaultSharedPreferences(context).getString(context.getString(R.string.settings_units_key), context.getString(R.string.settings_units_default_value)); String codePrefix = city.getCountryName().startsWith("United States") ? GET_PARAM_ZIP_PREFIX : GET_PARAM_CITY_CODE_PREFIX; String requestUri = new String(GET_URL + "?" + GET_PARAM_ACODE_PREFIX + "=" + GET_PARAM_ACODE + "&" + codePrefix + "=" + city.getId() + "&" + GET_PARAM_UNIT_PREFIX + "=" + preferredUnitType); httpGet = new HttpGet(requestUri); HttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { processXML(response.getEntity().getContent()); for (ForecastedDay day : forecast) { int pos = day.getImageURL().lastIndexOf('/'); if (pos < 0 || pos + 1 == day.getImageURL().length()) throw new Exception("Invalid image URL"); final String imageFilename = day.getImageURL().substring(pos + 1); File downloadDir = context.getDir(ForecastedDay.DOWNLOAD_DIR, Context.MODE_PRIVATE); File[] imagesFilteredByName = downloadDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { if (filename.equals(imageFilename)) return true; else return false; } }); if (imagesFilteredByName.length == 0) { httpGet = new HttpGet(day.getImageURL()); response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { BufferedOutputStream bus = null; try { bus = new BufferedOutputStream(new FileOutputStream(downloadDir.getAbsolutePath() + "/" + imageFilename)); response.getEntity().writeTo(bus); } finally { bus.close(); } } } } city.setDays(forecast); city.setLastUpdated(Calendar.getInstance().getTime()); model.saveCity(city); } } } catch (Exception e) { httpGet.abort(); e.printStackTrace(); } finally { handler.sendEmptyMessage(1); } }
00
Code Sample 1: public static String createStringFromHtml(MyUrl url) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.getUrl().openStream(), "UTF-8")); String line; String xmlAsString = ""; while ((line = reader.readLine()) != null) { xmlAsString += line; } reader.close(); return xmlAsString; } catch (Exception e) { return null; } } Code Sample 2: public static void copyFile(File inputFile, File outputFile) throws IOException { BufferedInputStream fr = new BufferedInputStream(new FileInputStream(inputFile)); BufferedOutputStream fw = new BufferedOutputStream(new FileOutputStream(outputFile)); byte[] buf = new byte[8192]; int n; while ((n = fr.read(buf)) >= 0) fw.write(buf, 0, n); fr.close(); fw.close(); }
11
Code Sample 1: private void prepareQueryResultData(ZipEntryRef zer, String nodeDir, String reportDir, Set<ZipEntryRef> statusZers) throws Exception { String jobDir = nodeDir + File.separator + "job_" + zer.getUri(); if (!WorkDirectory.isWorkingDirectoryValid(jobDir)) { throw new Exception("Cannot acces to " + jobDir); } File f = new File(jobDir + File.separator + "result.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to result file " + f.getAbsolutePath()); } String fcopyName = reportDir + File.separator + zer.getName() + ".xml"; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); zer.setUri(fcopyName); f = new File(jobDir + File.separator + "status.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to status file " + f.getAbsolutePath()); } fcopyName = reportDir + File.separator + zer.getName() + "_status.xml"; bis = new BufferedInputStream(new FileInputStream(f)); bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); statusZers.add(new ZipEntryRef(ZipEntryRef.SINGLE_FILE, zer.getName(), fcopyName, ZipEntryRef.WITH_REL)); } 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(); }
00
Code Sample 1: @Test public void testCustomerResource() throws Exception { DefaultHttpClient client = new DefaultHttpClient(); System.out.println("**** CustomerResource No Query params ***"); HttpGet get = new HttpGet("http://localhost:9095/customers"); HttpResponse response = client.execute(get); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } System.out.println("**** CustomerResource With Query params ***"); get = new HttpGet("http://localhost:9095/customers?start=1&size=3"); response = client.execute(get); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } System.out.println("**** CustomerResource With UriInfo and Query params ***"); get = new HttpGet("http://localhost:9095/customers/uriinfo?start=2&size=2"); response = client.execute(get); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } } Code Sample 2: private void extractSpecifications(String id, File specification) { Object resource = getClass().getResource(id + ".xml"); if (resource instanceof URL) { URL url = (URL) resource; try { InputStream istream = url.openStream(); try { OutputStream ostream = new FileOutputStream(specification); try { byte[] buffer = new byte[1024]; int length; while ((length = istream.read(buffer)) > 0) { ostream.write(buffer, 0, length); } } finally { ostream.close(); } } finally { istream.close(); } } catch (IOException ex) { throw new RuntimeException("Failed to open " + url, ex); } } }
00
Code Sample 1: private void createProject(IProgressMonitor monitor, boolean launchNewTestWizard) { try { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = root.getProject(namePage.getProjectName()); IProjectDescription description = ResourcesPlugin.getWorkspace().newProjectDescription(project.getName()); if (!Platform.getLocation().equals(namePage.getLocationPath())) description.setLocation(namePage.getLocationPath()); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); ICommand buildCommand = description.newCommand(); buildCommand.setBuilderName(JavaCore.BUILDER_ID); description.setBuildSpec(new ICommand[] { buildCommand }); project.create(description, monitor); project.open(monitor); IJavaProject javaProject = JavaCore.create(project); IFolder testFolder = project.getFolder("tests"); testFolder.create(false, true, monitor); IFolder srcFolder = project.getFolder("src"); srcFolder.create(false, true, monitor); IFolder binFolder = project.getFolder("bin"); binFolder.create(false, true, monitor); IFolder libFolder = project.getFolder("lib"); libFolder.create(false, true, monitor); try { FileUtils.copyFile(new Path(Platform.asLocalURL(CubicTestPlugin.getDefault().find(new Path("lib/CubicTestElementAPI.jar"))).getPath()).toFile(), libFolder.getFile("CubicTestElementAPI.jar").getLocation().toFile()); FileUtils.copyFile(new Path(Platform.asLocalURL(CubicTestPlugin.getDefault().find(new Path("lib/CubicUnit.jar"))).getPath()).toFile(), libFolder.getFile("CubicUnit.jar").getLocation().toFile()); } catch (IOException e1) { e1.printStackTrace(); } javaProject.setOutputLocation(binFolder.getFullPath(), monitor); IClasspathEntry[] classpath; classpath = new IClasspathEntry[] { JavaCore.newSourceEntry(srcFolder.getFullPath()), JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")), JavaCore.newLibraryEntry(libFolder.getFile("CubicTestElementAPI.jar").getFullPath(), null, null), JavaCore.newLibraryEntry(libFolder.getFile("CubicUnit.jar").getFullPath(), null, null) }; javaProject.setRawClasspath(classpath, binFolder.getFullPath(), monitor); ResourceNavigator navigator = null; IViewPart viewPart = workbench.getActiveWorkbenchWindow().getActivePage().getViewReferences()[0].getView(false); if (viewPart instanceof ResourceNavigator) { navigator = (ResourceNavigator) viewPart; } if (launchNewTestWizard) { launchNewTestWizard(testFolder); if (navigator != null && testFolder.members().length > 0) { navigator.selectReveal(new StructuredSelection(testFolder.members()[0])); } } project.refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e) { e.printStackTrace(); } } Code Sample 2: @Override public boolean checkConnection() { int status = 0; try { URL url = new URL(TupeloProxy.endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); status = conn.getResponseCode(); } catch (Exception e) { logger.severe("Connection test failed with code:" + status); e.printStackTrace(); } if (status < 200 || status >= 400) return false; String url = this.url + "?title=Special:UserLogin&action=submitlogin&type=login&returnto=Main_Page&wpDomain=" + domain + "&wpLoginattempt=Log%20in&wpName=" + username + "&wpPassword=" + password; return true; }
00
Code Sample 1: private int resourceToString(String aFile, StringBuffer aBuffer) { int cols = 0; URL url = getClass().getResource(aFile); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; do { line = in.readLine(); if (line != null) { if (line.length() > cols) cols = line.length(); aBuffer.append(line); aBuffer.append('\n'); } } while (line != null); } catch (IOException e) { e.printStackTrace(); } return cols; } Code Sample 2: protected void loadUrl(URL url) throws BuildException { Properties props = new Properties(); log("Loading " + url, Project.MSG_VERBOSE); try { InputStream is = url.openStream(); try { loadProperties(props, is, url.getFile().endsWith(".xml")); } finally { if (is != null) { is.close(); } } addProperties(props); } catch (IOException ex) { throw new BuildException(ex, getLocation()); } }
00
Code Sample 1: public Savable loadResource(String name, PrimitiveLoader loader) { Savable objeto = null; URL url = ResourceLocator.locateFile(loader.getBaseFolder(), name, loader.getCompiledExtension()); if (url == null) { url = ResourceLocator.locateFile(loader.getBaseFolder(), name, loader.getPrimitiveExtension()); if (url != null) { try { objeto = loader.loadResource(name, url.openStream()); File file = ResourceLocator.replaceExtension(url, loader.getCompiledExtension()); BinaryExporter.getInstance().save(objeto, file); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } } else { try { objeto = BinaryImporter.getInstance().load(url.openStream()); } catch (IOException e) { e.printStackTrace(); } } return objeto; } Code Sample 2: public InputSource resolveEntity(String name, String uri) throws IOException, SAXException { InputSource retval; String mappedURI = name2uri(name); InputStream stream; if (mappedURI == null && (stream = mapResource(name)) != null) { uri = "java:resource:" + (String) id2resource.get(name); retval = new InputSource(XmlReader.createReader(stream)); } else { URL url; URLConnection conn; if (mappedURI != null) uri = mappedURI; else if (uri == null) return null; url = new URL(uri); conn = url.openConnection(); uri = conn.getURL().toString(); if (ignoringMIME) retval = new InputSource(XmlReader.createReader(conn.getInputStream())); else { String contentType = conn.getContentType(); retval = createInputSource(contentType, conn.getInputStream(), false, url.getProtocol()); } } retval.setSystemId(uri); retval.setPublicId(name); return retval; }
11
Code Sample 1: @Test public void testCopy_readerToOutputStream_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); try { IOUtils.copy((Reader) null, out); fail(); } catch (NullPointerException ex) { } } Code Sample 2: static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } }
11
Code Sample 1: public void run() { if (getCommand() == null) throw new IllegalArgumentException("Given command is null!"); if (getSocketProvider() == null) throw new IllegalArgumentException("Given connection is not open!"); if (getCommand() instanceof ListCommand) { try { setReply(ReplyWorker.readReply(getSocketProvider(), true)); setStatus(ReplyWorker.FINISHED); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } return; } else if (getCommand() instanceof RetrieveCommand) { RetrieveCommand retrieveCommand = (RetrieveCommand) getCommand(); if (retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_I || retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_A) { try { log.debug("Download file: " + retrieveCommand.getFromFile().toString()); FileOutputStream out = null; FileChannel channel = null; if (getDownloadMethod() == RetrieveCommand.FILE_BASED) { out = new FileOutputStream(retrieveCommand.getToFile().getFile()); channel = out.getChannel(); if (retrieveCommand.getResumePosition() != -1) { try { channel.position(retrieveCommand.getResumePosition()); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); try { channel.close(); } catch (IOException ioe2) { } return; } } } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } int amount; try { while ((amount = getSocketProvider().read(buffer)) != -1) { if (amount == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } buffer.flip(); while (buffer.hasRemaining()) { if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) { int rem = buffer.remaining(); byte[] buf = new byte[rem]; buffer.get(buf, 0, rem); this.outputPipe.write(buf, 0, rem); } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } else { channel.write(buffer); } } buffer.clear(); } buffer.flip(); while (buffer.hasRemaining()) { if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) { int rem = buffer.remaining(); byte[] buf = new byte[rem]; buffer.get(buf, 0, rem); this.outputPipe.write(buf, 0, rem); } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } else { channel.write(buffer); } } buffer.clear(); setStatus(ReplyWorker.FINISHED); if (channel != null) channel.close(); if (this.outputPipe != null) this.outputPipe.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { channel.close(); getSocketProvider().close(); } catch (Exception e) { } } } catch (FileNotFoundException fnfe) { setCaughtException(fnfe); setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND); } } else throw new IllegalArgumentException("Unknown file transfer type for download!"); return; } else if (getCommand() instanceof StoreCommand) { StoreCommand storeCommand = (StoreCommand) getCommand(); if (storeCommand.getToFile().getTransferType().intern() == Command.TYPE_I || storeCommand.getToFile().getTransferType().intern() == Command.TYPE_A) { try { log.debug("Upload file: " + storeCommand.getFromFile()); InputStream in = storeCommand.getStream(); int amount; int socketWrite; int socketAmount = 0; if (in instanceof FileInputStream) { FileChannel channel = ((FileInputStream) in).getChannel(); if (storeCommand.getResumePosition() != -1) { try { channel.position(storeCommand.getResumePosition()); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); try { channel.close(); } catch (IOException ioe2) { } return; } } try { while ((amount = channel.read(buffer)) != -1) { buffer.flip(); socketWrite = 0; while ((socketWrite = getSocketProvider().write(buffer)) != -1) { socketAmount += socketWrite; if (amount <= socketAmount) { break; } if (socketWrite == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } } if (socketWrite == -1) { break; } socketAmount = 0; buffer.clear(); } setStatus(ReplyWorker.FINISHED); channel.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { channel.close(); getSocketProvider().close(); } catch (Exception e) { } } } else { try { while ((amount = in.read(buffer.array())) != -1) { buffer.flip(); buffer.limit(amount); socketWrite = 0; while ((socketWrite = getSocketProvider().write(buffer)) != -1) { socketAmount = socketWrite; if (amount <= socketAmount) { break; } if (socketWrite == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } } if (socketWrite == -1) { break; } socketAmount = 0; buffer.clear(); } setStatus(ReplyWorker.FINISHED); in.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { in.close(); getSocketProvider().close(); } catch (Exception e) { } } } } catch (FileNotFoundException fnfe) { setCaughtException(fnfe); setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND); } } else throw new IllegalArgumentException("Unknown file transfer type for upload!"); } else throw new IllegalArgumentException("Given command is not supported!"); } 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: public static IProject createSimplemodelEnabledJavaProject() throws CoreException { IWorkspaceDescription desc = ResourcesPlugin.getWorkspace().getDescription(); desc.setAutoBuilding(false); ResourcesPlugin.getWorkspace().setDescription(desc); String name = "TestProject"; for (int i = 0; i < 1000; i++) { IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(name + i); if (project.exists()) continue; project.create(null); project.open(null); IProjectDescription description = project.getDescription(); String[] natures = description.getNatureIds(); String[] newNatures = new String[natures.length + 2]; System.arraycopy(natures, 0, newNatures, 0, natures.length); newNatures[natures.length] = JavaCore.NATURE_ID; newNatures[natures.length + 1] = SimplemodelNature.NATURE_ID; description.setNatureIds(newNatures); project.setDescription(description, null); IJavaProject javaProject = JavaCore.create(project); Set<IClasspathEntry> entries = new HashSet<IClasspathEntry>(); IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall(); Path containerPath = new Path(JavaRuntime.JRE_CONTAINER); IPath vmPath = containerPath.append(vmInstall.getVMInstallType().getId()).append(vmInstall.getName()); entries.add(JavaCore.newContainerEntry(vmPath)); LibraryLocation[] locations = JavaRuntime.getLibraryLocations(vmInstall); for (LibraryLocation element : locations) { entries.add(JavaCore.newLibraryEntry(element.getSystemLibraryPath(), null, null)); } final Path srcPath = new Path("src"); final IFolder src = project.getFolder(srcPath); final Path binPath = new Path("bin"); final IFolder bin = project.getFolder(binPath); src.create(true, true, null); bin.create(true, true, null); entries.add(JavaCore.newSourceEntry(project.getFullPath().append(srcPath))); javaProject.setOutputLocation(project.getFullPath().append(binPath), null); javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null); return project; } throw new RuntimeException("Failed"); } Code Sample 2: public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (logger.isDebugEnabled()) { logger.debug("doAdd(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse) - start"); } t_information_EditMap editMap = new t_information_EditMap(); try { t_information_Form vo = null; vo = (t_information_Form) form; vo.setCompany(vo.getCounty()); if ("����".equals(vo.getInfo_type())) { vo.setInfo_level(null); vo.setAlert_level(null); } String str_postFIX = ""; int i_p = 0; editMap.add(vo); try { logger.info("���͹�˾�鱨��"); String[] mobiles = request.getParameterValues("mobiles"); vo.setMobiles(mobiles); SMSService.inforAlert(vo); } catch (Exception e) { logger.error("doAdd(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse)", e); } String filename = vo.getFile().getFileName(); if (null != filename && !"".equals(filename)) { FormFile file = vo.getFile(); String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String inforId = vo.getId(); String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); String strAppend = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); if (file.getFileSize() != 0) { file.getInputStream(); String name = file.getFileName(); i_p = file.getFileName().lastIndexOf("."); str_postFIX = file.getFileName().substring(i_p, file.getFileName().length()); String fullPath = realpath + "attach/" + strAppend + str_postFIX; t_attach attach = new t_attach(); attach.setAttach_fullname(fullPath); attach.setAttach_name(name); attach.setInfor_id(Integer.parseInt(inforId)); attach.setInsert_day(new Date()); attach.setUpdate_day(new Date()); t_attach_EditMap attachEdit = new t_attach_EditMap(); attachEdit.add(attach); File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(file.getInputStream(), out); out.close(); } } } catch (HibernateException e) { logger.error("doAdd(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse)", e); ActionErrors errors = new ActionErrors(); errors.add("org.apache.struts.action.GLOBAL_ERROR", new ActionError("error.database.save", e.toString())); saveErrors(request, errors); e.printStackTrace(); request.setAttribute("t_information_Form", form); if (logger.isDebugEnabled()) { logger.debug("doAdd(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse) - end"); } return "addpage"; } if (logger.isDebugEnabled()) { logger.debug("doAdd(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse) - end"); } return "aftersave"; }
00
Code Sample 1: public static void main(String[] args) throws Exception { String linesep = System.getProperty("line.separator"); FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt")); fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes()); fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes()); fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes()); fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes()); fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes()); fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes()); File[] files = new File(args[0]).listFiles(new JarFileFilter()); for (int i = 0; i < files.length; i++) { if (new File(files[i].getPath() + ".meta").exists()) { Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta")); Iterator<String> itsect = metaprops.keySet().iterator(); while (itsect.hasNext()) { String section = itsect.next(); fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes()); fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes()); fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes()); fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes()); fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes()); } } if (new File(files[i].getPath() + ".extra").exists()) { fos.write(new String("The author says:" + linesep).getBytes()); FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra")); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } fos.write(linesep.getBytes()); } fos.close(); } Code Sample 2: public void run() { if (!shouldLogin) { u.p("skipping the auto-login"); return; } try { u.p("logging in to the server"); String query = "hostname=blahfoo2.com" + "&osname=" + URLEncoder.encode(System.getProperty("os.name"), "UTF-8") + "&javaver=" + URLEncoder.encode(System.getProperty("java.runtime.version"), "UTF-8") + "&timezone=" + URLEncoder.encode(TimeZone.getDefault().getID(), "UTF-8"); u.p("unencoded query: \n" + query); String login_url = "http://joshy.org:8088/org.glossitopeTracker/login.jsp?"; String url = login_url + query; u.p("final encoded url = \n" + url); InputStream in = new URL(url).openStream(); byte[] buf = new byte[256]; while (true) { int n = in.read(buf); if (n == -1) break; for (int i = 0; i < n; i++) { } } } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
00
Code Sample 1: HttpURLConnection getHttpURLConnection(String bizDocToExecute, boolean doom, boolean cmt) { StringBuffer servletURL = new StringBuffer(); servletURL.append(getBaseServletURL()); servletURL.append("?_BIZVIEW=").append(bizDocToExecute); if (doom) { servletURL.append("&_DOOM=TRUE"); } if (cmt) { servletURL.append("&_CMT=TRUE"); } Map<String, Object> inputParms = getInputParams(); if (inputParms != null) { Set<Entry<String, Object>> entrySet = inputParms.entrySet(); for (Entry<String, Object> entry : entrySet) { String name = entry.getKey(); String value = entry.getValue().toString(); servletURL.append("&").append(name).append("=").append(value); } } HttpURLConnection connection = null; try { URL url = new URL(servletURL.toString()); connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { Assert.fail("Failed to connect to the test servlet: " + e); } return connection; } Code Sample 2: public LocationResponse getResponse(LocationRequest lrq) throws UnregisteredComponentException { LocationResponse lrs = lrq.createResponse(); try { String rqs, rss; rqs = encodeSkyhookRequest(lrq); if (null == rqs) { lrs.setError("No authentication was provided."); return lrs; } URL url = new URL(this.skyhookServerUri); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "text/xml"); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(rqs); wr.flush(); BufferedReader rd; rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); rss = ""; String line; while ((line = rd.readLine()) != null) rss += line; rd.close(); decodeSkyhookResponse(rss, lrs); } catch (Exception e) { e.printStackTrace(); lrs.setError("Error querying Skyhook"); } return lrs; }
00
Code Sample 1: public static String compute(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("UTF-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException nax) { RuntimeException rx = new IllegalStateException(); rx.initCause(rx); throw rx; } catch (UnsupportedEncodingException uex) { RuntimeException rx = new IllegalStateException(); rx.initCause(uex); throw rx; } } Code Sample 2: private FTPClient connect() throws FTPException { try { FTPClient ftp = new FTPClient(); ftp.connect(host, port); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); } ftp.login(userName, password); ftp.setFileType(FTP.BINARY_FILE_TYPE); return ftp; } catch (SocketException e) { throw new FTPException("Failed to connect to server", e); } catch (IOException e) { throw new FTPException("Failed to connect to server", e); } }
00
Code Sample 1: public static String executePost(String urlStr, Map paramsMap) throws IOException { StringBuffer result = new StringBuffer(); HttpURLConnection connection = null; URL url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); PrintWriter out = new PrintWriter(connection.getOutputStream()); Iterator paramKeys = paramsMap.keySet().iterator(); while (paramKeys.hasNext()) { String paramName = (String) paramKeys.next(); out.print(paramName + "=" + paramsMap.get(paramName)); if (paramKeys.hasNext()) { out.print('&'); } } out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { result.append(inputLine); } in.close(); out.close(); connection.disconnect(); String msg = result.toString(); return stripOuterElement(msg); } Code Sample 2: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
00
Code Sample 1: public void run(IAction action) { int style = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getStyle(); Shell shell = new Shell((style & SWT.MIRRORED) != 0 ? SWT.RIGHT_TO_LEFT : SWT.NONE); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(shell); viewer.setEditDomain(new DefaultEditDomain(null)); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setEditPartFactory(new ProjectEditPartFactory()); viewer.setContents(getContents()); viewer.flush(); int printMode = new PrintModeDialog(shell).open(); if (printMode == -1) return; PrintDialog dialog = new PrintDialog(shell, SWT.NULL); PrinterData data = dialog.open(); if (data != null) { PrintGraphicalViewerOperation op = new PrintGraphicalViewerOperation(new Printer(data), viewer); op.setPrintMode(printMode); op.run(selectedFile.getName()); } } Code Sample 2: public static String hash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: private String getMD5(String data) { try { MessageDigest md5Algorithm = MessageDigest.getInstance("MD5"); md5Algorithm.update(data.getBytes(), 0, data.length()); byte[] digest = md5Algorithm.digest(); StringBuffer hexString = new StringBuffer(); String hexDigit = null; for (int i = 0; i < digest.length; i++) { hexDigit = Integer.toHexString(0xFF & digest[i]); if (hexDigit.length() < 2) { hexDigit = "0" + hexDigit; } hexString.append(hexDigit); } return hexString.toString(); } catch (NoSuchAlgorithmException ne) { return data; } } Code Sample 2: private void getInfoFromXML() { final ProgressDialog dialog = ProgressDialog.show(this, "", getString(R.string.loading), true, true); setProgressBarIndeterminateVisibility(true); Thread t3 = new Thread() { public void run() { waiting(200); txtinfo.post(new Runnable() { public void run() { txtinfo.setText("Searching"); } }); try { URL url = new URL(urlAddress); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); XMLHandlerReviews myXMLHandler = new XMLHandlerReviews(); xr.setContentHandler(myXMLHandler); xr.parse(new InputSource(url.openStream())); if (statuscode != 200 && statuscode != 206) { throw new Exception(); } nReviewsOnPage = myXMLHandler.nItems; statuscode = myXMLHandler.statuscode; if (nReviewsOnPage > 0) { authors = new String[nReviewsOnPage]; reviews = new String[nReviewsOnPage]; ratings = new String[nReviewsOnPage]; titles = new String[nReviewsOnPage]; listtext = new String[nReviewsOnPage]; for (int i = 0; i < nReviewsOnPage; i++) { reviews[i] = myXMLHandler.reviews[i]; authors[i] = myXMLHandler.authors[i]; titles[i] = myXMLHandler.titles[i]; ratings[i] = myXMLHandler.ratings[i]; if (authors[i] == null || authors[i] == "") { authors[i] = "Anonymous"; } if (ratings[i] == null || ratings[i] == "") { listtext[i] = titles[i] + " - " + reviews[i] + " - " + authors[i]; } else { listtext[i] = "Score: " + ratings[i] + " - " + titles[i] + " - " + reviews[i] + " - " + authors[i]; } } nTotalReviews = myXMLHandler.nTotalItems; final int fnmin = iFirstReviewOnPage; final int fnmax = iFirstReviewOnPage + nReviewsOnPage - 1; final int fntotalitems = nTotalReviews; if (nTotalReviews > fnmax) { nextButton.post(new Runnable() { public void run() { nextButton.setVisibility(0); } }); } else { nextButton.post(new Runnable() { public void run() { nextButton.setVisibility(8); } }); } if (iFirstReviewOnPage > 1) { previousButton.post(new Runnable() { public void run() { previousButton.setVisibility(0); } }); } else if (nTotalReviews > fnmax) { previousButton.post(new Runnable() { public void run() { previousButton.setVisibility(8); } }); } else { previousButton.post(new Runnable() { public void run() { previousButton.setVisibility(4); } }); } txtinfo.post(new Runnable() { public void run() { if (title != null && title != "") { txtinfo.setText(title + "\n" + getString(R.string.showing) + " " + fnmin + " " + getString(R.string.through) + " " + fnmax + " " + getString(R.string.of) + " " + fntotalitems); } else { txtinfo.setText(getString(R.string.showing) + " " + fnmin + " " + getString(R.string.through) + " " + fnmax + " " + getString(R.string.of) + " " + fntotalitems); } } }); handlerSetList.sendEmptyMessage(0); } else { txtinfo.post(new Runnable() { public void run() { txtinfo.setText(title + getString(R.string.no_reviews_for_this_album)); } }); } } catch (Exception e) { final Exception ef = e; txtinfo.post(new Runnable() { public void run() { txtinfo.setText(R.string.search_failed); } }); } dialog.dismiss(); handlerDoneLoading.sendEmptyMessage(0); } }; t3.start(); }
11
Code Sample 1: private static void backupFile(File file) { FileChannel in = null, out = null; try { if (!file.getName().endsWith(".bak")) { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(new File(file.toString() + ".bak")).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } } catch (Exception e) { e.getMessage(); } finally { try { System.gc(); if (in != null) in.close(); if (out != null) out.close(); } catch (Exception e) { e.getMessage(); } } } Code Sample 2: 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; }
11
Code Sample 1: private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { GTLogger.getInstance().error(e); } } catch (FileNotFoundException e) { GTLogger.getInstance().error(e); } } Code Sample 2: public DataRecord addRecord(InputStream input) throws DataStoreException { File temporary = null; try { temporary = newTemporaryFile(); DataIdentifier tempId = new DataIdentifier(temporary.getName()); usesIdentifier(tempId); long length = 0; MessageDigest digest = MessageDigest.getInstance(DIGEST); OutputStream output = new DigestOutputStream(new FileOutputStream(temporary), digest); try { length = IOUtils.copyLarge(input, output); } finally { output.close(); } DataIdentifier identifier = new DataIdentifier(digest.digest()); File file; synchronized (this) { usesIdentifier(identifier); file = getFile(identifier); System.out.println("new file name: " + file.getName()); File parent = file.getParentFile(); System.out.println("parent file: " + file.getParentFile().getName()); if (!parent.isDirectory()) { parent.mkdirs(); } if (!file.exists()) { temporary.renameTo(file); if (!file.exists()) { throw new IOException("Can not rename " + temporary.getAbsolutePath() + " to " + file.getAbsolutePath() + " (media read only?)"); } } else { long now = System.currentTimeMillis(); if (file.lastModified() < now) { file.setLastModified(now); } } if (!file.isFile()) { throw new IOException("Not a file: " + file); } if (file.length() != length) { throw new IOException(DIGEST + " collision: " + file); } } inUse.remove(tempId); return new FileDataRecord(identifier, file); } catch (NoSuchAlgorithmException e) { throw new DataStoreException(DIGEST + " not available", e); } catch (IOException e) { throw new DataStoreException("Could not add record", e); } finally { if (temporary != null) { temporary.delete(); } } }
00
Code Sample 1: public byte[] applyTransformationOnURL(String url, int format) throws RemoteException { byte[] result = null; try { result = applyTransformation(new URL(url).openStream(), format); } catch (Exception e) { throwServiceException(e); } return result; } Code Sample 2: private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } }
11
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getParameter("i") != null) { String img = req.getParameter("i"); if (img == null) { resp.sendError(404, "Image was null"); return; } File f = null; if (img.startsWith("file")) { try { f = new File(new URI(img)); } catch (URISyntaxException e) { resp.sendError(500, e.getMessage()); return; } } else { f = new File(img); } if (f.exists()) { f = f.getCanonicalFile(); if (f.getName().endsWith(".jpg") || f.getName().endsWith(".png")) { resp.setContentType("image/png"); FileInputStream fis = null; OutputStream os = resp.getOutputStream(); try { fis = new FileInputStream(f); IOUtils.copy(fis, os); } finally { os.flush(); if (fis != null) fis.close(); } } } return; } String mediaUrl = "/media" + req.getPathInfo(); String parts[] = mediaUrl.split("/"); mediaHandler.handleRequest(parts, req, resp); } Code Sample 2: public static void moveOutputAsmFile(File inputLocation, File outputLocation) throws Exception { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(inputLocation); outputStream = new FileOutputStream(outputLocation); byte buffer[] = new byte[1024]; while (inputStream.available() > 0) { int read = inputStream.read(buffer); outputStream.write(buffer, 0, read); } inputLocation.delete(); } finally { IOUtil.closeAndIgnoreErrors(inputStream); IOUtil.closeAndIgnoreErrors(outputStream); } }
11
Code Sample 1: public static String novoMetodoDeCriptografarParaMD5QueNaoFoiUtilizadoAinda(String input) { if (input == null) { return null; } try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes("UTF-8")); BigInteger hash = new BigInteger(1, digest.digest()); String output = hash.toString(16); if (output.length() < 32) { int sizeDiff = 32 - output.length(); do { output = "0" + output; } while (--sizeDiff > 0); } return output; } catch (NoSuchAlgorithmException ns) { LoggerFactory.getLogger(UtilAdrs.class).error(Msg.EXCEPTION_MESSAGE, UtilAdrs.class.getSimpleName(), ns); return input; } catch (UnsupportedEncodingException e) { LoggerFactory.getLogger(UtilAdrs.class).error(Msg.EXCEPTION_MESSAGE, UtilAdrs.class.getSimpleName(), e); return input; } } Code Sample 2: public static String generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0L; 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 < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { log.error("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); }
11
Code Sample 1: public static void copy(File srcFile, File destFile) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(srcFile); out = new FileOutputStream(destFile); final byte[] buf = new byte[4096]; int read; while ((read = in.read(buf)) >= 0) { out.write(buf, 0, read); } } finally { try { if (in != null) in.close(); } catch (IOException ioe) { } try { if (out != null) out.close(); } catch (IOException ioe) { } } } Code Sample 2: 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; }
00
Code Sample 1: public boolean moveFileSafely(final File in, final File out) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; FileChannel inChannel = null; FileChannel outChannel = null; final File tempOut = File.createTempFile("move", ".tmp"); try { fis = new FileInputStream(in); fos = new FileOutputStream(tempOut); inChannel = fis.getChannel(); outChannel = fos.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { try { if (inChannel != null) inChannel.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", inChannel); } try { if (outChannel != null) outChannel.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", outChannel); } try { if (fis != null) fis.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fis); } try { if (fos != null) fos.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fos); } } out.delete(); if (!out.exists()) { tempOut.renameTo(out); return in.delete(); } return false; } Code Sample 2: public static String getCssFile(String url) { StringBuffer buffer = new StringBuffer(); try { buffer = new StringBuffer(); URL urlToCrawl = new URL(url); URLConnection urlToCrawlConnection = urlToCrawl.openConnection(); urlToCrawlConnection.setRequestProperty("User-Agent", "USER_AGENT"); urlToCrawlConnection.setRequestProperty("Referer", "REFERER"); urlToCrawlConnection.setUseCaches(false); InputStreamReader isr = new InputStreamReader(urlToCrawlConnection.getInputStream()); BufferedReader in = new BufferedReader(isr); String str; while ((str = in.readLine()) != null) buffer.append(str); FileOutputStream fos = new FileOutputStream("c:\\downloads\\" + System.currentTimeMillis() + ".css"); Writer out = new OutputStreamWriter(fos); out.write(buffer.toString()); out.close(); } catch (Exception e) { System.out.println("Error Downloading css file" + e); } return buffer.toString(); }
00
Code Sample 1: public void testJPEGBuffImage() throws MalformedURLException, IOException { System.out.println("JPEGCodec BufferedImage:"); long start = Calendar.getInstance().getTimeInMillis(); for (int i = 0; i < images.length; i++) { String url = Constants.getDefaultURIMediaConnectorBasePath() + "albums/hund/" + images[i]; InputStream istream = (new URL(url)).openStream(); JPEGImageDecoder dec = JPEGCodec.createJPEGDecoder(istream); BufferedImage image = dec.decodeAsBufferedImage(); int width = image.getWidth(); int height = image.getHeight(); istream.close(); System.out.println("w: " + width + " - h: " + height); } long stop = Calendar.getInstance().getTimeInMillis(); System.out.println("zeit: " + (stop - start)); } Code Sample 2: private void jbInit() throws Exception { getContentPane().setLayout(borderLayout1); this.setTitle("�ϥλ���"); jTextPane1.setEditable(false); this.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); jScrollPane1.getViewport().add(jTextPane1); this.setSize(400, 600); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); URL url = ReadmeFrame.class.getResource("readme.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuilder strBuilder = new StringBuilder(); while (reader.ready()) { strBuilder.append(reader.readLine()); strBuilder.append('\n'); } reader.close(); jTextPane1.setText(strBuilder.toString()); }
11
Code Sample 1: public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text ".getBytes())); fc.close(); fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("Some more".getBytes())); fc.close(); fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) System.out.print((char) buff.get()); } Code Sample 2: public void generate(String rootDir, RootModel root) throws Exception { IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("stylesheet.css"), new FileOutputStream(new File(rootDir, "stylesheet.css"))); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("model", root); context.put("util", new VelocityUtils()); context.put("msg", messages); processTemplate("index.html", new File(rootDir, "index.html"), context); processTemplate("list.html", new File(rootDir, "list.html"), context); processTemplate("summary.html", new File(rootDir, "summary.html"), context); File imageDir = new File(rootDir, "images"); imageDir.mkdir(); IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("primarykey.gif"), new FileOutputStream(new File(imageDir, "primarykey.gif"))); File tableDir = new File(rootDir, "tables"); tableDir.mkdir(); for (TableModel table : root.getTables()) { context.put("table", table); processTemplate("table.html", new File(tableDir, table.getTableName() + ".html"), context); } }
00
Code Sample 1: public Web(String urlString, String charset) throws java.net.MalformedURLException, java.io.IOException { this.charset = charset; final java.net.URL url = new java.net.URL(urlString); final java.net.URLConnection uconn = url.openConnection(); if (!(uconn instanceof java.net.HttpURLConnection)) throw new java.lang.IllegalArgumentException("URL protocol must be HTTP."); final java.net.HttpURLConnection conn = (java.net.HttpURLConnection) uconn; conn.setConnectTimeout(600000); conn.setReadTimeout(600000); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-agent", "spider"); conn.connect(); responseHeader = conn.getHeaderFields(); responseCode = conn.getResponseCode(); responseURL = conn.getURL(); length = conn.getContentLength(); final java.io.InputStream stream = conn.getErrorStream(); if (stream != null) { content = readStream(length, stream); } else if ((inputStream = conn.getContent()) != null && inputStream instanceof java.io.InputStream) { content = readStream(length, (java.io.InputStream) inputStream); } conn.disconnect(); } Code Sample 2: public void adjustPadding(File file, int paddingSize, long audioStart) throws FileNotFoundException, IOException { logger.finer("Need to move audio file to accomodate tag"); FileChannel fcIn = null; FileChannel fcOut; ByteBuffer paddingBuffer = ByteBuffer.wrap(new byte[paddingSize]); File paddedFile; try { paddedFile = File.createTempFile(Utils.getMinBaseFilenameAllowedForTempFile(file), ".new", file.getParentFile()); logger.finest("Created temp file:" + paddedFile.getName() + " for " + file.getName()); } catch (IOException ioe) { logger.log(Level.SEVERE, ioe.getMessage(), ioe); if (ioe.getMessage().equals(FileSystemMessage.ACCESS_IS_DENIED.getMsg())) { logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); throw new UnableToCreateFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); } else { logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); throw new UnableToCreateFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); } } try { fcOut = new FileOutputStream(paddedFile).getChannel(); } catch (FileNotFoundException ioe) { logger.log(Level.SEVERE, ioe.getMessage(), ioe); logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_MODIFY_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); throw new UnableToModifyFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_MODIFY_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); } try { fcIn = new FileInputStream(file).getChannel(); long written = fcOut.write(paddingBuffer); logger.finer("Copying:" + (file.length() - audioStart) + "bytes"); long audiolength = file.length() - audioStart; if (audiolength <= MAXIMUM_WRITABLE_CHUNK_SIZE) { long written2 = fcIn.transferTo(audioStart, audiolength, fcOut); logger.finer("Written padding:" + written + " Data:" + written2); if (written2 != audiolength) { throw new RuntimeException(ErrorMessage.MP3_UNABLE_TO_ADJUST_PADDING.getMsg(audiolength, written2)); } } else { long noOfChunks = audiolength / MAXIMUM_WRITABLE_CHUNK_SIZE; long lastChunkSize = audiolength % MAXIMUM_WRITABLE_CHUNK_SIZE; long written2 = 0; for (int i = 0; i < noOfChunks; i++) { written2 += fcIn.transferTo(audioStart + (i * MAXIMUM_WRITABLE_CHUNK_SIZE), MAXIMUM_WRITABLE_CHUNK_SIZE, fcOut); } written2 += fcIn.transferTo(audioStart + (noOfChunks * MAXIMUM_WRITABLE_CHUNK_SIZE), lastChunkSize, fcOut); logger.finer("Written padding:" + written + " Data:" + written2); if (written2 != audiolength) { throw new RuntimeException(ErrorMessage.MP3_UNABLE_TO_ADJUST_PADDING.getMsg(audiolength, written2)); } } long lastModified = file.lastModified(); if (fcIn != null) { if (fcIn.isOpen()) { fcIn.close(); } } if (fcOut != null) { if (fcOut.isOpen()) { fcOut.close(); } } replaceFile(file, paddedFile); paddedFile.setLastModified(lastModified); } finally { try { if (fcIn != null) { if (fcIn.isOpen()) { fcIn.close(); } } if (fcOut != null) { if (fcOut.isOpen()) { fcOut.close(); } } } catch (Exception e) { logger.log(Level.WARNING, "Problem closing channels and locks:" + e.getMessage(), e); } } }
00
Code Sample 1: private void loginImageShack() throws Exception { loginsuccessful = false; HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); NULogger.getLogger().info("Trying to log in to imageshack.us"); HttpPost httppost = new HttpPost("http://imageshack.us/auth.php"); httppost.setHeader("Referer", "http://www.uploading.com/"); httppost.setHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); httppost.setHeader("Cookie", newcookie + ";" + phpsessioncookie + ";" + imgshckcookie + ";" + uncookie + ";" + latestcookie + ";" + langcookie); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("username", getUsername())); formparams.add(new BasicNameValuePair("password", getPassword())); formparams.add(new BasicNameValuePair("stay_logged_in", "")); formparams.add(new BasicNameValuePair("format", "json")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); HttpEntity en = httpresponse.getEntity(); uploadresponse = EntityUtils.toString(en); NULogger.getLogger().log(Level.INFO, "Upload response : {0}", uploadresponse); NULogger.getLogger().info("Getting cookies........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("myid")) { myidcookie = escookie.getValue(); NULogger.getLogger().info(myidcookie); loginsuccessful = true; } if (escookie.getName().equalsIgnoreCase("myimages")) { myimagescookie = escookie.getValue(); NULogger.getLogger().info(myimagescookie); } if (escookie.getName().equalsIgnoreCase("isUSER")) { usercookie = escookie.getValue(); NULogger.getLogger().info(usercookie); } } if (loginsuccessful) { NULogger.getLogger().info("ImageShack Login Success"); loginsuccessful = true; username = getUsername(); password = getPassword(); } else { NULogger.getLogger().info("ImageShack Login failed"); loginsuccessful = false; username = ""; password = ""; JOptionPane.showMessageDialog(NeembuuUploader.getInstance(), "<html><b>" + HOSTNAME + "</b> " + TranslationProvider.get("neembuuuploader.accounts.loginerror") + "</html>", HOSTNAME, JOptionPane.WARNING_MESSAGE); AccountsManager.getInstance().setVisible(true); } } Code Sample 2: private String readWebpage() { BufferedReader in = null; StringBuffer sb = new StringBuffer(); try { URI uri = new URI("file:///www.vogella.de"); IProxyService proxyService = getProxyService(); IProxyData[] proxyDataForHost = proxyService.select(uri); for (IProxyData data : proxyDataForHost) { if (data.getHost() != null) { System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", data.getHost()); } if (data.getHost() != null) { System.setProperty("http.proxyPort", String.valueOf(data.getPort())); } } proxyService = null; URL url; url = uri.toURL(); in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine + "\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); }
11
Code Sample 1: public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } } Code Sample 2: public TapdocContextImpl(Registry registry, FileObject javaDom, List<String> javadocLinks, List<String> libraryLocations, FileObject outputDirectory, List<String> tapdocLinks, DocumentGenerator documentGenerator) { this.registry = registry; this.documentGenerator = documentGenerator; try { if (javaDom == null) { javaDom = outputDirectory.resolveFile("tapdoc-javadom.xml"); } if (!javaDom.exists()) { javaDom.createFile(); javaDom.close(); IOUtils.copy(new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?><tapdoc-javadom></tapdoc-javadom>"), javaDom.getContent().getOutputStream()); } this.javaDom = javaDom; this.javadocLinks = javadocLinks; this.tapdocLinks = tapdocLinks; this.libraryLocations = libraryLocations; this.outputDirectory = outputDirectory; } catch (Exception e) { throw new RuntimeException(e); } }
11
Code Sample 1: public static String getPasswordHash(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes()); byte[] byteData = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { logger.log(Level.SEVERE, "Unknow error in hashing password", e); return "Unknow error, check system log"; } } Code Sample 2: public String encripta(String senha) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return senha; } }
11
Code Sample 1: 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"); } } Code Sample 2: public GetMessages(String messageType) { String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetMessages"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "messages.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&messagetype=" + messageType + "&filename=" + URLEncoder.encode(username, "UTF-8") + "messages.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("message"); int num = nodelist.getLength(); messages = new String[num][7]; for (int i = 0; i < num; i++) { messages[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messageid")); messages[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "subject")); messages[i][2] = (new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "firstname"))) + " " + (new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "lastname"))); messages[i][3] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messagedatetime")); messages[i][4] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messagefrom")); messages[i][5] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messageto")); messages[i][6] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "documentid")); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException e) { } catch (Exception ex) { System.out.println(ex); } }
11
Code Sample 1: 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); } } Code Sample 2: public static PortalConfig install(File xml, File dir) throws IOException, ConfigurationException { if (!dir.exists()) { log.info("Creating directory {}", dir); dir.mkdirs(); } if (!xml.exists()) { log.info("Installing default configuration to {}", xml); OutputStream output = new FileOutputStream(xml); try { InputStream input = ResourceLoader.open("res://" + PORTAL_CONFIG_XML); try { IOUtils.copy(input, output); } finally { input.close(); } } finally { output.close(); } } return create(xml, dir); }
11
Code Sample 1: protected void convertInternal(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream, DocumentFormat outputFormat) { File inputFile = null; File outputFile = null; try { inputFile = File.createTempFile("document", "." + inputFormat.getFileExtension()); OutputStream inputFileStream = null; try { inputFileStream = new FileOutputStream(inputFile); IOUtils.copy(inputStream, inputFileStream); } finally { IOUtils.closeQuietly(inputFileStream); } outputFile = File.createTempFile("document", "." + outputFormat.getFileExtension()); convert(inputFile, inputFormat, outputFile, outputFormat); InputStream outputFileStream = null; try { outputFileStream = new FileInputStream(outputFile); IOUtils.copy(outputFileStream, outputStream); } finally { IOUtils.closeQuietly(outputFileStream); } } catch (IOException ioException) { throw new OpenOfficeException("conversion failed", ioException); } finally { if (inputFile != null) { inputFile.delete(); } if (outputFile != null) { outputFile.delete(); } } } Code Sample 2: private void copyFile(File source, File dest) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: private void initUserExtensions(SeleniumConfiguration seleniumConfiguration) throws IOException { StringBuilder contents = new StringBuilder(); StringOutputStream s = new StringOutputStream(); IOUtils.copy(SeleniumConfiguration.class.getResourceAsStream("default-user-extensions.js"), s); contents.append(s.toString()); File providedUserExtensions = seleniumConfiguration.getFile(ConfigurationPropertyKeys.SELENIUM_USER_EXTENSIONS, seleniumConfiguration.getDirectoryConfiguration().getInput(), false); if (providedUserExtensions != null) { contents.append(FileUtils.readFileToString(providedUserExtensions, null)); } seleniumUserExtensions = new File(seleniumConfiguration.getDirectoryConfiguration().getInput(), "user-extensions.js"); FileUtils.forceMkdir(seleniumUserExtensions.getParentFile()); FileUtils.writeStringToFile(seleniumUserExtensions, contents.toString(), null); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { closeQuietly(in); closeQuietly(out); } return success; }
00
Code Sample 1: @Override protected String doInBackground(Void... params) { try { HttpGet request = new HttpGet(UPDATE_URL); request.setHeader("Accept", "text/plain"); HttpResponse response = MyMovies.getHttpClient().execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { return "Error: Failed getting update notes"; } return EntityUtils.toString(response.getEntity()); } catch (Exception e) { return "Error: " + e.getMessage(); } } Code Sample 2: public static String MD5(String input) throws Exception { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(input.getBytes(), 0, input.length()); input = new BigInteger(1, m.digest()).toString(16); if (input.length() == 31) input = "0" + input; return input; }
00
Code Sample 1: @NotNull public Set<Class<?>> in(Package pack) { String packageName = pack.getName(); String packageOnly = pack.getName(); final boolean recursive = true; Set<Class<?>> classes = new LinkedHashSet<Class<?>>(); String packageDirName = packageOnly.replace('.', '/'); Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); } catch (IOException e) { throw new PackageScanFailedException("Could not read from package directory: " + packageDirName, e); } while (dirs.hasMoreElements()) { URL url = dirs.nextElement(); String protocol = url.getProtocol(); if ("file".equals(protocol)) { try { findClassesInDirPackage(packageOnly, URLDecoder.decode(url.getFile(), "UTF-8"), recursive, classes); } catch (UnsupportedEncodingException e) { throw new PackageScanFailedException("Could not read from file: " + url, e); } } else if ("jar".equals(protocol)) { JarFile jar; try { jar = ((JarURLConnection) url.openConnection()).getJarFile(); } catch (IOException e) { throw new PackageScanFailedException("Could not read from jar url: " + url, e); } Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.charAt(0) == '/') { name = name.substring(1); } if (name.startsWith(packageDirName)) { int idx = name.lastIndexOf('/'); if (idx != -1) { packageName = name.substring(0, idx).replace('/', '.'); } if ((idx != -1) || recursive) { if (name.endsWith(".class") && !entry.isDirectory()) { String className = name.substring(packageName.length() + 1, name.length() - 6); add(packageName, classes, className); } } } } } } return classes; } Code Sample 2: public void playSIDFromURL(String name) { player.reset(); player.setStatus("Loading song: " + name); URL url; try { if (name.startsWith("http")) { url = new URL(name); } else { url = getResource(name); } if (player.readSID(url.openConnection().getInputStream())) { player.playSID(); } } catch (IOException ioe) { System.out.println("Could not load: "); ioe.printStackTrace(); player.setStatus("Could not load SID: " + ioe.getMessage()); } }
00
Code Sample 1: @Test public void testCopy_readerToOutputStream_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); try { IOUtils.copy((Reader) null, out); fail(); } catch (NullPointerException ex) { } } Code Sample 2: protected void initDefaultRolesFile() { String webConfigPath = System.getProperty("dcm4chee-web3.cfg.path", "conf/dcm4chee-web3"); File mappingFile = new File(webConfigPath + "roles.json"); if (!mappingFile.isAbsolute()) mappingFile = new File(ServerConfigLocator.locate().getServerHomeDir(), mappingFile.getPath()); if (mappingFile.exists()) return; log.info("Init default Role Mapping file! mappingFile:" + mappingFile); if (mappingFile.getParentFile().mkdirs()) log.info("M-WRITE dir:" + mappingFile.getParent()); FileChannel fos = null; InputStream is = null; try { URL url = getClass().getResource("/META-INF/roles-default.json"); log.info("Use default Mapping File content of url:" + url); is = url.openStream(); ReadableByteChannel inCh = Channels.newChannel(is); fos = new FileOutputStream(mappingFile).getChannel(); int pos = 0; while (is.available() > 0) pos += fos.transferFrom(inCh, pos, is.available()); } catch (Exception e) { log.error("Roles file doesn't exist and the default can't be created!", e); } finally { close(is); close(fos); } }
11
Code Sample 1: private static void extract(ZipFile zipFile) throws Exception { FileUtils.deleteQuietly(WEBKIT_DIR); WEBKIT_DIR.mkdirs(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { new File(WEBKIT_DIR, entry.getName()).mkdirs(); continue; } InputStream inputStream = zipFile.getInputStream(entry); File outputFile = new File(WEBKIT_DIR, entry.getName()); FileOutputStream outputStream = new FileOutputStream(outputFile); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } Code Sample 2: public boolean clonarFichero(String rutaFicheroOrigen, String rutaFicheroDestino) { System.out.println(""); System.out.println("*********** DENTRO DE 'clonarFichero' ***********"); boolean estado = false; try { FileInputStream entrada = new FileInputStream(rutaFicheroOrigen); FileOutputStream salida = new FileOutputStream(rutaFicheroDestino); FileChannel canalOrigen = entrada.getChannel(); FileChannel canalDestino = salida.getChannel(); canalOrigen.transferTo(0, canalOrigen.size(), canalDestino); entrada.close(); salida.close(); estado = true; } catch (IOException e) { System.out.println("No se encontro el archivo"); e.printStackTrace(); estado = false; } return estado; }
11
Code Sample 1: public static void copy(String srcFileName, String destFileName) throws IOException { if (srcFileName == null) { throw new IllegalArgumentException("srcFileName is null"); } if (destFileName == null) { throw new IllegalArgumentException("destFileName is null"); } FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(srcFileName).getChannel(); dest = new FileOutputStream(destFileName).getChannel(); long n = src.size(); MappedByteBuffer buf = src.map(FileChannel.MapMode.READ_ONLY, 0, n); dest.write(buf); } finally { if (dest != null) { try { dest.close(); } catch (IOException e1) { } } if (src != null) { try { src.close(); } catch (IOException e1) { } } } } Code Sample 2: public static File insertFileInto(File zipFile, File toInsert, String targetPath) { Zip64File zip64File = null; try { boolean compress = false; zip64File = new Zip64File(zipFile); FileEntry testEntry = getFileEntry(zip64File, targetPath); if (testEntry != null && testEntry.getMethod() == FileEntry.iMETHOD_DEFLATED) { compress = true; } processAndCreateFolderEntries(zip64File, parseTargetPath(targetPath, toInsert), compress); if (testEntry != null) { log.info("[insertFileInto] Entry exists: " + testEntry.getName()); log.info("[insertFileInto] Will delete this entry before inserting: " + toInsert.getName()); if (!testEntry.isDirectory()) { zip64File.delete(testEntry.getName()); } else { log.info("[insertFileInto] Entry is a directory. " + "Will delete all files contained in this entry and insert " + toInsert.getName() + "and all nested files."); if (!targetPath.contains("/")) { targetPath = targetPath + "/"; } deleteFileEntry(zip64File, testEntry); log.info("[insertFileInto] Entry successfully deleted."); } log.info("[insertFileInto] Writing new Entry: " + targetPath); EntryOutputStream out = null; if (!compress) { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_STORED, new Date(toInsert.lastModified())); } else { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_DEFLATED, new Date(toInsert.lastModified())); } if (toInsert.isDirectory()) { out.flush(); out.close(); log.info("[insertFileInto] Finished writing entry: " + targetPath); List<String> containedPaths = normalizePaths(toInsert); List<File> containedFiles = listAllFilesAndFolders(toInsert, new ArrayList<File>()); log.info("[insertFileInto] Added entry is a folder."); log.info("[insertFileInto] Adding all nested files: "); for (int i = 0; i < containedPaths.size(); i++) { File currentFile = containedFiles.get(i); String currentPath = targetPath.replace("/", "") + File.separator + containedPaths.get(i); EntryOutputStream loop_out = null; if (!compress) { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_STORED, new Date(currentFile.lastModified())); } else { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_DEFLATED, new Date(currentFile.lastModified())); } if (currentFile.isFile()) { InputStream loop_in = new FileInputStream(currentFile); IOUtils.copyLarge(loop_in, loop_out); loop_in.close(); } log.info("[insertFileInto] Added: " + currentPath); loop_out.flush(); loop_out.close(); } } else { InputStream in = new FileInputStream(toInsert); IOUtils.copyLarge(in, out); in.close(); out.flush(); out.close(); } } else { EntryOutputStream out = null; if (!compress) { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_STORED, new Date(toInsert.lastModified())); } else { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_DEFLATED, new Date(toInsert.lastModified())); } if (toInsert.isDirectory()) { out.flush(); out.close(); log.info("[insertFileInto] Finished writing entry: " + targetPath); List<String> containedPaths = normalizePaths(toInsert); List<File> containedFiles = listAllFilesAndFolders(toInsert, new ArrayList<File>()); log.info("[insertFileInto] Added entry is a folder."); log.info("[insertFileInto] Adding all nested files: "); for (int i = 0; i < containedPaths.size(); i++) { File currentFile = containedFiles.get(i); String currentPath = targetPath.replace("/", "") + File.separator + containedPaths.get(i); EntryOutputStream loop_out = null; if (!compress) { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_STORED, new Date(currentFile.lastModified())); } else { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_DEFLATED, new Date(currentFile.lastModified())); } if (currentFile.isFile()) { InputStream loop_in = new FileInputStream(currentFile); IOUtils.copyLarge(loop_in, loop_out); loop_in.close(); } log.info("[insertFileInto] Added: " + currentPath); loop_out.flush(); loop_out.close(); } } else { InputStream in = new FileInputStream(toInsert); IOUtils.copyLarge(in, out); in.close(); out.flush(); out.close(); } } log.info("[insertFileInto] Done! Added " + toInsert.getName() + " to zip."); zip64File.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return new File(zip64File.getDiskFile().getFileName()); }
11
Code Sample 1: public static void encrypt(File plain, File symKey, File ciphered, String algorithm) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { Key key = null; try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(symKey)); key = (Key) in.readObject(); } catch (IOException ioe) { KeyGenerator generator = KeyGenerator.getInstance(algorithm); key = generator.generateKey(); ObjectOutputStream out = new ObjectOutputStream(new java.io.FileOutputStream(symKey)); out.writeObject(key); out.close(); } Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getEncoded(), algorithm)); FileInputStream in = new FileInputStream(plain); CipherOutputStream out = new CipherOutputStream(new FileOutputStream(ciphered), cipher); byte[] buffer = new byte[4096]; for (int read = in.read(buffer); read > -1; read = in.read(buffer)) { out.write(buffer, 0, read); } out.close(); } Code Sample 2: public static void copyTo(File inFile, File outFile) throws IOException { char[] cbuff = new char[32768]; BufferedReader reader = new BufferedReader(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); int readedBytes = 0; long absWrittenBytes = 0; while ((readedBytes = reader.read(cbuff, 0, cbuff.length)) != -1) { writer.write(cbuff, 0, readedBytes); absWrittenBytes += readedBytes; } reader.close(); writer.close(); }
11
Code Sample 1: public static Properties parse() { try { String userHome = System.getProperty("user.home"); File dsigFolder = new File(userHome, ".dsig"); if (!dsigFolder.exists() && !dsigFolder.mkdir()) { throw new IOException("Could not create .dsig folder in user home directory"); } File settingsFile = new File(dsigFolder, "settings.properties"); if (!settingsFile.exists()) { InputStream is = UserHomeSettingsParser.class.getResourceAsStream("/defaultSettings.properties"); if (is != null) { IOUtils.copy(is, new FileOutputStream(settingsFile)); } } if (settingsFile.exists()) { Properties p = new Properties(); FileInputStream fis = new FileInputStream(settingsFile); p.load(fis); IOUtils.closeQuietly(fis); return p; } } catch (IOException e) { logger.warn("Error while initialize settings", e); } return null; } Code Sample 2: public ActionForward uploadFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request, HttpServletResponse in_response) { ActionMessages errors = new ActionMessages(); ActionMessages messages = new ActionMessages(); String returnPage = "submitPocketSampleInformationPage"; UploadForm form = (UploadForm) actForm; Integer shippingId = null; try { eHTPXXLSParser parser = new eHTPXXLSParser(); String proposalCode; String proposalNumber; String proposalName; String uploadedFileName; String realXLSPath; if (request != null) { proposalCode = (String) request.getSession().getAttribute(Constants.PROPOSAL_CODE); proposalNumber = String.valueOf(request.getSession().getAttribute(Constants.PROPOSAL_NUMBER)); proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = form.getRequestFile().getFileName(); String fileName = proposalName + "_" + uploadedFileName; realXLSPath = request.getRealPath("\\tmp\\") + "\\" + fileName; FormFile f = form.getRequestFile(); InputStream in = f.getInputStream(); File outputFile = new File(realXLSPath); if (outputFile.exists()) outputFile.delete(); FileOutputStream out = new FileOutputStream(outputFile); while (in.available() != 0) { out.write(in.read()); out.flush(); } out.flush(); out.close(); } else { proposalCode = "ehtpx"; proposalNumber = "1"; proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = "ispyb-template41.xls"; realXLSPath = "D:\\" + uploadedFileName; } FileInputStream inFile = new FileInputStream(realXLSPath); parser.retrieveShippingId(realXLSPath); shippingId = parser.getShippingId(); String requestShippingId = form.getShippingId(); if (requestShippingId != null && !requestShippingId.equals("")) { shippingId = new Integer(requestShippingId); } ClientLogger.getInstance().debug("uploadFile for shippingId " + shippingId); if (shippingId != null) { Log.debug(" ---[uploadFile] Upload for Existing Shipment (DewarTRacking): Deleting Samples from Shipment :"); double nbSamplesContainers = DBAccess_EJB.DeleteAllSamplesAndContainersForShipping(shippingId); if (nbSamplesContainers > 0) parser.getValidationWarnings().add(new XlsUploadException("Shipment contained Samples and/or Containers", "Previous Samples and/or Containers have been deleted and replaced by new ones.")); else parser.getValidationWarnings().add(new XlsUploadException("Shipment contained no Samples and no Containers", "Samples and Containers have been added.")); } Hashtable<String, Hashtable<String, Integer>> listProteinAcronym_SampleName = new Hashtable<String, Hashtable<String, Integer>>(); ProposalFacadeLocal proposal = ProposalFacadeUtil.getLocalHome().create(); ProteinFacadeLocal protein = ProteinFacadeUtil.getLocalHome().create(); CrystalFacadeLocal crystal = CrystalFacadeUtil.getLocalHome().create(); ProposalLightValue targetProposal = (ProposalLightValue) (((ArrayList) proposal.findByCodeAndNumber(proposalCode, new Integer(proposalNumber))).get(0)); ArrayList listProteins = (ArrayList) protein.findByProposalId(targetProposal.getProposalId()); for (int p = 0; p < listProteins.size(); p++) { ProteinValue prot = (ProteinValue) listProteins.get(p); Hashtable<String, Integer> listSampleName = new Hashtable<String, Integer>(); CrystalLightValue listCrystals[] = prot.getCrystals(); for (int c = 0; c < listCrystals.length; c++) { CrystalLightValue _xtal = (CrystalLightValue) listCrystals[c]; CrystalValue xtal = crystal.findByPrimaryKey(_xtal.getPrimaryKey()); BlsampleLightValue listSamples[] = xtal.getBlsamples(); for (int s = 0; s < listSamples.length; s++) { BlsampleLightValue sample = listSamples[s]; listSampleName.put(sample.getName(), sample.getBlSampleId()); } } listProteinAcronym_SampleName.put(prot.getAcronym(), listSampleName); } parser.validate(inFile, listProteinAcronym_SampleName, targetProposal.getProposalId()); List listErrors = parser.getValidationErrors(); List listWarnings = parser.getValidationWarnings(); if (listErrors.size() == 0) { parser.open(realXLSPath); if (parser.getCrystals().size() == 0) { parser.getValidationErrors().add(new XlsUploadException("No crystals have been found", "Empty shipment")); } } Iterator errIt = listErrors.iterator(); while (errIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) errIt.next(); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveErrors(request, errors); } catch (Exception e) { } Iterator warnIt = listWarnings.iterator(); while (warnIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) warnIt.next(); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveMessages(request, messages); } catch (Exception e) { } if (listErrors.size() > 0) { resetCounts(shippingId); return mapping.findForward("submitPocketSampleInformationPage"); } if (listWarnings.size() > 0) returnPage = "submitPocketSampleInformationPage"; String crystalDetailsXML; XtalDetails xtalDetailsWebService = new XtalDetails(); CrystalDetailsBuilder cDE = new CrystalDetailsBuilder(); CrystalDetailsElement cd = cDE.createCrystalDetailsElement(proposalName, parser.getCrystals()); cDE.validateJAXBObject(cd); crystalDetailsXML = cDE.marshallJaxBObjToString(cd); xtalDetailsWebService.submitCrystalDetails(crystalDetailsXML); String diffractionPlan; DiffractionPlan diffractionPlanWebService = new DiffractionPlan(); DiffractionPlanBuilder dPB = new DiffractionPlanBuilder(); Iterator it = parser.getDiffractionPlans().iterator(); while (it.hasNext()) { DiffractionPlanElement dpe = (DiffractionPlanElement) it.next(); dpe.setProjectUUID(proposalName); diffractionPlan = dPB.marshallJaxBObjToString(dpe); diffractionPlanWebService.submitDiffractionPlan(diffractionPlan); } String crystalShipping; Shipping shippingWebService = new Shipping(); CrystalShippingBuilder cSB = new CrystalShippingBuilder(); Person person = cSB.createPerson("XLS Upload", null, "ISPyB", null, null, "ISPyB", null, "ispyb@esrf.fr", "0000", "0000", null, null); Laboratory laboratory = cSB.createLaboratory("Generic Laboratory", "ISPyB Lab", "Sandwich", "Somewhere", "UK", "ISPyB", "ispyb.esrf.fr", person); DeliveryAgent deliveryAgent = parser.getDeliveryAgent(); CrystalShipping cs = cSB.createCrystalShipping(proposalName, laboratory, deliveryAgent, parser.getDewars()); String shippingName; shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xls")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xls") : 0); if (shippingName.equalsIgnoreCase("")) shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xlt")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xlt") : 0); cs.setName(shippingName); crystalShipping = cSB.marshallJaxBObjToString(cs); shippingWebService.submitCrystalShipping(crystalShipping, (ArrayList) parser.getDiffractionPlans(), shippingId); ServerLogger.Log4Stat("XLS_UPLOAD", proposalName, uploadedFileName); } catch (XlsUploadException e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.getMessage())); ClientLogger.getInstance().error(e.toString()); saveErrors(request, errors); return mapping.findForward("error"); } catch (Exception e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString())); ClientLogger.getInstance().error(e.toString()); e.printStackTrace(); saveErrors(request, errors); return mapping.findForward("error"); } setCounts(shippingId); return mapping.findForward(returnPage); }
00
Code Sample 1: public static void copy(File sourceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public static ArrayList<String> remoteCall(Map<String, String> dataDict) { ArrayList<String> result = new ArrayList<String>(); String encodedData = ""; for (String key : dataDict.keySet()) { String encodedSegment = ""; String value = dataDict.get(key); if (value == null) continue; try { encodedSegment = key + "=" + URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (encodedData.length() > 0) { encodedData += "&"; } encodedData += encodedSegment; } try { URL url = new URL(baseURL + encodedData); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { result.add(line); System.out.println("GOT: " + line); } reader.close(); result.remove(0); if (result.size() != 0) { if (!result.get(result.size() - 1).equals("DONE")) { result.clear(); } else { result.remove(result.size() - 1); } } } catch (MalformedURLException e) { } catch (IOException e) { } return result; }
00
Code Sample 1: public static String digest(String ha1, String ha2, String nonce) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(ha1, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(nonce, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(ha2, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } } Code Sample 2: public void invoke(InputStream is) throws AgentException { try { addHeader("Content-Type", "application/zip"); addHeader("Content-Length", String.valueOf(is.available())); connection.setDoOutput(true); connection.connect(); OutputStream os = connection.getOutputStream(); boolean success = false; try { IOUtils.copy(is, os); success = true; } finally { try { os.flush(); os.close(); } catch (IOException x) { if (success) throw x; } } connection.disconnect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new AgentException("Failed to execute REST call at " + connection.getURL() + ": " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (ConnectException e) { throw new AgentException("Failed to connect to beehive at " + connection.getURL()); } catch (IOException e) { throw new AgentException("Failed to connect to beehive", e); } }
11
Code Sample 1: public String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public static boolean checkEncryptedPassword(String md5key, String passwordAccount, String encryptedPassword, int passwdenc) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance(Constants.ALGORITHM); switch(passwdenc) { case 1: md.update((md5key + encryptedPassword).getBytes("8859_1")); return md.digest().equals(passwordAccount.getBytes("8859_1")); case 2: md.update((encryptedPassword + md5key).getBytes("8859_1")); return md.digest().equals(passwordAccount.getBytes("8859_1")); default: return false; } }
11
Code Sample 1: private void updateUser(AddEditUserForm addform, HttpServletRequest request) throws Exception { Session hbsession = HibernateUtil.currentSession(); try { Transaction tx = hbsession.beginTransaction(); NvUsers user = (NvUsers) hbsession.load(NvUsers.class, addform.getLogin()); if (!addform.getPassword().equalsIgnoreCase("")) { MessageDigest md = (MessageDigest) MessageDigest.getInstance("MD5").clone(); md.update(addform.getPassword().getBytes("UTF-8")); byte[] pd = md.digest(); StringBuffer app = new StringBuffer(); for (int i = 0; i < pd.length; i++) { String s2 = Integer.toHexString(pd[i] & 0xFF); app.append((s2.length() == 1) ? "0" + s2 : s2); } user.setPassword(app.toString()); } ActionErrors errors = new ActionErrors(); HashMap cAttrs = addform.getCustomAttrs(); Query q1 = hbsession.createQuery("from org.nodevision.portal.hibernate.om.NvCustomAttrs as a"); Iterator attrs = q1.iterate(); HashMap attrInfos = new HashMap(); while (attrs.hasNext()) { NvCustomAttrs element = (NvCustomAttrs) attrs.next(); attrInfos.put(element.getAttrName(), element.getAttrType()); NvCustomValuesId id = new NvCustomValuesId(); id.setNvUsers(user); NvCustomValues value = new NvCustomValues(); id.setNvCustomAttrs(element); value.setId(id); if (element.getAttrType().equalsIgnoreCase("String")) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream serializer = new ObjectOutputStream(bout); serializer.writeObject(cAttrs.get(element.getAttrName()).toString()); value.setAttrValue(Hibernate.createBlob(bout.toByteArray())); } else if (element.getAttrType().equalsIgnoreCase("Boolean")) { Boolean valueBoolean = Boolean.FALSE; if (cAttrs.get(element.getAttrName()) != null) { valueBoolean = Boolean.TRUE; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream serializer = new ObjectOutputStream(bout); serializer.writeObject(valueBoolean); value.setAttrValue(Hibernate.createBlob(bout.toByteArray())); } else if (element.getAttrType().equalsIgnoreCase("Date")) { Date date = new Date(0); if (!cAttrs.get(element.getAttrName()).toString().equalsIgnoreCase("")) { String bdate = cAttrs.get(element.getAttrName()).toString(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); date = df.parse(bdate); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream serializer = new ObjectOutputStream(bout); serializer.writeObject(date); value.setAttrValue(Hibernate.createBlob(bout.toByteArray())); } hbsession.saveOrUpdate(value); hbsession.flush(); } String bdate = addform.getUser_bdate(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); Date parsedDate = df.parse(bdate); user.setTimezone(addform.getTimezone()); user.setLocale(addform.getLocale()); user.setBdate(new BigDecimal(parsedDate.getTime())); user.setGender(addform.getUser_gender()); user.setEmployer(addform.getEmployer()); user.setDepartment(addform.getDepartment()); user.setJobtitle(addform.getJobtitle()); user.setNamePrefix(addform.getName_prefix()); user.setNameGiven(addform.getName_given()); user.setNameFamily(addform.getName_famliy()); user.setNameMiddle(addform.getName_middle()); user.setNameSuffix(addform.getName_suffix()); user.setHomeName(addform.getHome_name()); user.setHomeStreet(addform.getHome_street()); user.setHomeStateprov(addform.getHome_stateprov()); user.setHomePostalcode(addform.getHome_postalcode().equalsIgnoreCase("") ? new Integer(0) : new Integer(addform.getHome_postalcode())); user.setHomeOrganization(addform.getHome_organization_name()); user.setHomeCountry(addform.getHome_country()); user.setHomeCity(addform.getHome_city()); user.setHomePhoneIntcode((addform.getHome_phone_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_intcode())); user.setHomePhoneLoccode((addform.getHome_phone_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_loccode())); user.setHomePhoneNumber((addform.getHome_phone_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_number())); user.setHomePhoneExt((addform.getHome_phone_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_ext())); user.setHomePhoneComment(addform.getHome_phone_commment()); user.setHomeFaxIntcode((addform.getHome_fax_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_intcode())); user.setHomeFaxLoccode((addform.getHome_fax_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_loccode())); user.setHomeFaxNumber((addform.getHome_fax_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_number())); user.setHomeFaxExt((addform.getHome_fax_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_ext())); user.setHomeFaxComment(addform.getHome_fax_commment()); user.setHomeMobileIntcode((addform.getHome_mobile_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_intcode())); user.setHomeMobileLoccode((addform.getHome_mobile_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_loccode())); user.setHomeMobileNumber((addform.getHome_mobile_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_number())); user.setHomeMobileExt((addform.getHome_mobile_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_ext())); user.setHomeMobileComment(addform.getHome_mobile_commment()); user.setHomePagerIntcode((addform.getHome_pager_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_intcode())); user.setHomePagerLoccode((addform.getHome_pager_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_loccode())); user.setHomePagerNumber((addform.getHome_pager_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_number())); user.setHomePagerExt((addform.getHome_pager_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_ext())); user.setHomePagerComment(addform.getHome_pager_commment()); user.setHomeUri(addform.getHome_uri()); user.setHomeEmail(addform.getHome_email()); user.setBusinessName(addform.getBusiness_name()); user.setBusinessStreet(addform.getBusiness_street()); user.setBusinessStateprov(addform.getBusiness_stateprov()); user.setBusinessPostalcode((addform.getBusiness_postalcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_postalcode())); user.setBusinessOrganization(addform.getBusiness_organization_name()); user.setBusinessCountry(addform.getBusiness_country()); user.setBusinessCity(addform.getBusiness_city()); user.setBusinessPhoneIntcode((addform.getBusiness_phone_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_intcode())); user.setBusinessPhoneLoccode((addform.getBusiness_phone_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_loccode())); user.setBusinessPhoneNumber((addform.getBusiness_phone_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_number())); user.setBusinessPhoneExt((addform.getBusiness_phone_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_ext())); user.setBusinessPhoneComment(addform.getBusiness_phone_commment()); user.setBusinessFaxIntcode((addform.getBusiness_fax_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_intcode())); user.setBusinessFaxLoccode((addform.getBusiness_fax_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_loccode())); user.setBusinessFaxNumber((addform.getBusiness_fax_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_number())); user.setBusinessFaxExt((addform.getBusiness_fax_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_ext())); user.setBusinessFaxComment(addform.getBusiness_fax_commment()); user.setBusinessMobileIntcode((addform.getBusiness_mobile_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_intcode())); user.setBusinessMobileLoccode((addform.getBusiness_mobile_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_loccode())); user.setBusinessMobileNumber((addform.getBusiness_mobile_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_number())); user.setBusinessMobileExt((addform.getBusiness_mobile_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_ext())); user.setBusinessMobileComment(addform.getBusiness_mobile_commment()); user.setBusinessPagerIntcode((addform.getBusiness_pager_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_intcode())); user.setBusinessPagerLoccode((addform.getBusiness_pager_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_loccode())); user.setBusinessPagerNumber((addform.getBusiness_pager_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_number())); user.setBusinessPagerExt((addform.getBusiness_pager_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_ext())); user.setBusinessPagerComment(addform.getBusiness_pager_commment()); user.setBusinessUri(addform.getBusiness_uri()); user.setBusinessEmail(addform.getBusiness_email()); String hqlDelete = "delete org.nodevision.portal.hibernate.om.NvUserRoles where login = :login"; int deletedEntities = hbsession.createQuery(hqlDelete).setString("login", user.getLogin()).executeUpdate(); String[] selectedGroups = addform.getSelectedGroups(); Set newGroups = new HashSet(); for (int i = 0; i < selectedGroups.length; i++) { NvUserRolesId userroles = new NvUserRolesId(); userroles.setNvUsers(user); userroles.setNvRoles((NvRoles) hbsession.load(NvRoles.class, selectedGroups[i])); NvUserRoles newRole = new NvUserRoles(); newRole.setId(userroles); newGroups.add(newRole); } user.setSetOfNvUserRoles(newGroups); hbsession.update(user); hbsession.flush(); if (!hbsession.connection().getAutoCommit()) { tx.commit(); } } finally { HibernateUtil.closeSession(); } } Code Sample 2: private static MyCookieData parseCookie(Cookie cookie) throws CookieException { String value = cookie.getValue(); System.out.println("original cookie: " + value); value = value.replace("%3A", ":"); value = value.replace("%40", "@"); System.out.println("cookie after replacement: " + value); String[] parts = value.split(":"); if (parts.length < 4) throw new CookieException("only " + parts.length + " parts in the cookie! " + value); String email = parts[0]; String nickname = parts[1]; boolean admin = Boolean.getBoolean(parts[2].toLowerCase()); String hsh = parts[3]; boolean valid_cookie = true; String cookie_secret = System.getProperty("COOKIE_SECRET"); if (cookie_secret == "") throw new CookieException("cookie secret is not set"); if (email.equals("")) { System.out.println("email is empty!"); nickname = ""; admin = false; } else { try { MessageDigest sha = MessageDigest.getInstance("SHA"); sha.update((email + nickname + admin + cookie_secret).getBytes()); StringBuilder builder = new StringBuilder(); for (byte b : sha.digest()) { byte tmphigh = (byte) (b >> 4); tmphigh = (byte) (tmphigh & 0xf); builder.append(hextab.charAt(tmphigh)); byte tmplow = (byte) (b & 0xf); builder.append(hextab.charAt(tmplow)); } System.out.println(); String vhsh = builder.toString(); if (!vhsh.equals(hsh)) { System.out.println("hash not same!"); System.out.println("hash passed in: " + hsh); System.out.println("hash generated: " + vhsh); valid_cookie = false; } else System.out.println("cookie match!"); } catch (NoSuchAlgorithmException ex) { } } return new MyCookieData(email, admin, nickname, valid_cookie); }
11
Code Sample 1: public static boolean copyFileToDir(File inputFile, File outputDir) { try { String outputFileName = inputFile.getName(); int index = 1; while (existFileInDir(outputFileName, outputDir)) { outputFileName = index + inputFile.getName(); index++; } String directory = getDirectoryWithSlash(outputDir.getAbsolutePath()); File outputFile = new File(directory + outputFileName); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { return false; } return true; } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private void getRandomGUID(boolean secure) throws NoSuchAlgorithmException { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); throw 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: 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(); } }
11
Code Sample 1: public static void main(String[] args) { if (args.length < 2) { System.out.println(" *** DDL (creates) and DML (inserts) script importer from DB ***"); System.out.println(" You must specify name of the file with script importing data"); System.out.println(" Fisrt rows of this file must be:"); System.out.println(" 1) JDBC driver class for your DBMS"); System.out.println(" 2) URL for your database instance"); System.out.println(" 3) user in that database (with sufficient priviliges)"); System.out.println(" 4) password of that user"); System.out.println(" Next rows can have:"); System.out.println(" '}' before table to create,"); System.out.println(" '{' before schema to create tables in,"); System.out.println(" ')' before table to insert into,"); System.out.println(" '(' before schema to insert into tables in."); System.out.println(" '!' before row means that it is a comment."); System.out.println(" If some exception is occured, all script is rolled back."); System.out.println(" 2nd command line argument is name of output file;"); System.out.println(" if its extension is *.sql, its format is standard SQL"); System.out.println(" otherwize format is short one, understanded by SQLScript tool"); System.out.println(" Connection information remains unchanged in the last format"); System.out.println(" but in the first one it takes form 'connect user/password@URL'"); System.out.println(" where URL can be formed with different rools for different DBMSs"); System.out.println(" If file (with short format header) already exists and you specify"); System.out.println(" 3rd command line argument -db, we generate objects in the database"); System.out.println(" (known from the file header; must differ from 1st DB) but not in file"); System.out.println(" Note: when importing to a file of short format, line separators"); System.out.println(" in VARCHARS will be lost; LOBs will be empty for any file"); System.exit(0); } try { String[] info = new String[4]; BufferedReader reader = new BufferedReader(new FileReader(new File(args[0]))); Writer writer = null; Connection outConnection = null; try { for (int i = 0; i < info.length; i++) info[i] = reader.readLine(); try { Class.forName(info[0]); Connection connection = DriverManager.getConnection(info[1], info[2], info[3]); int format = args[1].toLowerCase().endsWith("sql") ? SQL_FORMAT : SHORT_FORMAT; File file = new File(args[1]); if (format == SHORT_FORMAT) { if (file.exists() && args.length > 2 && args[2].equalsIgnoreCase("-db")) { String[] outInfo = new String[info.length]; BufferedReader outReader = new BufferedReader(new FileReader(file)); for (int i = 0; i < outInfo.length; i++) outInfo[i] = reader.readLine(); outReader.close(); if (!(outInfo[1].equals(info[1]) && outInfo[2].equals(info[2]))) { Class.forName(info[0]); outConnection = DriverManager.getConnection(outInfo[1], outInfo[2], outInfo[3]); format = SQL_FORMAT; } } } if (outConnection == null) writer = new BufferedWriter(new FileWriter(file)); SQLImporter script = new SQLImporter(outConnection, connection); script.setFormat(format); if (format == SQL_FORMAT) { writer.write("connect " + info[2] + "/" + info[3] + "@" + script.getDatabaseURL(info[1]) + script.statementTerminator); } else { for (int i = 0; i < info.length; i++) writer.write(info[i] + lineSep); writer.write(lineSep); } try { System.out.println(script.executeScript(reader, writer) + " operations with tables has been generated during import"); } catch (SQLException e4) { reader.close(); if (writer != null) writer.close(); else outConnection.close(); System.out.println(" Script generation error: " + e4); } connection.close(); } catch (Exception e3) { reader.close(); if (writer != null) writer.close(); System.out.println(" Connection error: " + e3); } } catch (IOException e2) { System.out.println("Error in file " + args[0]); } } catch (FileNotFoundException e1) { System.out.println("File " + args[0] + " not found"); } } Code Sample 2: public void merge(VMImage image, VMSnapShot another) throws VMException { if (path == null || another.getPath() == null) throw new VMException("EmuVMSnapShot is NULL!"); logging.debug(LOG_NAME, "merge images " + path + " and " + another.getPath()); File target = new File(path); File src = new File(another.getPath()); if (target.isDirectory() || src.isDirectory()) return; try { FileInputStream in = new FileInputStream(another.getPath()); FileChannel inChannel = in.getChannel(); FileOutputStream out = new FileOutputStream(path, true); FileChannel outChannel = out.getChannel(); outChannel.transferFrom(inChannel, 0, inChannel.size()); outChannel.close(); inChannel.close(); } catch (IOException e) { throw new VMException(e); } }
00
Code Sample 1: private String readJsonString() { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(SERVER_URL); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(TAG, "Failed to download file"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } Code Sample 2: public static void main(String[] args) throws IOException { FileOutputStream f = new FileOutputStream("test.zip"); CheckedOutputStream csum = new CheckedOutputStream(f, new CRC32()); ZipOutputStream zos = new ZipOutputStream(csum); BufferedOutputStream out = new BufferedOutputStream(zos); zos.setComment("A test of Java Zipping"); for (String arg : args) { print("Writing file " + arg); BufferedReader in = new BufferedReader(new FileReader(arg)); zos.putNextEntry(new ZipEntry(arg)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.flush(); } out.close(); print("Checksum: " + csum.getChecksum().getValue()); print("Reading file"); FileInputStream fi = new FileInputStream("test.zip"); CheckedInputStream csumi = new CheckedInputStream(fi, new CRC32()); ZipInputStream in2 = new ZipInputStream(csumi); BufferedInputStream bis = new BufferedInputStream(in2); ZipEntry ze; while ((ze = in2.getNextEntry()) != null) { print("Reading file " + ze); int x; while ((x = bis.read()) != -1) { System.out.write(x); } if (args.length == 1) { print("Checksum: " + csumi.getChecksum().getValue()); } bis.close(); } }
00
Code Sample 1: protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String zOntoJsonApiUrl = getInitParameter("zOntoJsonApiServletUrl"); URL url = new URL(zOntoJsonApiUrl + "?" + req.getQueryString()); resp.setContentType("text/html"); InputStreamReader bf = new InputStreamReader(url.openStream()); BufferedReader bbf = new BufferedReader(bf); String response = ""; String line = bbf.readLine(); PrintWriter out = resp.getWriter(); while (line != null) { response += line; line = bbf.readLine(); } out.print(response); out.close(); } Code Sample 2: @Test public void testRegister() { try { String username = "muchu"; String password = "123"; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); String passwordMd5 = new String(md5.digest()); LogService logServiceMock = EasyMock.createMock(LogService.class); DbService dbServiceMock = EasyMock.createMock(DbService.class); userServ.setDbServ(dbServiceMock); userServ.setLogger(logServiceMock); IFeelerUser user = new FeelerUserImpl(); user.setUsername(username); user.setPassword(passwordMd5); logServiceMock.info(DbUserServiceImpl.class, ">>>rigister " + username + "<<<"); EasyMock.expect(dbServiceMock.queryFeelerUser(username)).andReturn(null); dbServiceMock.addFeelerUser(username, passwordMd5); logServiceMock.info(DbUserServiceImpl.class, ">>>identification " + username + "<<<"); EasyMock.expect(dbServiceMock.queryFeelerUser(username)).andReturn(user); EasyMock.replay(dbServiceMock, logServiceMock); Assert.assertTrue(userServ.register(username, password)); EasyMock.verify(dbServiceMock, logServiceMock); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
11
Code Sample 1: 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(); } Code Sample 2: public static void main(String[] a) { ArrayList<String> allFilesToBeCopied = new ArrayList<String>(); new File(outputDir).mkdirs(); try { FileReader fis = new FileReader(completeFileWithDirToCathFileList); BufferedReader bis = new BufferedReader(fis); String line = ""; String currentCombo = ""; while ((line = bis.readLine()) != null) { String[] allEntries = line.split("\\s+"); String fileName = allEntries[0]; String thisCombo = allEntries[1] + allEntries[2] + allEntries[3] + allEntries[4]; if (currentCombo.equals(thisCombo)) { } else { System.out.println("merke: " + fileName); allFilesToBeCopied.add(fileName); currentCombo = thisCombo; } } System.out.println(allFilesToBeCopied.size()); for (String file : allFilesToBeCopied) { try { FileChannel srcChannel = new FileInputStream(CathDir + file).getChannel(); FileChannel dstChannel = new FileOutputStream(outputDir + file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public void processExplicitSchemaAndWSDL(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { HashMap services = configContext.getAxisConfiguration().getServices(); String filePart = req.getRequestURL().toString(); String schema = filePart.substring(filePart.lastIndexOf("/") + 1, filePart.length()); if ((services != null) && !services.isEmpty()) { Iterator i = services.values().iterator(); while (i.hasNext()) { AxisService service = (AxisService) i.next(); InputStream stream = service.getClassLoader().getResourceAsStream("META-INF/" + schema); if (stream != null) { OutputStream out = res.getOutputStream(); res.setContentType("text/xml"); IOUtils.copy(stream, out, true); return; } } } } Code Sample 2: public void checkFilesAndCopyValid(String filename) { downloadResults(); loadResults(); File tmpFolderF = new File(tmpFolder); deleteFileFromTMPFolder(tmpFolderF); ZipReader zr = new ZipReader(); zr.UnzipFile(filename); try { LogManager.getInstance().log("Ov��uji odevzdan� soubory a kop�ruji validovan�:"); LogManager.getInstance().log(""); JAXBElement<?> element = ElementJAXB.getJAXBElement(); Ppa1VysledkyCviceniType pvct = (Ppa1VysledkyCviceniType) element.getValue(); File zipFolder = new File(tmpFolder).listFiles()[0].listFiles()[0].listFiles()[0]; File[] zipFolderList = zipFolder.listFiles(); for (File studentDirectory : zipFolderList) { if (studentDirectory.isDirectory()) { String osobniCisloZeSlozky = studentDirectory.getName().split("-")[0]; LogManager.getInstance().changeLog("Prov��ov�n� soubor� studenta s ��slem: " + osobniCisloZeSlozky); List<StudentType> students = (List<StudentType>) pvct.getStudent(); for (StudentType student : students) { if (student.getOsobniCislo().equals(osobniCisloZeSlozky)) { int pzp = student.getDomaciUlohy().getPosledniZpracovanyPokus().getCislo().intValue(); DomaciUlohyType dut = student.getDomaciUlohy(); ChybneOdevzdaneType chot = dut.getChybneOdevzdane(); ObjectFactory of = new ObjectFactory(); File[] pokusyDirectories = studentDirectory.listFiles(); NodeList souboryNL = result.getElementsByTagName("soubor"); int start = souboryNL.getLength() - 1; boolean samostatnaPrace = false; for (int i = (pokusyDirectories.length - 1); i >= 0; i--) { if ((pokusyDirectories[i].isDirectory()) && (pzp < Integer.parseInt(pokusyDirectories[i].getName().split("_")[1].trim()))) { File testedFile = pokusyDirectories[i].listFiles()[0]; if ((testedFile.exists()) && (testedFile.isFile())) { String[] partsOfFilename = testedFile.getName().split("_"); String osobniCisloZeSouboru = "", priponaSouboru = ""; String[] posledniCastSouboru = null; if (partsOfFilename.length == 4) { posledniCastSouboru = partsOfFilename[3].split("[.]"); osobniCisloZeSouboru = posledniCastSouboru[0]; if (posledniCastSouboru.length <= 1) priponaSouboru = ""; else priponaSouboru = posledniCastSouboru[1]; } String samostatnaPraceNazev = Konfigurace.getInstance().getSamostatnaPraceNazev(); List<SouborType> lst = chot.getSoubor(); if (testedFile.getName().startsWith(samostatnaPraceNazev)) { samostatnaPrace = true; } else { samostatnaPrace = false; if (partsOfFilename.length != 4) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� struktura jm�na souboru."); lst.add(st); continue; } else if (!testedFile.getName().startsWith("Ppa1_cv")) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� za��tek jm�na souboru."); lst.add(st); continue; } else if (!priponaSouboru.equals("java")) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� p��pona souboru."); lst.add(st); continue; } else if (!osobniCisloZeSouboru.equals(osobniCisloZeSlozky)) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Nesouhlas� osobn� ��sla."); lst.add(st); continue; } else if (partsOfFilename[3].split("[.]").length > 2) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("V�ce p��pon souboru."); lst.add(st); continue; } else { long cisloCviceni, cisloUlohy; try { if (partsOfFilename[1].length() == 4) { String cisloS = partsOfFilename[1].substring(2); long cisloL = Long.parseLong(cisloS); cisloCviceni = cisloL; } else { throw new NumberFormatException(); } } catch (NumberFormatException e) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Chyb� (nebo je chybn�) ��slo cvi�en�"); lst.add(st); continue; } try { if (partsOfFilename[2].length() > 0) { String cisloS = partsOfFilename[2]; long cisloL = Long.parseLong(cisloS); cisloUlohy = cisloL; } else { throw new NumberFormatException(); } } catch (NumberFormatException e) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Chyb� (nebo je chybn�) ��slo �lohy"); lst.add(st); continue; } CislaUloh ci = new CislaUloh(); List<long[]> cviceni = ci.getSeznamCviceni(); boolean nalezenoCv = false, nalezenaUl = false; for (long[] c : cviceni) { if (c[0] == cisloCviceni) { for (int j = 1; j < c.length; j++) { if (c[j] == cisloUlohy) { nalezenaUl = true; break; } } nalezenoCv = true; break; } } if (!nalezenoCv) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Neplatn� ��slo cvi�en�"); lst.add(st); continue; } if (!nalezenaUl) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Neplatn� ��slo �lohy"); lst.add(st); continue; } } } } Calendar dateFromZipFile = null; File zipFile = new File(filename); if (zipFile.exists()) { String[] s = zipFile.getName().split("_"); if (s.length >= 3) { String[] date = s[1].split("-"), time = s[2].split("-"); dateFromZipFile = new GregorianCalendar(); dateFromZipFile.set(Integer.parseInt(date[0]), Integer.parseInt(date[1]) - 1, Integer.parseInt(date[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1]), 0); } } boolean shodaJmenaSouboru = false; String vysledekValidaceSouboru = ""; for (int j = start; j >= 0; j--) { NodeList vlastnostiSouboruNL = souboryNL.item(j).getChildNodes(); for (int k = 0; k < vlastnostiSouboruNL.getLength(); k++) { if (vlastnostiSouboruNL.item(k).getNodeName().equals("cas")) { String[] obsahElementuCas = vlastnostiSouboruNL.item(k).getTextContent().split(" "); String[] datumZElementu = obsahElementuCas[0].split("-"), casZElementu = obsahElementuCas[1].split("-"); Calendar datumACasZElementu = new GregorianCalendar(); datumACasZElementu.set(Integer.parseInt(datumZElementu[0]), Integer.parseInt(datumZElementu[1]) - 1, Integer.parseInt(datumZElementu[2]), Integer.parseInt(casZElementu[0]), Integer.parseInt(casZElementu[1]), Integer.parseInt(casZElementu[2])); if ((dateFromZipFile != null) && (datumACasZElementu.compareTo(dateFromZipFile) > 0)) { shodaJmenaSouboru = false; break; } } if (vlastnostiSouboruNL.item(k).getNodeName().equals("nazev")) { shodaJmenaSouboru = vlastnostiSouboruNL.item(k).getTextContent().equals(testedFile.getName()); } if (vlastnostiSouboruNL.item(k).getNodeName().equals("vysledek")) { vysledekValidaceSouboru = vlastnostiSouboruNL.item(k).getTextContent(); } } if (shodaJmenaSouboru) { start = --j; break; } } if (shodaJmenaSouboru && !samostatnaPrace) { boolean odevzdanoVcas = false; String cisloCviceniS = testedFile.getName().split("_")[1].substring(2); int cisloCviceniI = Integer.parseInt(cisloCviceniS); String cisloUlohyS = testedFile.getName().split("_")[2]; int cisloUlohyI = Integer.parseInt(cisloUlohyS); List<CviceniType> lct = student.getDomaciUlohy().getCviceni(); for (CviceniType ct : lct) { if (ct.getCislo().intValue() == cisloCviceniI) { MezniTerminOdevzdaniVcasType mtovt = ct.getMezniTerminOdevzdaniVcas(); Calendar mtovGC = new GregorianCalendar(); mtovGC.set(mtovt.getDatum().getYear(), mtovt.getDatum().getMonth() - 1, mtovt.getDatum().getDay(), 23, 59, 59); Calendar fileTimeStamp = new GregorianCalendar(); fileTimeStamp.setTimeInMillis(testedFile.lastModified()); String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-"); String[] casSouboru = String.format("%tT", fileTimeStamp).split(":"); XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); if (fileTimeStamp.compareTo(mtovGC) <= 0) odevzdanoVcas = true; else odevzdanoVcas = false; List<UlohaType> lut = ct.getUloha(); for (UlohaType ut : lut) { if (ut.getCislo().intValue() == cisloUlohyI) { List<OdevzdanoType> lot = ut.getOdevzdano(); OdevzdanoType ot = of.createOdevzdanoType(); ot.setDatum(xmlGCDate); ot.setCas(xmlGCTime); OdevzdanoVcasType ovt = of.createOdevzdanoVcasType(); ovt.setVysledek(odevzdanoVcas); ValidatorType vt = of.createValidatorType(); vt.setVysledek(vysledekValidaceSouboru.equals("true")); ot.setOdevzdanoVcas(ovt); ot.setValidator(vt); lot.add(ot); if (vt.isVysledek()) { String test = String.format("%s%s%02d", validovane, File.separator, ct.getCislo().intValue()); if (!(new File(test).exists())) { LogManager.getInstance().log("Nebyla provedena p��prava soubor�. Chyb� slo�ka " + test.substring(Ppa1Cviceni.USER_DIR.length()) + "."); return; } else { copyValidFile(testedFile, ct.getCislo().intValue()); } } break; } } break; } } } else if (shodaJmenaSouboru && samostatnaPrace) { String[] partsOfFilename = testedFile.getName().split("_"); String[] partsOfLastPartOfFilename = partsOfFilename[partsOfFilename.length - 1].split("[.]"); String osobniCisloZeSouboru = partsOfLastPartOfFilename[0]; String priponaZeSouboru = partsOfLastPartOfFilename[partsOfLastPartOfFilename.length - 1]; if ((partsOfLastPartOfFilename.length == 2) && (priponaZeSouboru.equals("java"))) { if (student.getOsobniCislo().equals(osobniCisloZeSouboru)) { Calendar fileTimeStamp = new GregorianCalendar(); fileTimeStamp.setTimeInMillis(testedFile.lastModified()); String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-"); String[] casSouboru = String.format("%tT", fileTimeStamp).split(":"); XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); List<UlozenoType> lut = student.getSamostatnaPrace().getUlozeno(); if (lut.isEmpty()) { File samostatnaPraceNewFile = new File(sp + File.separator + testedFile.getName()); if (samostatnaPraceNewFile.exists()) { samostatnaPraceNewFile.delete(); samostatnaPraceNewFile.createNewFile(); } String EOL = "" + (char) 0x0D + (char) 0x0A; FileReader fr = new FileReader(testedFile); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(samostatnaPraceNewFile); String line; while ((line = br.readLine()) != null) fw.write(line + EOL); br.close(); fw.close(); samostatnaPraceNewFile.setLastModified(testedFile.lastModified()); } UlozenoType ut = of.createUlozenoType(); ut.setDatum(xmlGCDate); ut.setCas(xmlGCTime); lut.add(0, ut); } } } } } PosledniZpracovanyPokusType pzpt = new PosledniZpracovanyPokusType(); String[] slozkaPoslednihoPokusu = pokusyDirectories[pokusyDirectories.length - 1].getName().split("_"); int cisloPokusu = Integer.parseInt(slozkaPoslednihoPokusu[slozkaPoslednihoPokusu.length - 1].trim()); pzpt.setCislo(new BigInteger(String.valueOf(cisloPokusu))); student.getDomaciUlohy().setPosledniZpracovanyPokus(pzpt); break; } } } } ElementJAXB.setJAXBElement(element); LogManager.getInstance().log("Ov��ov�n� a kop�rov�n� odevzdan�ch soubor� dokon�eno."); } catch (FileNotFoundException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } catch (DatatypeConfigurationException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } catch (IOException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } LogManager.getInstance().log("Maz�n� rozbalen�ch soubor� ..."); deleteFileFromTMPFolder(tmpFolderF); LogManager.getInstance().changeLog("Maz�n� rozbalen�ch soubor� ... OK"); }
11
Code Sample 1: private static String scramble(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (byte b : md.digest()) sb.append(Integer.toString(b & 0xFF, 16)); return sb.toString(); } catch (UnsupportedEncodingException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } } Code Sample 2: public static String getMD5(String s) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(s.getBytes()); byte[] result = md5.digest(); StringBuilder hexString = new StringBuilder(); for (int i = 0; i < result.length; i++) { hexString.append(String.format("%02x", 0xFF & result[i])); } return hexString.toString(); }
00
Code Sample 1: public static final void copy(String source, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } } Code Sample 2: public synchronized void downloadTile(TileNumber tn) { try { Bitmap tile = getMapFromSdCache(tn); if (tile == null) { URL url = new URL("http://tile.openstreetmap.org/" + tn.getZoom() + "/" + tn.getX() + "/" + tn.getY() + ".png"); tile = BitmapFactory.decodeStream(url.openStream()); File sdCardPath = Environment.getExternalStorageDirectory(); Log.d(ctx.getResources().getString(open.gps.gopens.R.string.TEST), "Path to SD :: " + sdCardPath.getAbsolutePath()); File dir = new File(sdCardPath + ctx.getResources().getString(open.gps.gopens.R.string.CACHE_PATH) + tn.getZoom() + "/" + tn.getX() + "/"); dir.mkdirs(); File imgFile = new File(dir.getAbsolutePath() + "/" + tn.getY() + ".png"); imgFile.createNewFile(); FileOutputStream fOut = new FileOutputStream(imgFile); tile.compress(Bitmap.CompressFormat.PNG, 100, fOut); } cacheManager.put(tn.toString(), tile); setChanged(); notifyObservers(); Log.d("OBS", "OBS : Notify"); } catch (MalformedURLException e) { Log.e("Error", e.getMessage()); } catch (IOException e) { Log.e("Error", e.getMessage()); } }
11
Code Sample 1: 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(); } } Code Sample 2: private void copyFile(File source, File dest) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
00
Code Sample 1: public void service(TranslationRequest request, TranslationResponse response) { try { Thread.sleep((long) Math.random() * 250); } catch (InterruptedException e1) { } hits.incrementAndGet(); String key = getKey(request); RequestResponse cachedResponse = cache.get(key); if (cachedResponse == null) { response.setEndState(new ResponseStateBean(ResponseCode.ERROR, "response not found for " + key)); return; } response.addHeaders(cachedResponse.getExpectedResponse().getHeaders()); response.setTranslationCount(cachedResponse.getExpectedResponse().getTranslationCount()); response.setFailCount(cachedResponse.getExpectedResponse().getFailCount()); if (cachedResponse.getExpectedResponse().getLastModified() != -1) { response.setLastModified(cachedResponse.getExpectedResponse().getLastModified()); } try { OutputStream output = response.getOutputStream(); InputStream input = cachedResponse.getExpectedResponse().getInputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } catch (IOException e) { response.setEndState(new ResponseStateException(e)); return; } response.setEndState(cachedResponse.getExpectedResponse().getEndState()); } Code Sample 2: private void getViolationsReportByProductOfferIdYearMonthDay() throws IOException { String xmlFile9Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "getViolationsReportByProductOfferIdYearMonthDay.xml"; URL url9; url9 = new URL(bmReportingWSUrl); URLConnection connection9 = url9.openConnection(); HttpURLConnection httpConn9 = (HttpURLConnection) connection9; FileInputStream fin9 = new FileInputStream(xmlFile9Send); ByteArrayOutputStream bout9 = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin9, bout9); fin9.close(); byte[] b9 = bout9.toByteArray(); httpConn9.setRequestProperty("Content-Length", String.valueOf(b9.length)); httpConn9.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn9.setRequestProperty("SOAPAction", soapAction); httpConn9.setRequestMethod("POST"); httpConn9.setDoOutput(true); httpConn9.setDoInput(true); OutputStream out9 = httpConn9.getOutputStream(); out9.write(b9); out9.close(); InputStreamReader isr9 = new InputStreamReader(httpConn9.getInputStream()); BufferedReader in9 = new BufferedReader(isr9); String inputLine9; StringBuffer response9 = new StringBuffer(); while ((inputLine9 = in9.readLine()) != null) { response9.append(inputLine9); } in9.close(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: Business Manager\n" + "Interface Name: getReport\n" + "Operation Name: " + "getViolationsReportByProductOfferIdYearMonthDay\n" + "Input" + "ProductOfferID-1\n" + "PartyID-1\n" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println("--------------------------------"); System.out.println("Response\n" + response9.toString()); }
00
Code Sample 1: public static void BubbleSortDouble1(double[] num) { boolean flag = true; // set flag to true to begin first pass double temp; // holding variable while (flag) { flag = false; // set flag to false awaiting a possible swap for (int j = 0; j < num.length - 1; j++) { if (num[j] > num[j + 1]) // change to > for ascending sort { temp = num[j]; // swap elements num[j] = num[j + 1]; num[j + 1] = temp; flag = true; // shows a swap occurred } } } } Code Sample 2: private List<Intrebare> citesteIntrebari() throws IOException { ArrayList<Intrebare> intrebari = new ArrayList<Intrebare>(); try { URL url = new URL(getCodeBase(), "../intrebari.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader((url.openStream()))); String intrebare; while ((intrebare = reader.readLine()) != null) { Collection<String> raspunsuri = new ArrayList<String>(); Collection<String> predicate = new ArrayList<String>(); String raspuns = ""; while (!"".equals(raspuns = reader.readLine())) { raspunsuri.add(raspuns); predicate.add(reader.readLine()); } Intrebare i = new Intrebare(intrebare, raspunsuri.toArray(new String[raspunsuri.size()]), predicate.toArray(new String[predicate.size()])); intrebari.add(i); } } catch (ArgumentExcetpion e) { e.printStackTrace(); } return intrebari; }
00
Code Sample 1: @Override public void run() { try { File[] inputFiles = new File[this.previousFiles != null ? this.previousFiles.length + 1 : 1]; File copiedInput = new File(this.randomFolder, this.inputFile.getName()); IOUtils.copyFile(this.inputFile, copiedInput); inputFiles[inputFiles.length - 1] = copiedInput; if (previousFiles != null) { for (int i = 0; i < this.previousFiles.length; i++) { File prev = this.previousFiles[i]; File copiedPrev = new File(this.randomFolder, prev.getName()); IOUtils.copyFile(prev, copiedPrev); inputFiles[i] = copiedPrev; } } org.happycomp.radiog.Activator activator = org.happycomp.radiog.Activator.getDefault(); if (this.exportedMP3File != null) { EncodingUtils.encodeToWavAndThenMP3(inputFiles, this.exportedWavFile, this.exportedMP3File, this.deleteOnExit, this.randomFolder, activator.getCommandsMap()); } else { EncodingUtils.encodeToWav(inputFiles, this.exportedWavFile, randomFolder, activator.getCommandsMap()); } if (encodeMonitor != null) { encodeMonitor.setEncodingFinished(true); } } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } Code Sample 2: public MeetingScript getScript(Integer id) { MeetingScript script = null; try { URL url = new URL(SCRIPT_URL + "?script=" + id); ObjectInputStream ois = new ObjectInputStream(url.openStream()); script = (MeetingScript) ois.readObject(); ois.close(); System.out.println("got script"); } catch (Exception e) { e.printStackTrace(); } return script; }
00
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: public static Chunk updateLastSend(Chunk c) throws Exception { DBConnectionManager dbm = null; Connection conn = null; PreparedStatement stmt = null; Chunk ret = null; String SQL = "UPDATE CHUNK SET SENT=? WHERE FILEHASH=? AND STARTOFF=? AND LENGTH=?"; log.debug("update chunk last sent for chunk " + c.getHash() + " startoff " + c.getStartOffset()); try { dbm = DBConnectionManager.getInstance(); conn = dbm.getConnection("satmule"); stmt = conn.prepareStatement(SQL); stmt.setDate(1, new java.sql.Date(c.getLastSend().getTime())); stmt.setString(2, c.getHash()); stmt.setLong(3, c.getStartOffset()); stmt.setLong(4, c.getSize()); stmt.executeUpdate(); conn.commit(); stmt.close(); dbm.freeConnection("satmule", conn); } catch (Exception e) { log.error("Error while updating chunk " + c.getHash() + "offset:" + c.getStartOffset() + "SQL error: " + SQL, e); Exception excep; if (dbm == null) excep = new Exception("Could not obtain pool object DbConnectionManager"); else if (conn == null) excep = new Exception("The Db connection pool could not obtain a database connection"); else { conn.rollback(); excep = new Exception("SQL Error : " + SQL + " error: " + e); dbm.freeConnection("satmule", conn); } throw excep; } return ret; }
11
Code Sample 1: public void print(PrintWriter out) { out.println("<?xml version=\"1.0\"?>\n" + "<?xml-stylesheet type=\"text/xsl\" href=\"http://www.urbigene.com/foaf/foaf2html.xsl\" ?>\n" + "<rdf:RDF \n" + "xml:lang=\"en\" \n" + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" \n" + "xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\" \n" + "xmlns=\"http://xmlns.com/foaf/0.1/\" \n" + "xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" \n" + "xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"); out.println("<!-- generated with SciFoaf http://www.urbigene.com/foaf -->"); if (this.mainAuthor == null && this.authors.getAuthorCount() > 0) { this.mainAuthor = this.authors.getAuthorAt(0); } if (this.mainAuthor != null) { out.println("<foaf:PersonalProfileDocument rdf:about=\"\">\n" + "\t<foaf:primaryTopic rdf:nodeID=\"" + this.mainAuthor.getID() + "\"/>\n" + "\t<foaf:maker rdf:resource=\"mailto:plindenbaum@yahoo.fr\"/>\n" + "\t<dc:title>FOAF for " + XMLUtilities.escape(this.mainAuthor.getName()) + "</dc:title>\n" + "\t<dc:description>\n" + "\tFriend-of-a-Friend description for " + XMLUtilities.escape(this.mainAuthor.getName()) + "\n" + "\t</dc:description>\n" + "</foaf:PersonalProfileDocument>\n\n"); } for (int i = 0; i < this.laboratories.size(); ++i) { Laboratory lab = this.laboratories.getLabAt(i); out.println("<foaf:Group rdf:ID=\"laboratory_ID" + i + "\" >"); out.println("\t<foaf:name>" + XMLUtilities.escape(lab.toString()) + "</foaf:name>"); for (int j = 0; j < lab.getAuthorCount(); ++j) { out.println("\t<foaf:member rdf:resource=\"#" + lab.getAuthorAt(j).getID() + "\" />"); } out.println("</foaf:Group>\n\n"); } for (int i = 0; i < this.authors.size(); ++i) { Author author = authors.getAuthorAt(i); out.println("<foaf:Person rdf:ID=\"" + xmlName(author.getID()) + "\" >"); out.println("\t<foaf:name>" + xmlName(author.getName()) + "</foaf:name>"); out.println("\t<foaf:title>Dr</foaf:title>"); out.println("\t<foaf:family_name>" + xmlName(author.getLastName()) + "</foaf:family_name>"); if (author.getForeName() != null && author.getForeName().length() > 2) { out.println("\t<foaf:firstName>" + xmlName(author.getForeName()) + "</foaf:firstName>"); } String prop = author.getProperty("foaf:mbox"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (tokens[j].trim().length() == 0) continue; if (tokens[j].equals("mailto:")) continue; if (!tokens[j].startsWith("mailto:")) tokens[j] = "mailto:" + tokens[j]; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(tokens[j].getBytes()); byte[] digest = md.digest(); out.print("\t<foaf:mbox_sha1sum>"); for (int k = 0; k < digest.length; k++) { String hex = Integer.toHexString(digest[k]); if (hex.length() == 1) hex = "0" + hex; hex = hex.substring(hex.length() - 2); out.print(hex); } out.println("</foaf:mbox_sha1sum>"); } catch (Exception err) { out.println("\t<foaf:mbox rdf:resource=\"" + tokens[j] + "\" />"); } } } prop = author.getProperty("foaf:nick"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (tokens[j].trim().length() == 0) continue; out.println("\t<foaf:surname>" + XMLUtilities.escape(tokens[j]) + "</foaf:surname>"); } } prop = author.getProperty("foaf:homepage"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (!tokens[j].trim().startsWith("http://")) continue; if (tokens[j].trim().equals("http://")) continue; out.println("\t<foaf:homepage rdf:resource=\"" + XMLUtilities.escape(tokens[j].trim()) + "\"/>"); } } out.println("\t<foaf:publications rdf:resource=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=pubmed&amp;cmd=Search&amp;itool=pubmed_Abstract&amp;term=" + author.getTerm() + "\"/>"); prop = author.getProperty("foaf:img"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (!tokens[j].trim().startsWith("http://")) continue; if (tokens[j].trim().equals("http://")) continue; out.println("\t<foaf:depiction rdf:resource=\"" + XMLUtilities.escape(tokens[j].trim()) + "\"/>"); } } AuthorList knows = this.whoknowwho.getKnown(author); for (int j = 0; j < knows.size(); ++j) { out.println("\t<foaf:knows rdf:resource=\"#" + xmlName(knows.getAuthorAt(j).getID()) + "\" />"); } Paper publications[] = this.papers.getAuthorPublications(author).toArray(); if (!(publications.length == 0)) { HashSet meshes = new HashSet(); for (int j = 0; j < publications.length; ++j) { meshes.addAll(publications[j].meshTerms); } for (Iterator itermesh = meshes.iterator(); itermesh.hasNext(); ) { MeshTerm meshterm = (MeshTerm) itermesh.next(); out.println("\t<foaf:interest>\n" + "\t\t<rdf:Description rdf:about=\"" + meshterm.getURL() + "\">\n" + "\t\t\t<dc:title>" + XMLUtilities.escape(meshterm.toString()) + "</dc:title>\n" + "\t\t</rdf:Description>\n" + "\t</foaf:interest>"); } } out.println("</foaf:Person>\n\n"); } Paper paperarray[] = this.papers.toArray(); for (int i = 0; i < paperarray.length; ++i) { out.println("<foaf:Document rdf:about=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&amp;db=pubmed&amp;dopt=Abstract&amp;list_uids=" + paperarray[i].getPMID() + "\">"); out.println("<dc:title>" + XMLUtilities.escape(paperarray[i].getTitle()) + "</dc:title>"); for (Iterator iter = paperarray[i].authors.iterator(); iter.hasNext(); ) { Author author = (Author) iter.next(); out.println("<dc:author rdf:resource=\"#" + XMLUtilities.escape(author.getID()) + "\"/>"); } out.println("</foaf:Document>"); } out.println("</rdf:RDF>"); } Code Sample 2: private String getBytes(String in) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(in.getBytes()); byte[] passWordBytes = md5.digest(); String s = "["; for (int i = 0; i < passWordBytes.length; i++) s += passWordBytes[i] + ", "; s = s.substring(0, s.length() - 2); s += "]"; return s; }
00
Code Sample 1: public Savable loadResource(String name, PrimitiveLoader loader) { Savable objeto = null; URL url = ResourceLocator.locateFile(loader.getBaseFolder(), name, loader.getCompiledExtension()); if (url == null) { url = ResourceLocator.locateFile(loader.getBaseFolder(), name, loader.getPrimitiveExtension()); if (url != null) { try { objeto = loader.loadResource(name, url.openStream()); File file = ResourceLocator.replaceExtension(url, loader.getCompiledExtension()); BinaryExporter.getInstance().save(objeto, file); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } } else { try { objeto = BinaryImporter.getInstance().load(url.openStream()); } catch (IOException e) { e.printStackTrace(); } } return objeto; } Code Sample 2: @SuppressWarnings("unchecked") private Map<String, Object> _request(String method, String path, Map<String, Object> body, JSONRecognizer... recognizers) throws IOException, TwinException { String uri = url + path; HttpRequest request; if (body == null) { BasicHttpRequest r = new BasicHttpRequest(method, uri); request = r; } else { BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(method, uri); StringEntity entity; try { entity = new StringEntity(JSON.encode(body), "utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } entity.setContentType("application/json; charset=utf-8"); r.setEntity(entity); request = r; } HttpClient client = getClient(); try { HttpResponse response = client.execute(new HttpHost(url.getHost(), url.getPort()), request); HttpEntity entity = response.getEntity(); if (entity == null) return null; String contentType = entity.getContentType().getValue(); boolean isJson = (contentType != null) && ("application/json".equals(contentType) || contentType.startsWith("application/json;")); String result = null; InputStream in = entity.getContent(); try { Reader r = new InputStreamReader(in, "UTF-8"); StringBuilder sb = new StringBuilder(); char[] buf = new char[256]; int read; while ((read = r.read(buf, 0, buf.length)) >= 0) sb.append(buf, 0, read); r.close(); result = sb.toString(); } finally { try { in.close(); } catch (Exception e) { } } int code = response.getStatusLine().getStatusCode(); if (code >= 400) { if (isJson) { try { throw deserializeException((Map<String, Object>) JSON.decode(result)); } catch (IllegalArgumentException e) { throw TwinError.UnknownError.create("Couldn't parse error response: \n" + result, e); } } if (code == 404) throw TwinError.UnknownCommand.create("Got server response " + code + " for request " + uri); else throw TwinError.UnknownError.create("Got server response " + code + " for request " + uri + "\nBody is " + result); } if (!isJson) throw TwinError.UnknownError.create("Got wrong content type " + contentType + " for request " + uri + "\nBody is " + result); try { return (Map<String, Object>) JSON.decode(result, recognizers); } catch (Exception e) { throw TwinError.UnknownError.create("Malformed JSON result for request " + uri + ": \nBody is " + result, e); } } catch (ClientProtocolException e) { throw new IOException(e); } }
11
Code Sample 1: private void copyFile(File dir, File fileToAdd) { try { byte[] readBuffer = new byte[1024]; File file = new File(dir.getCanonicalPath() + File.separatorChar + fileToAdd.getName()); if (file.createNewFile()) { FileInputStream fis = new FileInputStream(fileToAdd); FileOutputStream fos = new FileOutputStream(file); int bytesRead; do { bytesRead = fis.read(readBuffer); fos.write(readBuffer, 0, bytesRead); } while (bytesRead == 0); fos.flush(); fos.close(); fis.close(); } else { logger.severe("unable to create file:" + file.getAbsolutePath()); } } catch (IOException ioe) { logger.severe("unable to create file:" + ioe); } } Code Sample 2: public BasePolicy(String flaskPath) throws Exception { SWIGTYPE_p_p_policy p_p_pol = apol.new_policy_t_p_p(); if (!flaskPath.endsWith("/")) flaskPath += "/"; File tmpPolConf = File.createTempFile("tmpBasePolicy", ".conf"); BufferedWriter tmpPolFile = new BufferedWriter(new FileWriter(tmpPolConf)); BufferedReader secClassFile = new BufferedReader(new FileReader(flaskPath + "security_classes")); int bufSize = 1024; char[] buffer = new char[bufSize]; int read; while ((read = secClassFile.read(buffer)) > 0) { tmpPolFile.write(buffer, 0, read); } secClassFile.close(); BufferedReader sidsFile = new BufferedReader(new FileReader(flaskPath + "initial_sids")); while ((read = sidsFile.read(buffer)) > 0) { tmpPolFile.write(buffer, 0, read); } sidsFile.close(); BufferedReader axxVecFile = new BufferedReader(new FileReader(flaskPath + "access_vectors")); while ((read = axxVecFile.read(buffer)) > 0) { tmpPolFile.write(buffer, 0, read); } axxVecFile.close(); tmpPolFile.write("attribute ricka; \ntype rick_t; \nrole rick_r types rick_t; \nuser rick_u roles rick_r;\nsid kernel rick_u:rick_r:rick_t\nfs_use_xattr ext3 rick_u:rick_r:rick_t;\ngenfscon proc / rick_u:rick_r:rick_t\n"); tmpPolFile.flush(); tmpPolFile.close(); if (apol.open_policy(tmpPolConf.getAbsolutePath(), p_p_pol) == 0) { Policy = apol.policy_t_p_p_value(p_p_pol); if (Policy == null) { throw new Exception("Failed to allocate memory for policy_t struct."); } tmpPolConf.delete(); } else { throw new IOException("Failed to open/parse base policy file: " + tmpPolConf.getAbsolutePath()); } }
11
Code Sample 1: public static boolean copyFileToContentFolder(String source, LearningDesign learningDesign) { File inputFile = new File(source); File outputFile = new File(getRootFilePath(learningDesign) + inputFile.getName()); FileReader in; try { in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } Code Sample 2: public static File copyFile(File fileToCopy, File copiedFile) { BufferedInputStream in = null; BufferedOutputStream outWriter = null; if (!copiedFile.exists()) { try { copiedFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); return null; } } try { in = new BufferedInputStream(new FileInputStream(fileToCopy), 4096); outWriter = new BufferedOutputStream(new FileOutputStream(copiedFile), 4096); int c; while ((c = in.read()) != -1) outWriter.write(c); in.close(); outWriter.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } return copiedFile; }