label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public void update(String target, String cfgVersion) throws MalformedURLException, FileNotFoundException, IOException { Debug.log("Config Updater", "Checking for newer configuration..."); URL url = new URL(target); String[] urlSplit = target.split("/"); this.fileName = urlSplit[urlSplit.length - 1]; BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(Main.getHomeDir() + "tmp-" + this.fileName)); URLConnection urlConnection = url.openConnection(); InputStream in = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int numRead; int fileSize = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); fileSize += numRead; } Debug.log("Config Updater", "Read latest configuration: " + fileSize + " bytes"); in.close(); out.close(); XMLController xmlC = new XMLController(); String newFileVersion = xmlC.readCfgVersion(Main.getHomeDir() + "tmp-" + this.fileName); if (new File(Main.getHomeDir() + this.fileName).exists()) { Debug.log("Config Updater", "Local configfile '" + Main.getHomeDir() + this.fileName + "' exists (version " + cfgVersion + ")"); if (Double.parseDouble(newFileVersion) > Double.parseDouble(cfgVersion)) { Debug.log("Config Updater", "Removing old config and replacing it with version " + newFileVersion); new File(Main.getHomeDir() + this.fileName).delete(); new File(Main.getHomeDir() + "tmp-" + this.fileName).renameTo(new File(Main.getHomeDir() + this.fileName)); this.result = "ConfigFile upgraded to version " + newFileVersion; } else { new File(Main.getHomeDir() + "tmp-" + this.fileName).delete(); Debug.log("Config Updater", "I already have the latest version " + cfgVersion); } } else { Debug.log("Config Updater", "Local config doesn't exist. Loading the new one, version " + newFileVersion); new File(Main.getHomeDir() + "tmp-" + this.fileName).renameTo(new File(Main.getHomeDir() + this.fileName)); this.result = "ConfigFile upgraded to version " + newFileVersion; } Debug.log("Config Updater", "Update of configuration done"); } Code Sample 2: public void url2SaveAsFile(String urlStr, String saveAsFileName) throws Exception { URL url = new URL(urlStr); URLConnection uc = url.openConnection(); File f = new File(saveAsFileName); if (!f.exists()) { FileOutputStream fos = new FileOutputStream(f); BufferedInputStream bis = new BufferedInputStream(uc.getInputStream()); byte[] buffer = new byte[4096]; int readCount = 0; while ((readCount = bis.read(buffer)) != -1) { fos.write(buffer, 0, readCount); } fos.flush(); fos.close(); bis.close(); } }
00
Code Sample 1: public void testCreateNewXMLFile() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource emptySource = loadTestSource(); assertEquals(false, emptySource.exists()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } InputStream expected = getClass().getResourceAsStream(CONTENT_FILE); JCRNodeSource persistentSource = loadTestSource(); assertEquals(true, persistentSource.exists()); InputStream actual = persistentSource.getInputStream(); try { assertTrue(isXmlEqual(expected, actual)); } finally { expected.close(); actual.close(); } JCRNodeSource tmpSrc = (JCRNodeSource) resolveSource(BASE_URL + "users/alexander.saar"); persistentSource.delete(); tmpSrc.delete(); } Code Sample 2: public static String readFromAddress(String address) throws Exception { StringBuilder sb = new StringBuilder(); URL url = new URL(address); URLConnection con = url.openConnection(); con.connect(); InputStream is = (InputStream) con.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); while (true) { String redak = br.readLine(); if (redak == null) break; sb.append(redak); sb.append(System.getProperty("line.separator")); } br.close(); return sb.toString(); }
11
Code Sample 1: public static void copyFile(File source, String target) throws FileNotFoundException, IOException { File fout = new File(target); fout.mkdirs(); fout.delete(); fout = new File(target); FileChannel in = new FileInputStream(source).getChannel(); FileChannel out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } Code Sample 2: private void saveFile(InputStream in, String fullPath) { try { File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(in, out); out.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: private static void testIfNoneMatch() throws Exception { String eTag = c.getHeaderField("ETag"); InputStream in = c.getInputStream(); byte[] buffer = new byte[1024]; int read = 0; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); do { read = in.read(buffer); if (read > 0) md5.update(buffer, 0, read); } while (read < 0); byte[] digest = md5.digest(); String hexDigest = getHexString(digest); if (hexDigest.equals(eTag)) System.out.print("eTag content : md5 hex string"); String quotedHexDigest = "\"" + hexDigest + "\""; if (quotedHexDigest.equals(eTag)) System.out.print("eTag content : quoted md5 hex string"); HttpURLConnection c2 = (HttpURLConnection) url.openConnection(); c2.addRequestProperty("If-None-Match", eTag); c2.connect(); int code = c2.getResponseCode(); System.out.print("If-None-Match response: "); boolean supported = (code == 304); System.out.println(b2s(supported) + " - " + code + " (" + c2.getResponseMessage() + ")"); } Code Sample 2: public void download(RequestContext ctx) throws IOException { if (ctx.isRobot()) { ctx.forbidden(); return; } long id = ctx.id(); File bean = File.INSTANCE.Get(id); if (bean == null) { ctx.not_found(); return; } String f_ident = ctx.param("fn", ""); if (id >= 100 && !StringUtils.equals(f_ident, bean.getIdent())) { ctx.not_found(); return; } if (bean.IsLoginRequired() && ctx.user() == null) { StringBuilder login = new StringBuilder(LinkTool.home("home/login?goto_page=")); ctx.redirect(login.toString()); return; } FileInputStream fis = null; try { java.io.File file = StorageService.FILES.readFile(bean.getPath()); fis = new FileInputStream(file); ctx.response().setContentLength((int) file.length()); String ext = FilenameUtils.getExtension(bean.getPath()); String mine_type = Multimedia.mime_types.get(ext); if (mine_type != null) ctx.response().setContentType(mine_type); String ua = ctx.header("user-agent"); if (ua != null && ua.indexOf("Firefox") >= 0) ctx.header("Content-Disposition", "attachment; filename*=\"utf8''" + LinkTool.encode_url(bean.getName()) + "." + ext + "\""); else ctx.header("Content-Disposition", "attachment; filename=" + LinkTool.encode_url(bean.getName() + "." + ext)); IOUtils.copy(fis, ctx.response().getOutputStream()); bean.IncDownloadCount(1); } finally { IOUtils.closeQuietly(fis); } }
00
Code Sample 1: private void loadServers() { try { URL url = new URL(VirtualDeckConfig.SERVERS_URL); cmbServer.addItem("Local"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; if (in.readLine().equals("[list]")) { while ((str = in.readLine()) != null) { String[] host_line = str.split(";"); Host h = new Host(); h.setIp(host_line[0]); h.setPort(Integer.parseInt(host_line[1])); h.setName(host_line[2]); getServers().add(h); cmbServer.addItem(h.getName()); } } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } } 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; }
00
Code Sample 1: public static InputStream obterConteudoArquivo(String u) { URL url; try { url = new URL(u); URLConnection conn = null; if (proxy != null) conn = url.openConnection(proxy.getProxy()); else conn = url.openConnection(); return new DataInputStream(conn.getInputStream()); } catch (MalformedURLException e) { throw new AlfredException(e); } catch (IOException e) { throw new AlfredException(e); } } Code Sample 2: public static boolean copy(File source, File dest) { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
00
Code Sample 1: public void readPage(String search) { InputStream is = null; try { URL url = new URL("http://www.english-german-dictionary.com/index.php?search=" + search.trim()); is = url.openStream(); InputStreamReader isr = new InputStreamReader(is, "ISO-8859-15"); Scanner scan = new Scanner(isr); String str = new String(); String translate = new String(); String temp; while (scan.hasNextLine()) { temp = (scan.nextLine()); if (temp.contains("<td style='padding-top:4px;' class='ergebnisse_res'>")) { int anfang = temp.indexOf("-->") + 3; temp = temp.substring(anfang); temp = temp.substring(0, temp.indexOf("<!--")); translate = temp.trim(); } else if (temp.contains("<td style='' class='ergebnisse_art'>") || temp.contains("<td style='' class='ergebnisse_art_dif'>") || temp.contains("<td style='padding-top:4px;' class='ergebnisse_art'>")) { if (searchEnglish == false && searchGerman == false) { searchEnglish = temp.contains("<td style='' class='ergebnisse_art'>"); searchGerman = temp.contains("<td style='' class='ergebnisse_art_dif'>"); } int anfang1 = temp.lastIndexOf("'>") + 2; temp = temp.substring(anfang1, temp.lastIndexOf("</td>")); String to = temp.trim() + " "; temp = scan.nextLine(); int anfang2 = temp.lastIndexOf("\">") + 2; temp = (to != null ? to : "") + temp.substring(anfang2, temp.lastIndexOf("</a>")); str += translate + " - " + temp + "\n"; germanList.add(translate); englishList.add(temp.trim()); } } if (searchEnglish) { List<String> temp2 = englishList; englishList = germanList; germanList = temp2; } } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) try { is.close(); } catch (IOException e) { } } } Code Sample 2: public String execute(Map params, String body, RenderContext renderContext) throws MacroException { loadData(); String from = (String) params.get("from"); if (body.length() > 0 && from != null) { try { URL url; String serverUser = null; String serverPassword = null; url = new URL(semformsSettings.getZRapServerUrl() + "ZRAP_QueryProcessor.php?from=" + URLEncoder.encode(from, "utf-8") + "&query=" + URLEncoder.encode(body, "utf-8")); if (url.getUserInfo() != null) { String[] userInfo = url.getUserInfo().split(":"); if (userInfo.length == 2) { serverUser = userInfo[0]; serverPassword = userInfo[1]; } } URLConnection connection = null; InputStreamReader bf; if (serverUser != null && serverPassword != null) { connection = url.openConnection(); String encoding = new sun.misc.BASE64Encoder().encode((serverUser + ":" + serverPassword).getBytes()); connection.setRequestProperty("Authorization", "Basic " + encoding); bf = new InputStreamReader(connection.getInputStream()); } else { bf = new InputStreamReader(url.openStream()); } BufferedReader bbf = new BufferedReader(bf); String line = bbf.readLine(); String buffer = ""; while (line != null) { buffer += line; line = bbf.readLine(); } return buffer; } catch (Exception e) { e.printStackTrace(); return "ERROR:" + e.getLocalizedMessage(); } } else return "Please write an RDQL query in the macro as body and an url of the model as 'from' parameter"; }
11
Code Sample 1: 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; } Code Sample 2: private boolean confirmAndModify(MDPRArchiveAccessor archiveAccessor) { String candidateBackupName = archiveAccessor.getArchiveFileName() + ".old"; String backupName = createUniqueFileName(candidateBackupName); MessageFormat format = new MessageFormat(AUTO_MOD_MESSAGE); String message = format.format(new String[] { backupName }); boolean ok = MessageDialog.openQuestion(new Shell(Display.getDefault()), AUTO_MOD_TITLE, message); if (ok) { File orig = new File(archiveAccessor.getArchiveFileName()); try { IOUtils.copyFiles(orig, new File(backupName)); DeviceRepositoryAccessorManager dram = new DeviceRepositoryAccessorManager(archiveAccessor, new ODOMFactory()); dram.writeRepository(); } catch (IOException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } catch (RepositoryException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } } return ok; }
00
Code Sample 1: public HttpURLConnection openConnection(String url) throws IOException { if (isDebugMode()) System.out.println("open: " + url); URL u = new URL(url); HttpURLConnection urlConnection; if (proxy != null) urlConnection = (HttpURLConnection) u.openConnection(proxy); else urlConnection = (HttpURLConnection) u.openConnection(); urlConnection.setRequestProperty("User-Agent", userAgent); return urlConnection; } Code Sample 2: public String getMarketInfo() { try { URL url = new URL("http://api.eve-central.com/api/evemon"); BufferedReader s = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; String xml = ""; while ((line = s.readLine()) != null) { xml += line; } return xml; } catch (IOException ex) { ex.printStackTrace(); } return null; }
00
Code Sample 1: public FileInputStream execute() { FacesContext faces = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse(); String pdfPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pdf"); try { FileOutputStream outputStream = new FileOutputStream(pdfPath + "/driveTogether.pdf"); PdfWriter writer = PdfWriter.getInstance(doc, outputStream); doc.open(); String pfad = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pdf/template.pdf"); logger.info("Loading PDF-Template: " + pfad); PdfReader reader = new PdfReader(pfad); PdfImportedPage page = writer.getImportedPage(reader, 1); PdfContentByte cb = writer.getDirectContent(); cb.addTemplate(page, 0, 0); doHeader(); doParagraph(trip, forUser); doc.close(); fis = new FileInputStream(pdfPath + "/driveTogether.pdf"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return fis; } Code Sample 2: public void testScenario() throws Exception { String expression = "SELECT id, name, address, phone FROM " + TABLE + " where id > 2 and id < 12 order by id"; SQLQuery query = new SQLQuery(); query.setResourceID(mResourceID); query.addExpression(expression); TupleToWebRowSetCharArrays tupleToWebRowSet = new TupleToWebRowSetCharArrays(); tupleToWebRowSet.connectDataInput(query.getDataOutput()); DeliverToFTP deliverToFTP = new DeliverToFTP(); deliverToFTP.connectDataInput(tupleToWebRowSet.getResultOutput()); deliverToFTP.addFilename(FILE); deliverToFTP.addHost(mURL); PipelineWorkflow pipeline = new PipelineWorkflow(); pipeline.add(query); pipeline.add(tupleToWebRowSet); pipeline.add(deliverToFTP); mDRER.execute(pipeline, RequestExecutionType.SYNCHRONOUS); final URL url = new URL("ftp://" + mURL + "/" + FILE); final URLConnection connection = url.openConnection(); connection.setDoInput(true); connection.setDoOutput(false); InputStream is = connection.getInputStream(); WebRowSetToResultSet converter = new WebRowSetToResultSet(new InputStreamReader(is)); converter.setResultSetType(ResultSet.TYPE_FORWARD_ONLY); ResultSet rs = converter.getResultSet(); JDBCTestHelper.validateResultSet(mConnection, expression, rs, 1); rs.close(); }
00
Code Sample 1: byte[] makeIDPFXORMask() { if (idpfMask == null) { try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); String temp = strip(getPrimaryIdentifier()); sha.update(temp.getBytes("UTF-8"), 0, temp.length()); idpfMask = sha.digest(); } catch (NoSuchAlgorithmException e) { System.err.println("No such Algorithm (really, did I misspell SHA-1?"); System.err.println(e.toString()); return null; } catch (IOException e) { System.err.println("IO Exception. check out mask.write..."); System.err.println(e.toString()); return null; } } return idpfMask; } Code Sample 2: public static void downloadFile(HttpServletResponse response, String file) throws IOException { response.setContentType(FileUtils.getContentType(file)); response.setContentLength(FileUtils.getContentLength(file)); response.setHeader("Content-type", ResponseUtils.DOWNLOAD_CONTENT_TYPE); response.setHeader("Content-Disposition", "attachment; filename=\"" + FileUtils.getFileName(file) + "\""); response.setHeader("Content-Length", Integer.toString(FileUtils.getContentLength(file))); InputStream input = new FileInputStream(file); OutputStream output = response.getOutputStream(); IOUtils.copy(input, output, true); }
11
Code Sample 1: public static void copy(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } 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); } }
00
Code Sample 1: public static String hashPassword(String password) { String hashStr = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(Charset.defaultCharset())); BigInteger hash = new BigInteger(1, md5.digest()); hashStr = hash.toString(16); } catch (NoSuchAlgorithmException e) { return password; } StringBuilder buffer = new StringBuilder(hashStr); while (buffer.length() < 32) { buffer.insert(0, '0'); } return buffer.toString(); } Code Sample 2: @Override protected Integer doInBackground() throws Exception { int numOfRows = 0; combinationMap = new HashMap<AnsweredQuestion, Integer>(); combinationMapReverse = new HashMap<Integer, AnsweredQuestion>(); LinkedHashSet<AnsweredQuestion> answeredQuestionSet = new LinkedHashSet<AnsweredQuestion>(); LinkedHashSet<Integer> studentSet = new LinkedHashSet<Integer>(); final String delimiter = ";"; final String typeToProcess = "F"; String line; String[] chunks = new String[9]; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "ISO-8859-2")); in.readLine(); while ((line = in.readLine()) != null) { chunks = line.split(delimiter); numOfRows++; if (chunks[2].equals(typeToProcess)) { answeredQuestionSet.add(new AnsweredQuestion(chunks[4], chunks[5])); studentSet.add(new Integer(chunks[0])); } } in.close(); int i = 0; Integer I; for (AnsweredQuestion pair : answeredQuestionSet) { I = new Integer(i++); combinationMap.put(pair, I); combinationMapReverse.put(I, pair); } matrix = new SparseObjectMatrix2D(answeredQuestionSet.size(), studentSet.size()); int lastStudentNumber = -1; AnsweredQuestion pair; in = new BufferedReader(new InputStreamReader(url.openStream(), "ISO-8859-2")); in.readLine(); while ((line = in.readLine()) != null) { chunks = line.split(delimiter); pair = null; if (chunks[2].equals(typeToProcess)) { if (Integer.parseInt(chunks[0]) != lastStudentNumber) { lastStudentNumber++; } pair = new AnsweredQuestion(chunks[4], chunks[5]); if (combinationMap.containsKey(pair)) { matrix.setQuick(combinationMap.get(pair), lastStudentNumber, Boolean.TRUE); } } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } supportVector = new int[combinationMap.size()]; ObjectMatrix1D row = null; for (int i = 0; i < combinationMap.size(); i++) { row = matrix.viewRow(i); int sum = 0; for (int k = 0; k < row.size(); k++) { if (row.getQuick(k) != null && row.getQuick(k).equals(Boolean.TRUE)) { sum++; } } supportVector[i] = sum; } applet.combinationMap = this.combinationMap; applet.combinationMapReverse = this.combinationMapReverse; applet.matrix = this.matrix; applet.supportVector = supportVector; System.out.println("data loaded."); return null; }
11
Code Sample 1: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: protected void zipFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(to)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); }
00
Code Sample 1: public InlineImageChunk(URL url) { super(); this.url = url; try { URLConnection urlConn = url.openConnection(); urlConn.setReadTimeout(15000); ImageInputStream iis = ImageIO.createImageInputStream(urlConn.getInputStream()); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { ImageReader reader = readers.next(); reader.setInput(iis, true); this.width = reader.getWidth(0); this.ascent = reader.getHeight(0); this.descent = 0; reader.dispose(); } else System.err.println("cannot read width and height of image " + url + " - no suitable reader!"); } catch (Exception exc) { System.err.println("cannot read width and height of image " + url + " due to exception:"); System.err.println(exc); exc.printStackTrace(System.err); } } Code Sample 2: @Override public boolean validatePublisher(Object object, String... dbSettingParams) { DBConnectionListener listener = (DBConnectionListener) object; String host = dbSettingParams[0]; String port = dbSettingParams[1]; String driver = dbSettingParams[2]; String type = dbSettingParams[3]; String dbHost = dbSettingParams[4]; String dbName = dbSettingParams[5]; String dbUser = dbSettingParams[6]; String dbPassword = dbSettingParams[7]; boolean validPublisher = false; String url = "http://" + host + ":" + port + "/reports"; try { URL _url = new URL(url); _url.openConnection().connect(); validPublisher = true; } catch (Exception e) { log.log(Level.FINE, "Failed validating url " + url, e); } if (validPublisher) { Connection conn; try { if (driver != null) { conn = DBProperties.getInstance().getConnection(driver, dbHost, dbName, type, dbUser, dbPassword); } else { conn = DBProperties.getInstance().getConnection(); } } catch (Exception e) { conn = null; listener.connectionIsOk(false, null); validPublisher = false; } if (validPublisher) { if (!allNecessaryTablesCreated(conn)) { conn = null; listener.connectionIsOk(false, null); validPublisher = false; } listener.connectionIsOk(true, conn); } } else { listener.connectionIsOk(false, null); } return validPublisher; }
00
Code Sample 1: private static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: private String calculateCredential(Account account) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return null; } try { md5.update(account.getUsername().getBytes("UTF-8")); md5.update(account.getCryptPassword().getBytes("UTF-8")); md5.update(String.valueOf(account.getObjectId()).getBytes("UTF-8")); md5.update(account.getUid().getBytes("UTF-8")); byte[] digest = md5.digest(); return TextUtils.calculateMD5(digest); } catch (UnsupportedEncodingException e) { return null; } }
11
Code Sample 1: public void fileCopy(File inFile, File outFile) { try { FileInputStream in = new FileInputStream(inFile); FileOutputStream out = new FileOutputStream(outFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { System.err.println("Hubo un error de entrada/salida!!!"); } } 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(); } }
11
Code Sample 1: private void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public void 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 String getNextObjectId() throws SQLException { long nextserial = 1; String s0 = "lock table serials in exclusive mode"; String s1 = "SELECT nextserial FROM serials WHERE tablename = 'SERVER_OIDS'"; String s2; try { Statement stmt = dbconnect.connection.createStatement(); stmt.executeUpdate(s0); ResultSet rs = stmt.executeQuery(s1); if (!rs.next()) { s2 = "insert into serials (tablename,nextserial) values ('SERVER_OIDS', " + (nextserial) + ")"; } else { nextserial = rs.getLong(1) + 1; s2 = "update serials set nextserial=" + (nextserial) + " where tablename='SERVER_OIDS'"; } stmt.executeUpdate(s2); dbconnect.connection.commit(); rs.close(); stmt.close(); return "" + nextserial; } catch (SQLException e) { dbconnect.connection.rollback(); throw e; } } Code Sample 2: public static void zip(ZipOutputStream out, File f, String base) throws Exception { if (f.isDirectory()) { File[] fl = f.listFiles(); base = base.length() == 0 ? "" : base + File.separator; for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + fl[i].getName()); } } else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); FileInputStream in = new FileInputStream(f); IOUtils.copyStream(in, out); in.close(); } Thread.sleep(10); }
11
Code Sample 1: public Object run() { List correctUsers = (List) JsonPath.query("select * from ? where name=?", usersTable(), username); if (correctUsers.size() == 0) { return new LoginException("user " + username + " not found"); } Persistable userObject = (Persistable) correctUsers.get(0); boolean alreadyHashed = false; boolean passwordMatch = password.equals(userObject.get(PASSWORD_FIELD)); if (!passwordMatch) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(((String) userObject.get(PASSWORD_FIELD)).getBytes()); passwordMatch = password.equals(new String(new Base64().encode(md.digest()))); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } alreadyHashed = true; } if (passwordMatch) { Logger.getLogger(User.class.toString()).info("User " + username + " has been authenticated"); User user = (User) userObject; try { if (alreadyHashed) user.currentTicket = password; else { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); user.currentTicket = new String(new Base64().encode(md.digest())); } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return user; } else { Logger.getLogger(User.class.toString()).info("The password was incorrect for " + username); return new LoginException("The password was incorrect for user " + username + ". "); } } Code Sample 2: public BigInteger calculateMd5(String input) throws FileSystemException { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes()); byte[] messageDigest = digest.digest(); BigInteger bigInt = new BigInteger(1, messageDigest); return bigInt; } catch (Exception e) { throw new FileSystemException(e); } }
11
Code Sample 1: public static void copyFile(File in, File outDir) throws IOException { FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(in).getChannel(); File out = new File(outDir, in.getName()); destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { try { if (sourceChannel != null) { sourceChannel.close(); } } finally { if (destinationChannel != null) { destinationChannel.close(); } } } } Code Sample 2: public boolean restore() { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/Android/bluebox.bak"; String backupDBPath = "/data/android.bluebox/databases/bluebox.db"; File currentDB = new File(sd, currentDBPath); File backupDB = new File(data, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); return true; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
11
Code Sample 1: public static final boolean checkForUpdate(final String currentVersion, final String updateURL, boolean noLock) throws Exception { try { final String parentFDTConfDirName = System.getProperty("user.home") + File.separator + ".fdt"; final String fdtUpdateConfFileName = "update.properties"; final File confFile = createOrGetRWFile(parentFDTConfDirName, fdtUpdateConfFileName); if (confFile != null) { long lastCheck = 0; Properties updateProperties = new Properties(); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(confFile); updateProperties.load(fis); final String lastCheckProp = (String) updateProperties.get("LastCheck"); lastCheck = 0; if (lastCheckProp != null) { try { lastCheck = Long.parseLong(lastCheckProp); } catch (Throwable t) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Got exception parsing LastCheck param", t); } lastCheck = 0; } } } catch (Throwable t) { logger.log(Level.WARNING, "Cannot load update properties file: " + confFile, t); } finally { closeIgnoringExceptions(fos); closeIgnoringExceptions(fis); } final long now = System.currentTimeMillis(); boolean bHaveUpdates = false; checkAndSetInstanceID(updateProperties); if (lastCheck + FDT.UPDATE_PERIOD < now) { lastCheck = now; try { logger.log("\n\nChecking for remote updates ... This may be disabled using -noupdates flag."); bHaveUpdates = updateFDT(currentVersion, updateURL, false, noLock); if (bHaveUpdates) { logger.log("FDT may be updated using: java -jar fdt.jar -update"); } else { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "No updates available"); } } } catch (Throwable t) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.WARNING, "Got exception", t); } } updateProperties.put("LastCheck", "" + now); try { fos = new FileOutputStream(confFile); updateProperties.store(fos, null); } catch (Throwable t1) { logger.log(Level.WARNING, "Cannot store update properties file", t1); } finally { closeIgnoringExceptions(fos); } return bHaveUpdates; } } else { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, " [ checkForUpdate ] Cannot read or write the update conf file: " + parentFDTConfDirName + File.separator + fdtUpdateConfFileName); } return false; } } catch (Throwable t) { logger.log(Level.WARNING, "Got exception checking for updates", t); } return false; } Code Sample 2: public void install(Session session) throws Exception { String cfgPath = ConfigurationFactory.getConfigSonInstance().getConfigurationPath(); File setupKson = new File(cfgPath, "setup.kson"); InputStream is = null; if (setupKson.exists()) { log.debug("Reagind kson from " + setupKson.getAbsolutePath()); is = new FileInputStream(setupKson); } else { String ksonCp = "/org/chon/cms/core/setup/setup.kson"; is = Setup.class.getResourceAsStream(ksonCp); log.info("Creating initial setup.kson in " + setupKson.getAbsolutePath()); IOUtils.copy(is, new FileOutputStream(setupKson)); is = new FileInputStream(setupKson); } BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); List<String> lines = new ArrayList<String>(); while (true) { String line = br.readLine(); if (line == null) break; lines.add(line); } List<NodeCreation> ncList = readKSon(lines.toArray(new String[lines.size()])); for (NodeCreation nc : ncList) { try { createNode(session, nc); } catch (Exception e) { System.err.println("error crating node " + nc.path + " -> " + e.getMessage()); } } session.save(); }
11
Code Sample 1: private String hashSong(Song s) { if (s == null) return null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(s.getTitle().getBytes()); digest.update(s.getAllLyrics().getBytes()); String hash = Base64.encodeBytes(digest.digest()); return hash; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } Code Sample 2: public String login() { String authSuccess = "false"; try { String errorMesg = ""; int error; if ((error = utils.stringIsNull(passwd)) != -1) { errorMesg += rb.getString("passwdField") + ": " + utils.errors[error] + " "; } else if ((error = utils.stringIsEmpty(passwd)) != -1) { errorMesg += rb.getString("passwdField") + ": " + utils.errors[error] + " "; } if ((error = utils.stringIsNull(login)) != -1) { errorMesg += rb.getString("loginField") + ": " + utils.errors[error] + " "; } else if ((error = utils.stringIsEmpty(login)) != -1) { errorMesg += rb.getString("loginField") + ": " + utils.errors[error] + " "; } String[] admins = conf.getProperty("admin").split("\\s"); boolean admin = false; for (int i = 0; i < admins.length; i++) { if (admins[i].equals(login)) { admin = true; } } if (!admin) { errorMesg += rb.getString("noAdmin"); session.invalidate(); } else { session.setAttribute("conf", conf); } if (errorMesg.length() > 0) { status = errorMesg; System.out.println(status); FacesContext context = FacesContext.getCurrentInstance(); context.renderResponse(); } else { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(passwd.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { String hex = Integer.toHexString(0xFF & result[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } authSuccess = (sqlManager.getPassword(login).equals(hexString.toString())) ? "true" : "false"; if (authSuccess.equals("false")) session.invalidate(); } } catch (NoSuchAlgorithmException nsae) { utils.catchExp(nsae); status = utils.getStatus(); if (stacktrace) { stackTrace = utils.getStackTrace(); } FacesContext.getCurrentInstance().renderResponse(); } catch (SQLException sqle) { utils.catchExp(sqle); status = utils.getStatus(); if (stacktrace) { stackTrace = utils.getStackTrace(); } FacesContext.getCurrentInstance().renderResponse(); } return authSuccess; }
11
Code Sample 1: private void setInlineXML(Entry entry, DatastreamXMLMetadata ds) throws UnsupportedEncodingException, StreamIOException { String content; if (m_obj.hasContentModel(Models.SERVICE_DEPLOYMENT_3_0) && (ds.DatastreamID.equals("SERVICE-PROFILE") || ds.DatastreamID.equals("WSDL"))) { content = DOTranslationUtility.normalizeInlineXML(new String(ds.xmlContent, m_encoding), m_transContext); } else { content = new String(ds.xmlContent, m_encoding); } if (m_format.equals(ATOM_ZIP1_1)) { String name = ds.DSVersionID + ".xml"; try { m_zout.putNextEntry(new ZipEntry(name)); InputStream is = new ByteArrayInputStream(content.getBytes(m_encoding)); IOUtils.copy(is, m_zout); m_zout.closeEntry(); is.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); entry.setSummary(ds.DSVersionID); entry.setContent(iri, ds.DSMIME); } else { entry.setContent(content, ds.DSMIME); } } Code Sample 2: 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; }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: protected GraphicalViewer createGraphicalViewer(Composite parent) { GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(parent); viewer.getControl().setBackground(parent.getBackground()); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); GraphicalViewerKeyHandler graphicalViewerKeyHandler = new GraphicalViewerKeyHandler(viewer); KeyHandler parentKeyHandler = graphicalViewerKeyHandler.setParent(getCommonKeyHandler()); viewer.setKeyHandler(parentKeyHandler); getEditDomain().addViewer(viewer); getSite().setSelectionProvider(viewer); ContextMenuProvider provider = new TestContextMenuProvider(viewer, getActionRegistry()); viewer.setContextMenu(provider); getSite().registerContextMenu("cubicTestPlugin.editor.contextmenu", provider, viewer); viewer.addDropTargetListener(new DataEditDropTargetListner(((IFileEditorInput) getEditorInput()).getFile().getProject(), viewer)); viewer.addDropTargetListener(new FileTransferDropTargetListener(viewer)); viewer.setEditPartFactory(getEditPartFactory()); viewer.setContents(getContent()); return viewer; }
00
Code Sample 1: @Test public void testCopy_inputStreamToWriter_Encoding_nullEncoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer, null); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } 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); } }
11
Code Sample 1: public static boolean insert(final Cargo cargo) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into cargo (nome) values (?)"; pst = c.prepareStatement(sql); pst.setString(1, cargo.getNome()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { e1.printStackTrace(); } System.out.println("[CargoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); sql = "DELETE FROM usuario WHERE cod_usuario =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); 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 GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
00
Code Sample 1: public static long[] getUids(String myUid) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpGet get = new HttpGet(UIDS_URI); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); JSONArray result = new JSONArray(res); long[] friends = new long[result.length()]; long uid = Long.parseLong(myUid); for (int i = 0; i < result.length(); i++) { if (uid != result.getLong(i)) { friends[i] = result.getLong(i); } } return friends; } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); } Code Sample 2: public static boolean isUrlAvailable(String url) { boolean flag = true; try { URLConnection conn = (new URL(url)).openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.connect(); if (conn.getDate() == 0) { flag = false; } } catch (IOException e) { log.error(e); flag = false; } return flag; }
00
Code Sample 1: public RobotList<Location> sort_decr_Location(RobotList<Location> list, String field) { int length = list.size(); Index_value[] enemy_dist = new Index_value[length]; if (field.equals("") || field.equals("location")) { Location cur_loc = this.getLocation(); for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, distance(cur_loc, list.get(i))); } } else if (field.equals("x")) { for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, list.get(i).x); } } else if (field.equals("y")) { for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, list.get(i).y); } } else { say("impossible to sort list - nothing modified"); return list; } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (enemy_dist[i].value < enemy_dist[i + 1].value) { Index_value a = enemy_dist[i]; enemy_dist[i] = enemy_dist[i + 1]; enemy_dist[i + 1] = a; permut = true; } } } while (permut); RobotList<Location> new_location_list = new RobotList<Location>(Location.class); for (int i = 0; i < length; i++) { new_location_list.addLast(list.get(enemy_dist[i].index)); } return new_location_list; } Code Sample 2: public static URLConnection openRemoteDescriptionFile(String urlstr) throws MalformedURLException { URL url = new URL(urlstr); try { URLConnection conn = url.openConnection(); conn.connect(); return conn; } catch (Exception e) { Config conf = Config.getInstance(); SimpleSocketAddress localServAddr = conf.getLocalProxyServerAddress(); Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(localServAddr.host, localServAddr.port)); URLConnection conn; try { conn = url.openConnection(proxy); conn.connect(); return conn; } catch (IOException e1) { logger.error("Failed to retrive desc file:" + url, e1); } } return null; }
00
Code Sample 1: public void run() { URLConnection con = null; try { con = url.openConnection(); if ("HTTPS".equalsIgnoreCase(url.getProtocol())) { HttpsURLConnection scon = (HttpsURLConnection) con; try { scon.setSSLSocketFactory(SSLUtil.getSSLSocketFactory(clientCertAlias)); HostnameVerifier hv = SSLUtil.getHostnameVerifier(hostCertLevel); if (hv != null) { scon.setHostnameVerifier(hv); } } catch (GeneralSecurityException e) { Debug.logError(e, module); } catch (GenericConfigException e) { Debug.logError(e, module); } } } catch (IOException e) { Debug.logError(e, module); } synchronized (URLConnector.this) { if (timedOut && con != null) { close(con); } else { connection = con; URLConnector.this.notify(); } } } Code Sample 2: public static String loadWebsiteHtmlCode(String url, String useragent) { HttpClient httpClient = new DefaultHttpClient(); HttpGet getMethod = new HttpGet(url); String htmlCode = ""; if (useragent != null) { getMethod.setHeader("user-agent", useragent); } try { HttpResponse resp = httpClient.execute(getMethod); int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.debug("Method failed!" + statusCode); } htmlCode = EntityUtils.toString(resp.getEntity()); } catch (Exception e) { logger.debug("Fatal protocol violation: " + e.getMessage()); logger.trace(e); } return htmlCode; }
00
Code Sample 1: private void inject(int x, int y) throws IOException { Tag source = data.getTag(); Log.event(Log.DEBUG_INFO, "source: " + source.getString()); if (source == Tag.ORGANISM) { String seed = data.readString(); data.readTag(Tag.STREAM); injectCodeTape(data.getIn(), seed, x, y); } else if (source == Tag.URL) { String url = data.readString(); String seed = url.substring(url.lastIndexOf('.') + 1); BufferedReader urlIn = null; try { urlIn = new BufferedReader(new InputStreamReader(new URL(url).openStream())); injectCodeTape(urlIn, seed, x, y); } finally { if (urlIn != null) urlIn.close(); } } else data.writeString("unknown organism source: " + source.getString()); } Code Sample 2: public static Book GetReviewsForBook(String bookId, int page, int rating) throws Exception { Uri.Builder builder = new Uri.Builder(); builder.scheme("http"); builder.authority("www.goodreads.com"); builder.path("book/show"); builder.appendQueryParameter("key", _ConsumerKey); builder.appendQueryParameter("page", Integer.toString(page)); builder.appendQueryParameter("rating", Integer.toString(rating)); builder.appendQueryParameter("id", bookId); HttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(builder.build().toString()); if (get_IsAuthenticated()) { _Consumer.sign(getRequest); } HttpResponse response = httpClient.execute(getRequest); Response responseData = ResponseParser.parse(response.getEntity().getContent()); return responseData.get_Book(); }
11
Code Sample 1: public static void parseString(String str, String name) { BufferedReader reader; String zeile = null; boolean firstL = true; int lambda; float intens; int l_b = 0; int l_e = 0; HashMap<Integer, Float> curve = new HashMap<Integer, Float>(); String[] temp; try { File f = File.createTempFile("tempFile", null); URL url = new URL(str); InputStream is = url.openStream(); FileOutputStream os = new FileOutputStream(f); byte[] buffer = new byte[0xFFFF]; for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len); is.close(); os.close(); reader = new BufferedReader(new FileReader(f)); zeile = reader.readLine(); lambda = 0; while (zeile != null) { if (!(zeile.length() > 0 && zeile.charAt(0) == '#')) { zeile = reader.readLine(); break; } zeile = reader.readLine(); } while (zeile != null) { if (zeile.length() > 0) { temp = zeile.split(" "); lambda = Integer.parseInt(temp[0]); intens = Float.parseFloat(temp[1]); if (firstL) { firstL = false; l_b = lambda; } curve.put(lambda, intens); } zeile = reader.readLine(); } l_e = lambda; } catch (IOException e) { System.err.println("Error2 :" + e); } try { String tempV; File file = new File("C:/spectralColors/" + name + ".sd"); FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); bw.write("# COLOR: " + name + " Auto generated File: 02/09/2009; From " + l_b + " to " + l_e); bw.newLine(); bw.write(l_b + ""); bw.newLine(); for (int i = l_b; i <= l_e; i++) { if (curve.containsKey(i)) { tempV = i + " " + curve.get(i); bw.write(tempV); bw.newLine(); } } bw.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public String readLines() { StringBuffer lines = new StringBuffer(); try { int HttpResult; URL url = new URL(address); URLConnection urlconn = url.openConnection(); urlconn.connect(); HttpURLConnection httpconn = (HttpURLConnection) urlconn; HttpResult = httpconn.getResponseCode(); if (HttpResult != HttpURLConnection.HTTP_OK) { System.out.println("�޷����ӵ�" + address); } else { BufferedReader reader = new BufferedReader(new InputStreamReader(urlconn.getInputStream())); while (true) { String line = reader.readLine(); if (line == null) break; lines.append(line + "\r\n"); } reader.close(); } } catch (Exception e) { e.printStackTrace(); } return lines.toString(); }
11
Code Sample 1: public static String generateHash(String message) throws NoSuchAlgorithmException, UnsupportedEncodingException, DigestException { MessageDigest digest; digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(message.getBytes("iso-8859-1"), 0, message.length()); byte[] output = new byte[20]; digest.digest(output, 0, output.length); return convertToHex(output); } Code Sample 2: public static String generateToken(ClientInfo clientInfo) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); Random rand = new Random(); String random = clientInfo.getIpAddress() + ":" + clientInfo.getPort() + ":" + rand.nextInt(); md5.update(random.getBytes()); String token = toHexString(md5.digest((new Date()).toString().getBytes())); clientInfo.setToken(token); return token; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
11
Code Sample 1: private void getXMLData() { String result = null; URL url = null; URLConnection conn = null; BufferedReader rd = null; StringBuffer sb = new StringBuffer(); String line; try { url = new URL(this.url); conn = url.openConnection(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { sb.append(line + "\n"); } rd.close(); result = sb.toString(); } catch (MalformedURLException e) { log.error("URL was malformed: {}", url, e); } catch (IOException e) { log.error("IOException thrown: {}", url, e); } this.xmlString = result; } Code Sample 2: private static String getProviderName(URL url, PrintStream err) { InputStream in = null; try { in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); String result = null; while (true) { String line = reader.readLine(); if (line == null) { break; } int commentPos = line.indexOf('#'); if (commentPos >= 0) { line = line.substring(0, commentPos); } line = line.trim(); int len = line.length(); if (len != 0) { if (result != null) { print(err, "checkconfig.multiproviders", url.toString()); return null; } result = line; } } if (result == null) { print(err, "checkconfig.missingprovider", url.toString()); return null; } return result; } catch (IOException e) { print(err, "configconfig.read", url.toString(), e); return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
11
Code Sample 1: public String genPass() { String salto = "Z1mX502qLt2JTcW9MTDTGBBw8VBQQmY2"; String clave = (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10); password = clave; String claveConSalto = clave + salto; MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); m.update(claveConSalto.getBytes("utf-8"), 0, claveConSalto.length()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String claveCifrada = new BigInteger(1, m.digest()).toString(16); return claveCifrada + ":" + salto; } Code Sample 2: public static String md5(String word) { MessageDigest alg = null; try { alg = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ServletUtils.class.getName()).log(Level.SEVERE, null, ex); } alg.reset(); alg.update(word.getBytes()); byte[] digest = alg.digest(); StringBuilder hashedWord = new StringBuilder(); String hx; for (int i = 0; i < digest.length; i++) { hx = Integer.toHexString(0xFF & digest[i]); if (hx.length() == 1) { hx = "0" + hx; } hashedWord.append(hx); } return hashedWord.toString(); }
00
Code Sample 1: private static void salvarCategoria(Categoria categoria) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "insert into categoria VALUES (?,?)"; ps = conn.prepareStatement(sql); ps.setNull(1, Types.INTEGER); ps.setString(2, categoria.getNome()); ps.executeUpdate(); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } } Code Sample 2: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(targetPath + filename)); IOUtils.copy(is, fos); response.setStatus(HttpServletResponse.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
00
Code Sample 1: public String getScript(String script, String params) { params = params.replaceFirst("&", "?"); StringBuffer document = new StringBuffer(); try { URL url = new URL(script + params); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { document.append(line + "\n"); } reader.close(); } catch (Exception e) { return e.toString(); } return document.toString(); } Code Sample 2: public static String getMD5(String... list) { if (list.length == 0) return null; MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.reset(); for (String in : list) md.update(in.getBytes()); byte[] digest = md.digest(); StringBuilder hexString = new StringBuilder(); for (int i = 0; i < digest.length; ++i) { String hex = Integer.toHexString(0xFF & digest[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
00
Code Sample 1: private void copyTemplates(ProjectPath pPath) { String sourceAntPath = pPath.sourceAntPath(); final String moduleName = projectOperations.getFocusedTopLevelPackage().toString(); logger.info("Module Name: " + moduleName); String targetDirectory = pPath.canonicalFileSystemPath(projectOperations); logger.info("Moving into target Directory: " + targetDirectory); if (!targetDirectory.endsWith("/")) { targetDirectory += "/"; } if (!fileManager.exists(targetDirectory)) { fileManager.createDirectory(targetDirectory); } System.out.println("Target Directory: " + pPath.sourceAntPath()); String path = TemplateUtils.getTemplatePath(getClass(), sourceAntPath); Set<URL> urls = UrlFindingUtils.findMatchingClasspathResources(context.getBundleContext(), path); Assert.notNull(urls, "Could not search bundles for resources for Ant Path '" + path + "'"); if (urls.isEmpty()) { logger.info("URLS are empty stopping..."); } for (URL url : urls) { logger.info("Stepping into " + url.toExternalForm()); String fileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1); fileName = fileName.replace("-template", ""); String targetFilename = targetDirectory + fileName; logger.info("Handling " + targetFilename); if (!fileManager.exists(targetFilename)) { try { logger.info("Copied file"); String input = FileCopyUtils.copyToString(new InputStreamReader(url.openStream())); logger.info("TopLevelPackage: " + projectOperations.getFocusedTopLevelPackage()); logger.info("SegmentPackage: " + pPath.canonicalFileSystemPath(projectOperations)); String topLevelPackage = projectOperations.getFocusedTopLevelPackage().toString(); input = input.replace("__TOP_LEVEL_PACKAGE__", topLevelPackage); input = input.replace("__SEGMENT_PACKAGE__", pPath.segmentPackage()); input = input.replace("__PROJECT_NAME__", projectOperations.getFocusedProjectName()); input = input.replace("__ENTITY_NAME__", entityName); MutableFile mutableFile = fileManager.createFile(targetFilename); FileCopyUtils.copy(input.getBytes(), mutableFile.getOutputStream()); } catch (IOException ioe) { throw new IllegalStateException("Unable to create '" + targetFilename + "'", ioe); } } } } Code Sample 2: public String digest(String password, String digestType, String inputEncoding) throws CmsPasswordEncryptionException { MessageDigest md; String result; try { if (DIGEST_TYPE_PLAIN.equals(digestType.toLowerCase())) { result = password; } else if (DIGEST_TYPE_SSHA.equals(digestType.toLowerCase())) { byte[] salt = new byte[4]; byte[] digest; byte[] total; if (m_secureRandom == null) { m_secureRandom = SecureRandom.getInstance("SHA1PRNG"); } m_secureRandom.nextBytes(salt); md = MessageDigest.getInstance(DIGEST_TYPE_SHA); md.reset(); md.update(password.getBytes(inputEncoding)); md.update(salt); digest = md.digest(); total = new byte[digest.length + salt.length]; System.arraycopy(digest, 0, total, 0, digest.length); System.arraycopy(salt, 0, total, digest.length, salt.length); result = new String(Base64.encodeBase64(total)); } else { md = MessageDigest.getInstance(digestType); md.reset(); md.update(password.getBytes(inputEncoding)); result = new String(Base64.encodeBase64(md.digest())); } } catch (NoSuchAlgorithmException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_ALGORITHM_1, digestType); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } catch (UnsupportedEncodingException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_PASSWORD_ENCODING_1, inputEncoding); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } return result; }
11
Code Sample 1: public static void main(String[] args) throws IOException { System.out.println("start"); URL url = new URL("https://spreadsheets.google.com/feeds/list/" + "0AnoMCh3_x82sdERLR3FvVDBIWXpjT1JlcENmOFdERVE/" + "od7/public/basic"); InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { String[] mass = line.split("<entry>"); for (String m : mass) { System.out.println(m); } } } Code Sample 2: private static String connect(String apiURL, boolean secure) throws IOException { String baseUrl; if (secure) baseUrl = "https://todoist.com/API/"; else baseUrl = "http://todoist.com/API/"; URL url = new URL(baseUrl + apiURL); URLConnection c = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder toReturn = new StringBuilder(""); String toAppend; while ((toAppend = in.readLine()) != null) toReturn.append(toAppend); return toReturn.toString(); }
00
Code Sample 1: public QueryOutput run() throws Exception { boolean success = false; QueryOutput output = null; if (correlator != null || inMemMaster != null || customMatcher != null) { List<Object[]> rows = inMemMaster == null ? (correlator == null ? customMatcher.onCycleEnd() : correlator.onCycleEnd()) : inMemMaster.onCycleEnd(); if (rows.isEmpty()) { success = true; return null; } output = new DirectQueryOutput(rows); } else { connection = queryContext.createConnection(); try { connection.setAutoCommit(false); connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); thePreparedStatement = connection.prepareStatement(thePreparedStatementSQL); RowStatusHelper.setStatusValues(statusAndPositions, thePreparedStatement, queryContext.getRunCount()); long newResultIdsAfter = lastRowIdInsertedNow; int rows = thePreparedStatement.executeUpdate(); if (rows <= 0) { success = true; return null; } lastRowIdInsertedNow = getLastRowIdInResultTable(newResultIdsAfter, rows); output = new DBQueryOutput(newResultIdsAfter, lastRowIdInsertedNow, rows, timeKeeper.getTimeMsecs()); success = true; } finally { if (connection != null) { if (success) { connection.commit(); } else { connection.rollback(); } } } } return output; } Code Sample 2: public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { size = outputFile.length(); if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(outputFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } } }
00
Code Sample 1: public static final String convertPassword(final String srcPwd) { StringBuilder out; MessageDigest md; byte[] byteValues; byte singleChar = 0; try { md = MessageDigest.getInstance("MD5"); md.update(srcPwd.getBytes()); byteValues = md.digest(); if ((byteValues == null) || (byteValues.length <= 0)) { return null; } out = new StringBuilder(byteValues.length * 2); for (byte element : byteValues) { singleChar = (byte) (element & 0xF0); singleChar = (byte) (singleChar >>> 4); singleChar = (byte) (singleChar & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); singleChar = (byte) (element & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); } return out.toString(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } Code Sample 2: private void addLocale(Locale locale) throws MissingResourceException { locale = stripVariant(locale); Map<String, String> props = localeToMap.get(locale); if (props == null) props = new HashMap<String, String>(); String urlName = locale.toString() + LOCALE_FILE_URL_SUFFIX; URL url = ClassLoader.getSystemClassLoader().getResource(urlName); if (url == null) { url = Thread.currentThread().getContextClassLoader().getResource(urlName); if (url == null) { throw new MissingResourceException("Cannot locate hprops for " + "locale " + locale, "PropertiesLocalizer", "HProperties: for " + locale); } } BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader((InputStream) url.openStream(), "UTF8")); String str; while ((str = input.readLine()) != null) { str = str.trim(); if (!str.startsWith("#") && !str.startsWith("!")) { int index = -1; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c == ':' || c == '=') { index = i; break; } } if (index > 0) { String key = str.substring(0, index).trim(); String value = str.substring(index + 1); props.put(key, value); } } } } catch (IOException ioe) { throw new MissingResourceException(ioe.getMessage(), "PropertiesLocalizer", "HProperties: for " + locale.toString()); } finally { try { input.close(); } catch (IOException ioe) { } } localeToMap.put(locale, props); }
11
Code Sample 1: static final String md5(String text) throws RtmApiException { MessageDigest md; try { 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 e) { throw new RtmApiException("Md5 error: NoSuchAlgorithmException - " + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new RtmApiException("Md5 error: UnsupportedEncodingException - " + e.getMessage()); } } Code Sample 2: public static boolean validPassword(String password, String passwordInDb) throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] pwdInDb = hexStringToByte(passwordInDb); byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH]; System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length); if (Arrays.equals(digest, digestInDb)) { return true; } else { return false; } }
00
Code Sample 1: private String md5(String value) { String md5Value = "1"; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(value.getBytes()); md5Value = getHex(digest.digest()); } catch (Exception e) { e.printStackTrace(); } return md5Value; } Code Sample 2: public void create() throws IOException { FileChannel fc = new FileInputStream(sourceFile).getChannel(); for (RangeArrayElement element : array) { FileChannel fc_ = fc.position(element.starting()); File part = new File(destinationDirectory, "_0x" + Long.toHexString(element.starting()) + ".partial"); FileChannel partfc = new FileOutputStream(part).getChannel(); partfc.transferFrom(fc_, 0, element.getSize()); partfc.force(true); partfc.close(); } fc.close(); }
11
Code Sample 1: private void createNodes() { try { URL url = this.getClass().getResource(this.nodeFileName); InputStreamReader inReader = new InputStreamReader(url.openStream()); BufferedReader inNodes = new BufferedReader(inReader); // BufferedReader inNodes = new BufferedReader(new // FileReader("NodesFile.txt")); String s; while ((s = inNodes.readLine()) != null) { String label = inNodes.readLine(); String fullText = inNodes.readLine(); String type = inNodes.readLine(); Node n = new Node(s, type); n.label = label; n.fullText = fullText; node.add(n); } inNodes.close(); url = this.getClass().getResource(this.edgeFileName); inReader = new InputStreamReader(url.openStream()); BufferedReader inEdges = new BufferedReader(inReader); // BufferedReader inEdges = new BufferedReader(new // FileReader("EdgesFile.txt")); while ((s = inEdges.readLine()) != null) edge.add(new Edge(s, inEdges.readLine(), inEdges.readLine(), inEdges.readLine())); inEdges.close(); } catch (FileNotFoundException e) { // TODO �Զ���� catch �� e.printStackTrace(); } catch (IOException e) { // TODO �Զ���� catch �� e.printStackTrace(); } /* * for(Myparser.Nd x:FreeConnectTest.pNd){ Node n = new Node(x.id, * x.type); n.label = x.label; node.add(n); } for(Myparser.Ed * x:FreeConnectTest.pEd) edge.add(new Edge(x.id, x.source.id, * x.target.id)); */ } Code Sample 2: public static void loadPlugins() { Logger.trace("Loading plugins"); Enumeration<URL> urls = null; try { urls = Play.classloader.getResources("play.plugins"); } catch (Exception e) { } while (urls != null && urls.hasMoreElements()) { URL url = urls.nextElement(); Logger.trace("Found one plugins descriptor, %s", url); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { String[] infos = line.split(":"); PlayPlugin plugin = (PlayPlugin) Play.classloader.loadClass(infos[1].trim()).newInstance(); Logger.trace("Loaded plugin %s", plugin); plugin.index = Integer.parseInt(infos[0]); plugins.add(plugin); } } catch (Exception ex) { Logger.error(ex, "Cannot load %s", url); } } Collections.sort(plugins); for (PlayPlugin plugin : new ArrayList<PlayPlugin>(plugins)) { plugin.onLoad(); } }
00
Code Sample 1: @Override public String toString() { if (byteArrayOutputStream == null) return "<Unparsed binary data: Content-Type=" + getHeader("Content-Type") + " >"; String charsetName = getCharsetName(); if (charsetName == null) charsetName = "ISO-8859-1"; try { if (unzip) { GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); ByteArrayOutputStream unzippedResult = new ByteArrayOutputStream(); IOUtils.copy(gzipInputStream, unzippedResult); return unzippedResult.toString(charsetName); } else { return byteArrayOutputStream.toString(charsetName); } } catch (UnsupportedEncodingException e) { throw new OutputException(e); } catch (IOException e) { throw new OutputException(e); } } Code Sample 2: private void createCanvas() { GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.setRootEditPart(new ScalableRootEditPart()); viewer.setEditPartFactory(new BlockEditPartFactory()); viewer.createControl(this); viewer.setKeyHandler(new GraphicalViewerKeyHandler(viewer)); ActionRegistry actionRegistry = new ActionRegistry(); createActions(actionRegistry); ContextMenuProvider cmProvider = new BlockContextMenuProvider(viewer, actionRegistry); viewer.setContextMenu(cmProvider); Block b = new Block(); b.addChild(new ChartItem()); viewer.setContents(b); PaletteViewer paletteViewer = new PaletteViewer(); paletteViewer.createControl(this); }
00
Code Sample 1: public static String encrypt(String text) throws NoSuchAlgorithmException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; try { md.update(text.getBytes("iso-8859-1"), 0, text.length()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: private void delay(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String url = request.getRequestURL().toString(); if (delayed.contains(url)) { delayed.remove(url); LOGGER.info(MessageFormat.format("Loading delayed resource at url = [{0}]", url)); chain.doFilter(request, response); } else { LOGGER.info("Returning resource = [LoaderApplication.swf]"); InputStream input = null; OutputStream output = null; try { input = getClass().getResourceAsStream("LoaderApplication.swf"); output = response.getOutputStream(); delayed.add(url); response.setHeader("Cache-Control", "no-cache"); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } } }
00
Code Sample 1: protected void doRestoreOrganizeTypeRelation() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strDelQuery = "DELETE FROM " + Common.ORGANIZE_TYPE_RELATION_TABLE; String strSelQuery = "SELECT parent_organize_type,child_organize_type " + "FROM " + Common.ORGANIZE_TYPE_RELATION_B_TABLE + " " + "WHERE version_no = ?"; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_RELATION_TABLE + " " + "(parent_organize_type,child_organize_type) " + "VALUES (?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strDelQuery); ps.executeUpdate(); ps = con.prepareStatement(strSelQuery); ps.setInt(1, this.versionNO); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setString(1, result.getString("parent_organize_type")); ps.setString(2, result.getString("child_organize_type")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): ERROR Inserting data " + "in T_SYS_ORGANIZE_TYPE_RELATION INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): SQLException while committing or rollback"); } } Code Sample 2: public static void main(String[] argv) throws IOException { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); ; try { session.beginTransaction(); Properties cfg = new Properties(); URL url = SVM.class.getClassLoader().getResource(CFG_FILE); cfg.load(url.openStream()); int runMode = Integer.valueOf(cfg.getProperty(KEY_RUN_MODE)); switch(runMode) { case RUN_OPT: new SVM().optimizeParameters(cfg); break; case RUN_PREDICT: new SVM().trainAndPredict(cfg); break; case RUN_OPT_AND_PREDICT: break; } session.getTransaction().commit(); } catch (HibernateException he) { session.getTransaction().rollback(); logger.error("Database error.", he); session.close(); } }
00
Code Sample 1: public void moveRuleDown(String language, String tag, int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); int max = findMaxRank(stmt, language, tag); if ((row < 1) || (row > (max - 1))) throw new IllegalArgumentException("Row number (" + row + ") was not between 1 and " + (max - 1)); stmt.executeUpdate("update LanguageMorphologies set Rank = -1 " + "where Rank = " + row + " and MorphologyTag = '" + tag + "' and " + " LanguageName = '" + language + "'"); stmt.executeUpdate("update LanguageMorphologies set Rank = " + row + "where Rank = " + (row + 1) + " and MorphologyTag = '" + tag + "' and " + " LanguageName = '" + language + "'"); stmt.executeUpdate("update LanguageMorphologies set Rank = " + (row + 1) + "where Rank = -1 and MorphologyTag = '" + tag + "' and " + " LanguageName = '" + language + "'"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: public static long copy(File src, File dest) throws UtilException { FileChannel srcFc = null; FileChannel destFc = null; try { srcFc = new FileInputStream(src).getChannel(); destFc = new FileOutputStream(dest).getChannel(); long srcLength = srcFc.size(); srcFc.transferTo(0, srcLength, destFc); return srcLength; } catch (IOException e) { throw new UtilException(e); } finally { try { if (srcFc != null) srcFc.close(); srcFc = null; } catch (IOException e) { } try { if (destFc != null) destFc.close(); destFc = null; } catch (IOException e) { } } }
11
Code Sample 1: public static void copyFile(String source, String destination, boolean overwrite) { File sourceFile = new File(source); try { File destinationFile = new File(destination); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destinationFile)); int temp = 0; while ((temp = bis.read()) != -1) bos.write(temp); bis.close(); bos.close(); } catch (Exception e) { } return; } Code Sample 2: protected static String getURLandWriteToDisk(String url, Model retModel) throws MalformedURLException, IOException { String path = null; URL ontURL = new URL(url); InputStream ins = ontURL.openStream(); InputStreamReader bufRead; OutputStreamWriter bufWrite; int offset = 0, read = 0; initModelHash(); if (System.getProperty("user.dir") != null) { String delimiter; path = System.getProperty("user.dir"); if (path.contains("/")) { delimiter = "/"; } else { delimiter = "\\"; } char c = path.charAt(path.length() - 1); if (c == '/' || c == '\\') { path = path.substring(0, path.length() - 2); } path = path.substring(0, path.lastIndexOf(delimiter) + 1); path = path.concat("ontologies" + delimiter + "downloaded"); (new File(path)).mkdir(); path = path.concat(delimiter); path = createFullPath(url, path); bufWrite = new OutputStreamWriter(new FileOutputStream(path)); bufRead = new InputStreamReader(ins); read = bufRead.read(); while (read != -1) { bufWrite.write(read); offset += read; read = bufRead.read(); } bufRead.close(); bufWrite.close(); ins.close(); FileInputStream fs = new FileInputStream(path); retModel.read(fs, ""); } return path; }
11
Code Sample 1: private void copyResource(String resource, File targetDir) { InputStream is = FragmentFileSetTest.class.getResourceAsStream(resource); Assume.assumeNotNull(is); int i = resource.lastIndexOf("/"); String filename; if (i == -1) { filename = resource; } else { filename = resource.substring(i + 1); } try { FileOutputStream fos = new FileOutputStream(new File(targetDir, filename)); IOUtils.copy(is, fos); fos.close(); } catch (IOException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } Code Sample 2: public static void compress(final File zip, final Map<InputStream, String> entries, final IProgressMonitor monitor) 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); try { for (InputStream inputStream : entries.keySet()) { ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(inputStream))); out.putNextEntry(zipEntry); IOUtils.copy(inputStream, out); out.closeEntry(); inputStream.close(); if (monitor != null) monitor.worked(1); } } finally { IOUtils.closeQuietly(out); } }
11
Code Sample 1: private void fileCopier(String filenameFrom, String filenameTo) { FileInputStream fromStream = null; FileOutputStream toStream = null; try { fromStream = new FileInputStream(new File(filenameFrom)); if (new File(filenameTo).exists()) { new File(filenameTo).delete(); } File dirr = new File(getContactPicPath()); if (!dirr.exists()) { dirr.mkdir(); } toStream = new FileOutputStream(new File(filenameTo)); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fromStream.read(buffer)) != -1) toStream.write(buffer, 0, bytesRead); } catch (FileNotFoundException e) { Errmsg.errmsg(e); } catch (IOException e) { Errmsg.errmsg(e); } finally { try { if (fromStream != null) { fromStream.close(); } if (toStream != null) { toStream.close(); } } catch (IOException e) { Errmsg.errmsg(e); } } } Code Sample 2: private final long test(final boolean applyFilter, final int executionCount) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException, RuleLoadingException { final boolean stripHtmlEnabled = true; final boolean injectSecretTokensEnabled = true; final boolean encryptQueryStringsEnabled = true; final boolean protectParamsAndFormsEnabled = true; final boolean applyExtraProtectionForDisabledFormFields = true; final boolean applyExtraProtectionForReadonlyFormFields = false; final boolean applyExtraProtectionForRequestParamValueCount = false; final ContentInjectionHelper helper = new ContentInjectionHelper(); final RuleFileLoader ruleFileLoaderModificationExcludes = new ClasspathZipRuleFileLoader(); ruleFileLoaderModificationExcludes.setPath(WebCastellumFilter.MODIFICATION_EXCLUDES_DEFAULT); final ContentModificationExcludeDefinitionContainer containerModExcludes = new ContentModificationExcludeDefinitionContainer(ruleFileLoaderModificationExcludes); containerModExcludes.parseDefinitions(); helper.setContentModificationExcludeDefinitions(containerModExcludes); final AttackHandler attackHandler = new AttackHandler(null, 123, 600000, 100000, 300000, 300000, null, "MOCK", false, false, 0, false, false, Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), true); final SessionCreationTracker sessionCreationTracker = new SessionCreationTracker(attackHandler, 0, 600000, 300000, 0, "", "", "", ""); final RequestWrapper request = new RequestWrapper(new RequestMock(), helper, sessionCreationTracker, "123.456.789.000", false, true, true); final RuleFileLoader ruleFileLoaderResponseModifications = new ClasspathZipRuleFileLoader(); ruleFileLoaderResponseModifications.setPath(WebCastellumFilter.RESPONSE_MODIFICATIONS_DEFAULT); final ResponseModificationDefinitionContainer container = new ResponseModificationDefinitionContainer(ruleFileLoaderResponseModifications); container.parseDefinitions(); final ResponseModificationDefinition[] responseModificationDefinitions = downCast(container.getAllEnabledRequestDefinitions()); final List tmpPatternsToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpGroupNumbersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpGroupNumbersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); for (int i = 0; i < responseModificationDefinitions.length; i++) { final ResponseModificationDefinition responseModificationDefinition = responseModificationDefinitions[i]; if (responseModificationDefinition.isMatchesScripts()) { tmpPatternsToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPattern()); tmpPrefiltersToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPrefilter()); tmpPatternsToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinScripts.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } if (responseModificationDefinition.isMatchesTags()) { tmpPatternsToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPattern()); tmpPrefiltersToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPrefilter()); tmpPatternsToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinTags.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } } final Matcher[] matchersToExcludeCompleteTag = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteTag); final Matcher[] matchersToExcludeCompleteScript = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteScript); final Matcher[] matchersToExcludeLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinScripts); final Matcher[] matchersToExcludeLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinTags); final Matcher[] matchersToCaptureLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinScripts); final Matcher[] matchersToCaptureLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinTags); final WordDictionary[] prefiltersToExcludeCompleteTag = (WordDictionary[]) tmpPrefiltersToExcludeCompleteTag.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeCompleteScript = (WordDictionary[]) tmpPrefiltersToExcludeCompleteScript.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinTags = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinTags.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinTags = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinTags.toArray(new WordDictionary[0]); final int[][] groupNumbersToCaptureLinksWithinScripts = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinScripts); final int[][] groupNumbersToCaptureLinksWithinTags = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinTags); final Cipher cipher = CryptoUtils.getCipher(); final CryptoKeyAndSalt key = CryptoUtils.generateRandomCryptoKeyAndSalt(false); Cipher.getInstance("AES"); MessageDigest.getInstance("SHA-1"); final ResponseWrapper response = new ResponseWrapper(new ResponseMock(), request, attackHandler, helper, false, "___ENCRYPTED___", cipher, key, "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", false, false, false, false, "123.456.789.000", new HashSet(), prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, false, true, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false, false); final List durations = new ArrayList(); for (int i = 0; i < executionCount; i++) { final long start = System.currentTimeMillis(); Reader reader = null; Writer writer = null; try { reader = new BufferedReader(new FileReader(this.htmlFile)); writer = new FileWriter(this.outputFile); if (applyFilter) { writer = new ResponseFilterWriter(writer, true, "http://127.0.0.1/test/sample", "/test", "/test", "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", cipher, key, helper, "___ENCRYPTED___", request, response, stripHtmlEnabled, injectSecretTokensEnabled, protectParamsAndFormsEnabled, encryptQueryStringsEnabled, applyExtraProtectionForDisabledFormFields, applyExtraProtectionForReadonlyFormFields, applyExtraProtectionForRequestParamValueCount, prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, true, false, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false); writer = new BufferedWriter(writer); } char[] chars = new char[16 * 1024]; int read; while ((read = reader.read(chars)) != -1) { if (read > 0) { writer.write(chars, 0, read); } } durations.add(new Long(System.currentTimeMillis() - start)); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } if (writer != null) { try { writer.close(); } catch (IOException ignored) { } } } } long sum = 0; for (final Iterator iter = durations.iterator(); iter.hasNext(); ) { Long value = (Long) iter.next(); sum += value.longValue(); } return sum / durations.size(); }
00
Code Sample 1: public InputStream getResourceAsStream(String name) { InputStream is = parent.getResourceAsStream(name); if (is == null) { URL url = findResource(name); if (url != null) { try { is = url.openStream(); } catch (IOException e) { is = null; } } } return is; } Code Sample 2: protected synchronized Long putModel(String table, String linkTable, String type, TupleBinding binding, LocatableModel model) { try { if (model.getId() != null && !"".equals(model.getId())) { ps7.setInt(1, Integer.parseInt(model.getId())); ps7.execute(); ps6.setInt(1, Integer.parseInt(model.getId())); ps6.execute(); } if (persistenceMethod == PostgreSQLStore.BYTEA) { ps1.setString(1, model.getContig()); ps1.setInt(2, model.getStartPosition()); ps1.setInt(3, model.getStopPosition()); ps1.setString(4, type); DatabaseEntry objData = new DatabaseEntry(); binding.objectToEntry(model, objData); ps1.setBytes(5, objData.getData()); ps1.executeUpdate(); } else if (persistenceMethod == PostgreSQLStore.OID || persistenceMethod == PostgreSQLStore.FIELDS) { ps1b.setString(1, model.getContig()); ps1b.setInt(2, model.getStartPosition()); ps1b.setInt(3, model.getStopPosition()); ps1b.setString(4, type); DatabaseEntry objData = new DatabaseEntry(); binding.objectToEntry(model, objData); int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE); LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE); obj.write(objData.getData()); obj.close(); ps1b.setInt(5, oid); ps1b.executeUpdate(); } ResultSet rs = null; PreparedStatement ps = conn.prepareStatement("select currval('" + table + "_" + table + "_id_seq')"); rs = ps.executeQuery(); int modelId = -1; if (rs != null) { if (rs.next()) { modelId = rs.getInt(1); } } rs.close(); ps.close(); for (String key : model.getTags().keySet()) { int tagId = -1; if (tags.get(key) != null) { tagId = tags.get(key); } else { ps2.setString(1, key); rs = ps2.executeQuery(); if (rs != null) { while (rs.next()) { tagId = rs.getInt(1); } } rs.close(); } if (tagId < 0) { ps3.setString(1, key); ps3.setString(2, model.getTags().get(key)); ps3.executeUpdate(); rs = ps4.executeQuery(); if (rs != null) { if (rs.next()) { tagId = rs.getInt(1); tags.put(key, tagId); } } rs.close(); } ps5.setInt(1, tagId); ps5.executeUpdate(); } conn.commit(); return (new Long(modelId)); } catch (SQLException e) { try { conn.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } e.printStackTrace(); System.err.println(e.getMessage()); } catch (Exception e) { try { conn.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } e.printStackTrace(); System.err.println(e.getMessage()); } return (null); }
11
Code Sample 1: public int procesar() { int mas = 0; String uriOntologia = "", source = "", uri = ""; String fichOrigenHTML = "", fichOrigenLN = ""; String ficheroOutOWL = ""; md5 firma = null; StringTokenV2 entra = null, entra2 = null, entra3 = null; FileInputStream lengNat = null; BufferedInputStream lengNat2 = null; DataInputStream entradaLenguajeNatural = null; FileWriter salOWL = null; BufferedWriter salOWL2 = null; PrintWriter salidaOWL = null; String sujeto = "", verbo = "", CD = "", CI = "", fraseOrigen = ""; StringTokenV2 token2; boolean bandera = false; OntClass c = null; OntClass cBak = null; String claseTrabajo = ""; String nombreClase = "", nombrePropiedad = "", variasPalabras = ""; int incre = 0, emergencia = 0; String lineaSalida = ""; String[] ontologia = new String[5]; ontologia[0] = "http://www.criado.info/owl/vertebrados_es.owl#"; ontologia[1] = "http://www.w3.org/2001/sw/WebOnt/guide-src/wine#"; ontologia[2] = "http://www.co-ode.org/ontologies/pizza/2005/10/18/pizza.owl#"; ontologia[3] = "http://www.w3.org/2001/sw/WebOnt/guide-src/food#"; ontologia[4] = "http://www.daml.org/2001/01/gedcom/gedcom#"; String[] ontologiaSource = new String[5]; ontologiaSource[0] = this.directorioMapeo + "\\" + "mapeo_vertebrados_es.xml"; ontologiaSource[1] = this.directorioMapeo + "\\" + "mapeo_wine_es.xml"; ontologiaSource[2] = this.directorioMapeo + "\\" + "mapeo_pizza_es.xml"; ontologiaSource[3] = this.directorioMapeo + "\\" + "mapeo_food_es.xml"; ontologiaSource[4] = this.directorioMapeo + "\\" + "mapeo_parentesco_es.xml"; mapeoIdiomas clasesOntologias; try { if ((entrada = entradaFichero.readLine()) != null) { if (entrada.trim().length() > 10) { entrada2 = new StringTokenV2(entrada.trim(), "\""); if (entrada2.isIncluidaSubcadena("<fichero ontologia=")) { ontologiaOrigen = entrada2.getToken(2); fichOrigenHTML = entrada2.getToken(4); fichOrigenLN = entrada2.getToken(6); if (ontologiaOrigen.equals("VERTEBRADOS")) { source = ontologiaSource[0]; uriOntologia = ontologia[0]; } if (ontologiaOrigen.equals("WINE")) { source = ontologiaSource[1]; uriOntologia = ontologia[1]; } if (ontologiaOrigen.equals("PIZZA")) { source = ontologiaSource[2]; uriOntologia = ontologia[2]; } if (ontologiaOrigen.equals("FOOD")) { source = ontologiaSource[3]; uriOntologia = ontologia[3]; } if (ontologiaOrigen.equals("PARENTESCOS")) { source = ontologiaSource[4]; uriOntologia = ontologia[4]; } firma = new md5(uriOntologia, false); clasesOntologias = new mapeoIdiomas(source); uri = ""; ficheroOutOWL = ""; entra2 = new StringTokenV2(fichOrigenHTML, "\\"); int numToken = entra2.getNumeroTokenTotales(); entra = new StringTokenV2(fichOrigenHTML, " "); if (entra.isIncluidaSubcadena(directorioLocal)) { entra = new StringTokenV2(entra.getQuitar(directorioLocal) + "", " "); uri = entra.getCambiar("\\", "/"); uri = entra.getQuitar(entra2.getToken(numToken)) + ""; entra3 = new StringTokenV2(entra2.getToken(numToken), "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; uri = urlPatron + uri + ficheroOutOWL; } entra3 = new StringTokenV2(fichOrigenHTML, "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; lineaSalida = "<vistasemantica origen=\"" + fichOrigenLN + "\" destino=\"" + uri + "\" />"; lengNat = new FileInputStream(fichOrigenLN); lengNat2 = new BufferedInputStream(lengNat); entradaLenguajeNatural = new DataInputStream(lengNat2); salOWL = new FileWriter(ficheroOutOWL); salOWL2 = new BufferedWriter(salOWL); salidaOWL = new PrintWriter(salOWL2); while ((entradaInstancias = entradaLenguajeNatural.readLine()) != null) { sujeto = ""; verbo = ""; CD = ""; CI = ""; fraseOrigen = ""; if (entradaInstancias.trim().length() > 10) { entrada2 = new StringTokenV2(entradaInstancias.trim(), "\""); if (entrada2.isIncluidaSubcadena("<oracion sujeto=")) { sujeto = entrada2.getToken(2).trim(); verbo = entrada2.getToken(4).trim(); CD = entrada2.getToken(6).trim(); CI = entrada2.getToken(8).trim(); fraseOrigen = entrada2.getToken(10).trim(); if (sujeto.length() > 0 & verbo.length() > 0 & CD.length() > 0) { bandera = false; c = null; cBak = null; nombreClase = clasesOntologias.getClaseInstancia(CD); if (nombreClase.length() > 0) { bandera = true; } if (bandera) { if (incre == 0) { salidaOWL.write(" <rdf:RDF " + "\n"); salidaOWL.write(" xmlns:j.0=\"" + uriOntologia + "\"" + "\n"); salidaOWL.write(" xmlns:protege=\"http://protege.stanford.edu/plugins/owl/protege#\"" + "\n"); salidaOWL.write(" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"" + "\n"); salidaOWL.write(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"" + "\n"); salidaOWL.write(" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"" + "\n"); salidaOWL.write(" xmlns:owl=\"http://www.w3.org/2002/07/owl#\" " + "\n"); salidaOWL.write(" xmlns=\"" + uri + "#\"" + "\n"); salidaOWL.write(" xml:base=\"" + uri + "\">" + "\n"); salidaOWL.write(" <owl:Ontology rdf:about=\"\">" + "\n"); salidaOWL.write(" <owl:imports rdf:resource=\"" + uriOntologia + "\"/>" + "\n"); salidaOWL.write(" </owl:Ontology>" + "\n"); salidaOWL.flush(); salida.write(lineaSalida + "\n"); salida.flush(); incre = 1; } salidaOWL.write(" <j.0:" + nombreClase + " rdf:ID=\"" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" <owl:AllDifferent>" + "\n"); salidaOWL.write(" <owl:distinctMembers rdf:parseType=\"Collection\">" + "\n"); salidaOWL.write(" <" + nombreClase + " rdf:about=\"#" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" </owl:distinctMembers>" + "\n"); salidaOWL.write(" </owl:AllDifferent>" + "\n"); salidaOWL.flush(); bandera = false; } } } } } salidaOWL.write(" </rdf:RDF>" + "\n" + "\n"); salidaOWL.write("<!-- Creado por [html2ws] http://www.luis.criado.org -->" + "\n"); salidaOWL.flush(); } } mas = 1; } else { salida.write("</listaVistasSemanticas>\n"); salida.flush(); salida.close(); bw2.close(); fw2.close(); salidaOWL.close(); entradaFichero.close(); ent2.close(); ent1.close(); mas = -1; } } catch (Exception e) { mas = -2; salida.write("No se encuentra: " + fichOrigen + "\n"); salida.flush(); } return mas; } Code Sample 2: @Override public void fileUpload(UploadEvent uploadEvent) { FileOutputStream tmpOutStream = null; try { tmpUpload = File.createTempFile("projectImport", ".xml"); tmpOutStream = new FileOutputStream(tmpUpload); IOUtils.copy(uploadEvent.getInputStream(), tmpOutStream); panel.setGeneralMessage("Project file " + uploadEvent.getFileName() + " uploaded and ready for import."); } catch (Exception e) { panel.setGeneralMessage("Could not upload file: " + e); } finally { if (tmpOutStream != null) { IOUtils.closeQuietly(tmpOutStream); } } }
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: public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file: " + dest.getName()); } } byte[] buffer = new byte[bufSize]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } }
00
Code Sample 1: public void doPreparedStatementQueryAndUpdate(Connection conn, String id) throws SQLException { try { int key = getNextKey(); String bValue = "doPreparedStatementQueryAndUpdate:" + id + ":" + testId; PreparedStatement s1; if (key >= MAX_KEY_VALUE) { key = key % MAX_KEY_VALUE; s1 = conn.prepareStatement("delete from many_threads where a = ?"); s1.setInt(1, key); s1.executeUpdate(); s1.close(); } s1 = conn.prepareStatement("insert into many_threads values (?, ?, 0)"); s1.setInt(1, key); s1.setString(2, bValue); assertEquals(1, s1.executeUpdate()); s1.close(); s1 = conn.prepareStatement("select a from many_threads where a = ?"); s1.setInt(1, key); assertEquals(key, executeQuery(s1)); s1.close(); s1 = conn.prepareStatement("update many_threads set value = a * a, b = b || ? where a = ?"); s1.setString(1, "&" + bValue); s1.setInt(2, key + 1); s1.executeUpdate(); s1.close(); if (!conn.getAutoCommit()) { conn.commit(); } } catch (SQLException e) { if (!conn.getAutoCommit()) { try { conn.rollback(); } catch (SQLException e2) { } } } } Code Sample 2: public static List importSymbol(Report report, Symbol symbol, TradingDate startDate, TradingDate endDate) throws IOException { List quotes = new ArrayList(); String URLString = constructURL(symbol, startDate, endDate); QuoteFilter filter = new YahooQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { Quote quote = filter.toQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("YAHOO") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); throw new IOException(); } catch (ConnectException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); throw new IOException(); } catch (UnknownHostException e) { DesktopManager.showErrorMessage(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); throw new IOException(); } catch (NoRouteToHostException e) { DesktopManager.showErrorMessage(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); throw new IOException(); } catch (MalformedURLException e) { DesktopManager.showErrorMessage(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); throw new IOException(); } catch (FileNotFoundException e) { report.addError(Locale.getString("YAHOO") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + Locale.getString("NO_QUOTES_FOUND")); } catch (IOException e) { DesktopManager.showErrorMessage(Locale.getString("ERROR_DOWNLOADING_QUOTES")); throw new IOException(); } return quotes; }
11
Code Sample 1: protected static String encodePassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); return HexString.bufferToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } Code Sample 2: private StringBuffer hashPassword(StringBuffer password, String mode) { MessageDigest m = null; StringBuffer hash = new StringBuffer(); try { m = MessageDigest.getInstance(mode); m.update(password.toString().getBytes("UTF8")); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] digest = m.digest(); for (int i = 0; i < digest.length; i++) { String hex = Integer.toHexString(digest[i]); if (hex.length() == 1) hex = "0" + hex; hex = hex.substring(hex.length() - 2); hash.append(hex); } return hash; }
11
Code Sample 1: public void handleRequestInternal(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws ServletException, IOException { final String servetPath = httpServletRequest.getServletPath(); final String previousToken = httpServletRequest.getHeader(IF_NONE_MATCH); final String currentToken = getETagValue(httpServletRequest); httpServletResponse.setHeader(ETAG, currentToken); final Date modifiedDate = new Date(httpServletRequest.getDateHeader(IF_MODIFIED_SINCE)); final Calendar calendar = Calendar.getInstance(); final Date now = calendar.getTime(); calendar.setTime(modifiedDate); calendar.add(Calendar.MINUTE, getEtagExpiration()); if (currentToken.equals(previousToken) && (now.getTime() < calendar.getTime().getTime())) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_MODIFIED); httpServletResponse.setHeader(LAST_MODIFIED, httpServletRequest.getHeader(IF_MODIFIED_SINCE)); if (LOG.isDebugEnabled()) { LOG.debug("ETag the same, will return 304"); } } else { httpServletResponse.setDateHeader(LAST_MODIFIED, (new Date()).getTime()); final String width = httpServletRequest.getParameter(Constants.WIDTH); final String height = httpServletRequest.getParameter(Constants.HEIGHT); final ImageNameStrategy imageNameStrategy = imageService.getImageNameStrategy(servetPath); String code = imageNameStrategy.getCode(servetPath); String fileName = imageNameStrategy.getFileName(servetPath); final String imageRealPathPrefix = getRealPathPrefix(httpServletRequest.getServerName().toLowerCase()); String original = imageRealPathPrefix + imageNameStrategy.getFullFileNamePath(fileName, code); final File origFile = new File(original); if (!origFile.exists()) { code = Constants.NO_IMAGE; fileName = imageNameStrategy.getFileName(code); original = imageRealPathPrefix + imageNameStrategy.getFullFileNamePath(fileName, code); } String resizedImageFileName = null; if (width != null && height != null && imageService.isSizeAllowed(width, height)) { resizedImageFileName = imageRealPathPrefix + imageNameStrategy.getFullFileNamePath(fileName, code, width, height); } final File imageFile = getImageFile(original, resizedImageFileName, width, height); final FileInputStream fileInputStream = new FileInputStream(imageFile); IOUtils.copy(fileInputStream, httpServletResponse.getOutputStream()); fileInputStream.close(); } } Code Sample 2: public void xtestURL1() throws Exception { URL url = new URL(IOTest.URL); InputStream inputStream = url.openStream(); OutputStream outputStream = new FileOutputStream("C:/Temp/testURL1.mp4"); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); }
11
Code Sample 1: public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private void unzipData(ZipFile zipfile, ZipEntry entry) { if (entry.getName().equals("backUpExternalInfo.out")) { File outputFile = new File("temp", entry.getName()); if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } try { BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (IOException e) { throw new BackupException(e.getMessage()); } } }
00
Code Sample 1: @Override public DaeScene loadScene(URL url) throws IOException, IncorrectFormatException, ParsingErrorException { NullArgumentException.check(url); boolean baseURLWasNull = setBaseURLFromModelURL(url); DaeScene scene = loadScene(url.openStream()); if (baseURLWasNull) { popBaseURL(); } return (scene); } Code Sample 2: public Long processAddCompany(Company companyBean, String userLogin, Long holdingId, AuthSession authSession) { if (authSession == null) { return null; } PreparedStatement ps = null; DatabaseAdapter dbDyn = null; try { dbDyn = DatabaseAdapter.getInstance(); CustomSequenceType seq = new CustomSequenceType(); seq.setSequenceName("seq_WM_LIST_COMPANY"); seq.setTableName("WM_LIST_COMPANY"); seq.setColumnName("ID_FIRM"); Long sequenceValue = dbDyn.getSequenceNextValue(seq); ps = dbDyn.prepareStatement("insert into WM_LIST_COMPANY (" + " ID_FIRM, " + " full_name, " + " short_name, " + " address, " + " telefon_buh, " + " telefon_chief, " + " chief, " + " buh, " + " fax, " + " email, " + " icq, " + " short_client_info, " + " url, " + " short_info, " + "is_deleted" + ")" + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + " select " + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?,0 from WM_AUTH_USER " + "where USER_LOGIN=? " + (dbDyn.getIsNeedUpdateBracket() ? ")" : "")); int num = 1; RsetTools.setLong(ps, num++, sequenceValue); ps.setString(num++, companyBean.getName()); ps.setString(num++, companyBean.getShortName()); ps.setString(num++, companyBean.getAddress()); ps.setString(num++, ""); ps.setString(num++, ""); ps.setString(num++, companyBean.getCeo()); ps.setString(num++, companyBean.getCfo()); ps.setString(num++, ""); ps.setString(num++, ""); RsetTools.setLong(ps, num++, null); ps.setString(num++, ""); ps.setString(num++, companyBean.getWebsite()); ps.setString(num++, companyBean.getInfo()); ps.setString(num++, userLogin); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of inserted records - " + i1); if (holdingId != null) { InternalDaoFactory.getInternalHoldingDao().setRelateHoldingCompany(dbDyn, holdingId, sequenceValue); } dbDyn.commit(); return sequenceValue; } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error add new company"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
11
Code Sample 1: public static void copyAFile(final String entree, final String sortie) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(entree).getChannel(); out = new FileOutputStream(sortie).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } Code Sample 2: private void copy(File fromFile, File toFile) throws IOException { String fromFileName = fromFile.getName(); File tmpFile = new File(fromFileName); String toFileName = toFile.getName(); if (!tmpFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!tmpFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!tmpFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(tmpFile); File toF = new File(toFile.getCanonicalPath()); if (!toF.exists()) ; toF.createNewFile(); if (!SBCMain.DEBUG_MODE) to = new FileOutputStream(toFile); else to = new FileOutputStream(toF); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
11
Code Sample 1: public void downloadFile(OutputStream os, int fileId) throws IOException, SQLException { Connection conn = null; try { conn = ds.getConnection(); Guard.checkConnectionNotNull(conn); PreparedStatement ps = conn.prepareStatement("select * from FILE_BODIES where file_id=?"); ps.setInt(1, fileId); ResultSet rs = ps.executeQuery(); if (!rs.next()) { throw new FileNotFoundException("File with id=" + fileId + " not found!"); } Blob blob = rs.getBlob("data"); InputStream is = blob.getBinaryStream(); IOUtils.copyLarge(is, os); } finally { JdbcDaoHelper.safeClose(conn, log); } } Code Sample 2: public static final void main(String[] args) throws FileNotFoundException, IOException { ArrayList<String[]> result = new ArrayList<String[]>(); IStream is = new StreamImpl(); IOUtils.copy(new FileInputStream("H:\\7-项目预算表.xlsx"), is.getOutputStream()); int count = loadExcel(result, is, 0, 0, -1, 16, 1); System.out.println(count); for (String[] rs : result) { for (String r : rs) { System.out.print(r + "\t"); } System.out.println(); } }
00
Code Sample 1: public static void bubbleSort(Drawable[] list) { boolean swapped; do { swapped = false; for (int i = 0; i < list.length - 1; ++i) { if (list[i].getSortValue() > list[i + 1].getSortValue()) { Drawable temp = list[i]; list[i] = list[i + 1]; list[i + 1] = temp; swapped = true; } } } while (swapped); } Code Sample 2: public static String MD5(String source) { logger.info(source); String result = null; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(source.getBytes()); byte[] bytes = digest.digest(); result = EncodeUtils.hexEncode(bytes); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } logger.info(result); return result; }
00
Code Sample 1: public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { BufferedReader reader; if (baseUrl == null) setBaseUrlFromUrl(url); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); } catch (IOException e) { throw new FileNotFoundException(e.getMessage()); } fromUrl = true; return load(reader); } Code Sample 2: public String get(String url) { String buf = null; StringBuilder resultBuffer = new StringBuilder(512); if (debug.DEBUG) debug.logger("gov.llnl.tox.util.href", "get(url)>> " + url); try { URL theURL = new URL(url); URLConnection urlConn = theURL.openConnection(); urlConn.setDoOutput(true); urlConn.setReadTimeout(timeOut); BufferedReader urlReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); do { buf = urlReader.readLine(); if (buf != null) { resultBuffer.append(buf); resultBuffer.append("\n"); } } while (buf != null); urlReader.close(); if (debug.DEBUG) debug.logger("gov.llnl.tox.util.href", "get(output)>> " + resultBuffer.toString()); int xmlNdx = resultBuffer.lastIndexOf("?>"); if (xmlNdx == -1) result = resultBuffer.toString(); else result = resultBuffer.substring(xmlNdx + 2); } catch (Exception e) { result = debug.logger("gov.llnl.tox.util.href", "error: get >> ", e); } return (result); }
00
Code Sample 1: public static void processRequest(byte[] b) throws Exception { URL url = new URL("http://localhost:8080/instantsoap-ws-echotest-1.0/services/instantsoap/applications"); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); httpConn.setRequestProperty("SOAPAction", ""); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); OutputStream out = httpConn.getOutputStream(); out.write(b); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } Code Sample 2: void loadImage(final int runnumber, final String surl, final StatusCallback status) { Runnable run = new Runnable() { public void run() { try { if (sync == SyncType.SyncSpaced || sync == SyncType.Spaced) { Thread.sleep(spaceMillis); } URL url = new URL(surl + "&requestId=" + runnumber); long t0 = System.currentTimeMillis(); InputStream in = url.openStream(); transfer(in, new FileOutputStream(new File(outputFolder, "" + runnumber + ".png"))); BufferedImage image = ImageIO.read(new File(outputFolder, "" + runnumber + ".png")); status.score(runnumber, System.currentTimeMillis() - t0); ImageIO.write(image, "png", new FileOutputStream(new File(outputFolder, "" + runnumber + ".png"))); if (false) { int whiteCount = 0; for (int i = 0; i < image.getWidth(); i++) { for (int j = 0; j < image.getHeight(); j++) { whiteCount += image.getRGB(i, j) == -1 ? 1 : 0; } } System.err.println("##" + runnumber + "#: " + whiteCount); if (whiteCount < 227564) { System.err.println("whiteCount fails!!!!"); System.err.println("whiteCount fails!!!!"); System.exit(0); } } } catch (Exception ex) { System.err.println("##" + runnumber + "#: Exception!!! ###"); ex.printStackTrace(); status.score(runnumber, -999); } } }; if (sync == SyncType.SyncSpaced || sync == SyncType.Sync) { run.run(); } else { new Thread(run).start(); } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public void Copy() throws IOException { if (!FileDestination.exists()) { FileDestination.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(FileSource).getChannel(); destination = new FileOutputStream(FileDestination).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
11
Code Sample 1: public boolean executeUpdate(String strSql, HashMap<Integer, Object> prams) throws SQLException, ClassNotFoundException { getConnection(); boolean flag = false; try { pstmt = con.prepareStatement(strSql); setParamet(pstmt, prams); logger.info("###############::执行SQL语句操作(更新数据 有参数):" + strSql); if (0 < pstmt.executeUpdate()) { close_DB_Object(); flag = true; con.commit(); } } catch (SQLException ex) { logger.info("###############Error DBManager Line121::执行SQL语句操作(更新数据 无参数):" + strSql + "失败!"); flag = false; con.rollback(); throw ex; } catch (ClassNotFoundException ex) { logger.info("###############Error DBManager Line152::执行SQL语句操作(更新数据 无参数):" + strSql + "失败! 参数设置类型错误!"); con.rollback(); throw ex; } return flag; } Code Sample 2: public static void process(PricesType prices, Long id_site, DatabaseAdapter dbDyn) throws PriceException { PreparedStatement ps = null; String sql_ = null; PriceListItemType debugItem = null; try { if (log.isDebugEnabled()) { log.debug("dbDyn - " + dbDyn); if (dbDyn != null) log.debug("dbDyn.conn - " + dbDyn.getConnection()); } dbDyn.getConnection().setAutoCommit(false); if (dbDyn.getFamaly() != DatabaseManager.MYSQL_FAMALY) { sql_ = "delete from WM_PRICE_IMPORT_TABLE where shop_code in " + "( select shop_code from WM_PRICE_SHOP_LIST where ID_SITE=? )"; ps = dbDyn.prepareStatement(sql_); RsetTools.setLong(ps, 1, id_site); ps.executeUpdate(); ps.close(); ps = null; } else { String sqlCheck = ""; boolean isFound = false; WmPriceShopListListType shops = GetWmPriceShopListWithIdSiteList.getInstance(dbDyn, id_site).item; boolean isFirst = true; for (int i = 0; i < shops.getWmPriceShopListCount(); i++) { WmPriceShopListItemType shop = shops.getWmPriceShopList(i); isFound = true; if (isFirst) isFirst = false; else sqlCheck += ","; sqlCheck += ("'" + shop.getCodeShop() + "'"); } if (isFound) { sql_ = "delete from WM_PRICE_IMPORT_TABLE where shop_code in ( " + sqlCheck + " )"; if (log.isDebugEnabled()) log.debug("sql " + sql_); ps = dbDyn.prepareStatement(sql_); ps.executeUpdate(); ps.close(); ps = null; } } if (log.isDebugEnabled()) log.debug("Start unmarshalling data"); if (prices == null) throw new PriceException("������ ������� ����� �������. ��� ������ #10.03"); int batchLoop = 0; int count = 0; sql_ = "insert into WM_PRICE_IMPORT_TABLE " + "(is_group, id, id_main, name, price, currency, is_to_load, shop_code, ID_UPLOAD_PRICE) " + "values (?,?,?,?,?,?,?,?,?)"; Long id_upload_session = null; for (int j = 0; j < prices.getPriceListCount(); j++) { PriceListType price = prices.getPriceList(j); if (log.isDebugEnabled()) { log.debug("shopCode " + price.getShopCode()); log.debug("Size vector: " + price.getItemCount()); } for (int i = 0; (i < price.getItemCount()) && (count < 5000); i++, count++) { if (ps == null) ps = dbDyn.prepareStatement(sql_); PriceListItemType item = price.getItem(i); debugItem = item; ps.setInt(1, Boolean.TRUE.equals(item.getIsGroup()) ? 1 : 0); RsetTools.setLong(ps, 2, item.getItemID()); RsetTools.setLong(ps, 3, item.getParentID()); ps.setString(4, item.getNameItem()); RsetTools.setDouble(ps, 5, item.getPrice()); ps.setString(6, item.getCurr()); ps.setString(7, item.getIsLoad().toString()); ps.setString(8, price.getShopCode().toUpperCase()); RsetTools.setLong(ps, 9, id_upload_session); if (dbDyn.getIsBatchUpdate()) { ps.addBatch(); if (++batchLoop >= 200) { int[] updateCounts = ps.executeBatch(); ps.close(); ps = null; batchLoop = 0; } } else ps.executeUpdate(); } } if (dbDyn.getIsBatchUpdate()) { if (ps != null) { int[] updateCounts = ps.executeBatch(); ps.close(); ps = null; } } ImportPriceProcess.process(dbDyn, id_site); dbDyn.commit(); } catch (Exception e) { if (debugItem != null) { log.error("debugItem.getIsGroup() " + (Boolean.TRUE.equals(debugItem.getIsGroup()) ? 1 : 0)); log.error("debugItem.getItemID() " + debugItem.getItemID()); log.error("debugItem.getParentID() " + debugItem.getParentID()); log.error("debugItem.getNameItem() " + debugItem.getNameItem()); log.error("debugItem.getPrice() " + debugItem.getPrice()); log.error("debugItem.getCurr() " + debugItem.getCurr()); log.error("debugItem.getIsLoad().toString() " + debugItem.getIsLoad().toString()); } else log.error("debugItem is null"); log.error("sql:\n" + sql_); final String es = "error process import price-list"; log.error(es, e); try { dbDyn.rollback(); } catch (Exception e11) { } throw new PriceException(es, e); } finally { DatabaseManager.close(ps); ps = null; } }
00
Code Sample 1: public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { String bundleName = toBundleName(baseName, locale); String resourceName = toResourceName(bundleName, "properties"); ResourceBundle bundle = null; InputStream stream = null; if (reload) { URL url = loader.getResource(resourceName); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { connection.setUseCaches(false); stream = connection.getInputStream(); } } } else { stream = loader.getResourceAsStream(resourceName); } if (stream != null) { try { bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8")); } finally { stream.close(); } } return bundle; } Code Sample 2: public DataSet(String name, String type, URL docBase, String plotDir) { sitename = name.toUpperCase(); data = new Vector[3]; data[0] = new Vector(); data[1] = new Vector(); data[2] = new Vector(); if (type == null) return; plottype = type.toLowerCase(); String filename; filename = plotDir + sitename + "_" + plottype + ".plt.gz"; try { double total = 0; URL dataurl = new URL(docBase, filename); BufferedReader readme = new BufferedReader(new InputStreamReader(new GZIPInputStream(dataurl.openStream()))); while (true) { String myline = readme.readLine(); if (myline == null) break; myline = myline.toLowerCase(); if (myline.startsWith("fit:")) { if (haveFit) { continue; } StringTokenizer st = new StringTokenizer(myline.replace('\n', ' ')); fit = new Double[5]; String bye = (String) st.nextToken(); fit[0] = new Double((String) st.nextToken()); fit[1] = new Double((String) st.nextToken()); fit[2] = new Double((String) st.nextToken()); fit[3] = new Double((String) st.nextToken()); fit[4] = new Double((String) st.nextToken()); haveFit = true; continue; } if (myline.startsWith("decyear:")) { StringTokenizer st = new StringTokenizer(myline.replace('\n', ' ')); String bye = (String) st.nextToken(); decYear = new Double((String) st.nextToken()); haveDate = true; continue; } StringTokenizer st = new StringTokenizer(myline.replace('\n', ' ')); boolean ok = true; String tmp; Double[] mydbl = new Double[3]; for (int i = 0; i < 3 && ok; i++) { if (st.hasMoreTokens()) { tmp = (String) st.nextToken(); if (tmp.startsWith("X") || tmp.startsWith("x")) { ok = false; break; } else { mydbl[i] = new Double(tmp); } } else { mydbl[i] = new Double(0.0); } } if (ok) { if (mydbl[2].doubleValue() > 100) continue; total = mydbl[1].doubleValue() + total; for (int i = 0; i < 3; i++) { data[i].addElement(mydbl[i]); } } } average = total / length(); } catch (FileNotFoundException e) { System.err.println("PlotApplet: file not found: " + e); } catch (IOException e) { System.err.println("PlotApplet: error reading input file: " + e); } }
00
Code Sample 1: protected String insertCommand(String command) throws ServletException { String digest; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(command.getBytes()); byte bytes[] = new byte[20]; m_random.nextBytes(bytes); md.update(bytes); digest = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to generate graph ID: " + e); } String id = System.currentTimeMillis() + "-" + digest; m_map.put(id, command); return id; } Code Sample 2: @Override protected ResourceHandler doGet(final URI resourceUri) throws ResourceException { if (resourceUri.getHost() == null) { throw new IllegalStateException(InternalBundleHelper.StoreMessageBundle.getMessage("store.uri.ftp.illegal", resourceUri.toString())); } try { final URL configUrl = resourceUri.toURL(); final URLConnection urlConnection; Proxy httpProxy = null; if (!StringHelper.isEmpty(context.getString(FileStoreContextBuilder.ProxySet))) { if (context.getBoolean(FileStoreContextBuilder.ProxySet)) { final String proxyHost = context.getString(FileStoreContextBuilder.ProxyHost); final String proxyPort = context.getString(FileStoreContextBuilder.ProxyPort); if (!StringHelper.isEmpty(proxyHost)) { httpProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, !StringHelper.isEmpty(proxyPort) ? Integer.parseInt(proxyPort) : 80)); if (!StringHelper.isEmpty(context.getString(FileStoreContextBuilder.NonProxyHosts))) { System.getProperties().put("ftp.nonProxyHosts", context.getProperty(FileStoreContextBuilder.NonProxyHosts)); } if (!StringHelper.isEmpty(context.getString(FileStoreContextBuilder.ProxyUser)) && !StringHelper.isEmpty(context.getString(FileStoreContextBuilder.ProxyPassword))) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(context.getString(FileStoreContextBuilder.ProxyUser), context.getString(FileStoreContextBuilder.ProxyPassword).toCharArray()); } }); } } } } if (httpProxy == null) { urlConnection = configUrl.openConnection(); } else { urlConnection = configUrl.openConnection(httpProxy); } setUrlConnectionSettings(urlConnection); urlConnection.connect(); try { return createResourceHandler(resourceUri.toString(), urlConnection.getInputStream()); } catch (final FileNotFoundException fnfe) { throw new ResourceNotFoundException(resourceUri.toString()); } } catch (final MalformedURLException mure) { throw new IllegalStateException(InternalBundleHelper.StoreMessageBundle.getMessage("store.uri.malformed", resourceUri.toString())); } catch (final ConnectException ce) { throw new ResourceException("store.connection.error", ce, resourceUri.toString()); } catch (final IOException ioe) { if (ioe instanceof ResourceException) { throw (ResourceException) ioe; } else { throw new ResourceException(ioe, resourceUri.toString()); } } }
11
Code Sample 1: void copyFileOnPeer(String path, RServerInfo peerserver, boolean allowoverwrite) throws IOException { RFile file = new RFile(path); OutputStream out = null; FileInputStream in = null; try { in = fileManager.openFileRead(path); out = localClient.openWrite(file, false, WriteMode.TRANSACTED, 1, peerserver, !allowoverwrite); IOUtils.copyLarge(in, out); out.close(); out = null; } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (out != null) { try { out.close(); } catch (Throwable t) { } } } } Code Sample 2: public boolean copyFile(File source, File dest) { try { FileReader in = new FileReader(source); FileWriter out = new FileWriter(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return true; } catch (Exception e) { return false; } }
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 static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: public static String getMD5Str(String source) { String s = null; char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(source.getBytes()); byte tmp[] = md.digest(); char str[] = new char[16 * 2]; int k = 0; for (int i = 0; i < 16; i++) { byte byte0 = tmp[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } s = new String(str); } catch (Exception e) { e.printStackTrace(); } return s; } Code Sample 2: public void sendRequest(String method) { try { url = new URL(urlStr); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod(method); httpURLConnection.setDoOutput(true); httpURLConnection.getOutputStream().flush(); httpURLConnection.getOutputStream().close(); System.out.println(httpURLConnection.getResponseMessage()); } catch (Exception e) { e.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } } }
00
Code Sample 1: public void alterarQuestaoDiscursiva(QuestaoDiscursiva q) throws SQLException { PreparedStatement stmt = null; String sql = "UPDATE discursiva SET gabarito=? WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setString(1, q.getGabarito()); stmt.setInt(2, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } } Code Sample 2: public boolean loadURL(URL url) { try { _properties.load(url.openStream()); Argo.log.info("Configuration loaded from " + url + "\n"); return true; } catch (Exception e) { if (_canComplain) Argo.log.warn("Unable to load configuration " + url + "\n"); _canComplain = false; return false; } }
00
Code Sample 1: public String getDigest(String s) throws Exception { MessageDigest md = MessageDigest.getInstance(hashName); md.update(s.getBytes()); byte[] dig = md.digest(); return Base16.toHexString(dig); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: private void chopFileDisk() throws IOException { File tempFile = new File("" + logFile + ".tmp"); BufferedInputStream bis = null; BufferedOutputStream bos = null; long startCopyPos; byte readBuffer[] = new byte[2048]; int readCount; long totalBytesRead = 0; if (reductionRatio > 0 && logFile.length() > 0) { startCopyPos = logFile.length() / reductionRatio; } else { startCopyPos = 0; } try { bis = new BufferedInputStream(new FileInputStream(logFile)); bos = new BufferedOutputStream(new FileOutputStream(tempFile)); do { readCount = bis.read(readBuffer, 0, readBuffer.length); if (readCount > 0) { totalBytesRead += readCount; if (totalBytesRead > startCopyPos) { bos.write(readBuffer, 0, readCount); } } } while (readCount > 0); } finally { if (bos != null) { try { bos.close(); } catch (IOException ex) { } } if (bis != null) { try { bis.close(); } catch (IOException ex) { } } } if (tempFile.isFile()) { if (!logFile.delete()) { throw new IOException("Error when attempting to delete the " + logFile + " file."); } if (!tempFile.renameTo(logFile)) { throw new IOException("Error when renaming the " + tempFile + " to " + logFile + "."); } } } Code Sample 2: private void copy(File inputFile, File outputFile) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); while (reader.ready()) { writer.write(reader.readLine()); writer.write(System.getProperty("line.separator")); } } catch (IOException e) { } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e1) { } } }
11
Code Sample 1: public void setBckImg(String newPath) { try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = null; try { out = new FileOutputStream(outputFile); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } int c; if (out != null) { while ((c = in.read()) != -1) out.write(c); out.close(); } in.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } setPath(newPath); bckImg = new ImageIcon(getPath()); } Code Sample 2: private String transferWSDL(String wsdlURL, String userPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (userPassword != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(userPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDeployDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; }
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: private void fileMaker() { try { long allData = 0; double a = 10; int range = 0; int blockLength = 0; File newFile = new File(mfr.getFilename() + ".part"); if (newFile.exists()) { newFile.delete(); } ArrayList<DataRange> rangeList = null; byte[] data = null; newFile.createNewFile(); ByteBuffer buffer = ByteBuffer.allocate(mfr.getBlocksize()); FileChannel rChannel = new FileInputStream(inputFileName).getChannel(); FileChannel wChannel = new FileOutputStream(newFile, true).getChannel(); System.out.println(); System.out.print("File completion: "); System.out.print("|----------|"); openConnection(); http.getResponseHeader(); for (int i = 0; i < fileMap.length; i++) { fileOffset = fileMap[i]; if (fileOffset != -1) { rChannel.read(buffer, fileOffset); buffer.flip(); wChannel.write(buffer); buffer.clear(); } else { if (!rangeQueue) { rangeList = rangeLookUp(i); range = rangeList.size(); openConnection(); http.setRangesRequest(rangeList); http.sendRequest(); http.getResponseHeader(); data = http.getResponseBody(mfr.getBlocksize()); allData += http.getAllTransferedDataLength(); } if ((i * mfr.getBlocksize() + mfr.getBlocksize()) < mfr.getLength()) { blockLength = mfr.getBlocksize(); } else { blockLength = (int) ((int) (mfr.getBlocksize()) + (mfr.getLength() - (i * mfr.getBlocksize() + mfr.getBlocksize()))); } buffer.put(data, (range - rangeList.size()) * mfr.getBlocksize(), blockLength); buffer.flip(); wChannel.write(buffer); buffer.clear(); rangeList.remove(0); if (rangeList.isEmpty()) { rangeQueue = false; } } if ((((double) i / ((double) fileMap.length - 1)) * 100) >= a) { progressBar(((double) i / ((double) fileMap.length - 1)) * 100); a += 10; } } newFile.setLastModified(getMTime()); sha = new SHA1(newFile); if (sha.SHA1sum().equals(mfr.getSha1())) { System.out.println("\nverifying download...checksum matches OK"); System.out.println("used " + (mfr.getLength() - (mfr.getBlocksize() * missing)) + " " + "local, fetched " + (mfr.getBlocksize() * missing)); new File(mfr.getFilename()).renameTo(new File(mfr.getFilename() + ".zs-old")); newFile.renameTo(new File(mfr.getFilename())); allData += mfr.getLengthOfMetafile(); System.out.println("really downloaded " + allData); double overhead = ((double) (allData - (mfr.getBlocksize() * missing)) / ((double) (mfr.getBlocksize() * missing))) * 100; System.out.println("overhead: " + df.format(overhead) + "%"); } else { System.out.println("\nverifying download...checksum don't match"); System.out.println("Deleting temporary file"); newFile.delete(); System.exit(1); } } catch (IOException ex) { System.out.println("Can't read or write, check your permissions."); System.exit(1); } }
00
Code Sample 1: private void checkUrl(URL url) throws IOException { File urlFile = new File(url.getFile()); assertEquals(file.getCanonicalPath(), urlFile.getCanonicalPath()); System.out.println("Using url " + url); InputStream openStream = url.openStream(); assertNotNull(openStream); } Code Sample 2: private static InputStream openStream(final URL url) throws IOException { try { return (InputStream) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws IOException { return url.openStream(); } }); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } }
11
Code Sample 1: public static String encodePassword(String password) { try { MessageDigest messageDiegest = MessageDigest.getInstance("SHA-1"); messageDiegest.update(password.getBytes("UTF-8")); return Base64.encodeToString(messageDiegest.digest(), false); } catch (NoSuchAlgorithmException e) { log.error("Exception while encoding password"); throw new Error(e); } catch (UnsupportedEncodingException e) { log.error("Exception while encoding password"); throw new Error(e); } } Code Sample 2: public void test_calculateLastModifiedSizeContent() { File file; String content = "Hello, world!"; String expected; FileETag etag; try { file = File.createTempFile("temp", "txt"); file.deleteOnExit(); FileOutputStream out = new FileOutputStream(file); out.write(content.getBytes()); out.flush(); out.close(); SimpleDateFormat date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); long lastModified = date.parse("06/21/2007 11:19:36").getTime(); file.setLastModified(lastModified); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(content.getBytes()); StringBuffer buffer = new StringBuffer(); buffer.append(lastModified); buffer.append(content.length()); expected = new String(Hex.encodeHex(messageDigest.digest(buffer.toString().getBytes()))); etag = new FileETag(); etag.setFlags(FileETag.FLAG_CONTENT | FileETag.FLAG_MTIME | FileETag.FLAG_SIZE); String value = etag.calculate(file); assertEquals("Unexpected value", expected, value); } catch (FileNotFoundException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (IOException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (ParseException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); fail("Unexpected exception"); } }
11
Code Sample 1: public boolean backup() { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/data/android.bluebox/databases/bluebox.db"; String backupDBPath = "/Android/bluebox.bak"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); return true; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } Code Sample 2: public boolean copy(String file, String target, int tag) { try { File file_in = new File(file); File file_out = new File(target); File parent = file_out.getParentFile(); parent.mkdirs(); FileInputStream in1 = new FileInputStream(file_in); FileOutputStream out1 = new FileOutputStream(file_out); byte[] bytes = new byte[1024]; int c; while ((c = in1.read(bytes)) != -1) out1.write(bytes, 0, c); in1.close(); out1.close(); return true; } catch (Exception e) { e.printStackTrace(); System.out.println("Error!"); return false; } }
00
Code Sample 1: public HashSet<String> queryResource(String resourceName, String propertyName) { if (resourceName.startsWith("http://dbpedia.org/resource/")) { resourceName = resourceName.substring(28); } try { resourceName = resourceName.trim().replace(' ', '_'); resourceName = URLEncoder.encode(resourceName, "UTF-8"); } catch (UnsupportedEncodingException exc) { } String select = prefix + " SELECT ?hasValue WHERE { { " + "<http://dbpedia.org/resource/" + resourceName + "> " + propertyName + " ?hasValue } FILTER (lang(?hasValue) = \"" + lang + "\" || !isLiteral(?hasValue))}"; System.out.println(select); HashSet<String> values = new HashSet<String>(); try { URL url = new URL(queryBase + URLEncoder.encode(select, "UTF-8")); InputStream inStream = url.openStream(); Document doc = docBuild.parse(inStream); Element table = doc.getDocumentElement(); NodeList rows = table.getElementsByTagName("tr"); for (int i = 0; i < rows.getLength(); i++) { Element row = (Element) rows.item(i); NodeList cols = row.getElementsByTagName("td"); if (cols.getLength() > 0) { Element valElem = (Element) cols.item(0); String value = ((Text) valElem.getFirstChild()).getData(); if (value.startsWith("http://dbpedia.org/resource/")) { value = value.substring(28).replaceAll("_", " "); } else if (value.startsWith("http://dbpedia.org/ontology/")) { value = value.substring(28).replaceAll("_", " "); } else if (value.startsWith("http://dbpedia.org/class/yago/")) { value = value.substring(30); value = value.split("[\\d]+")[0]; } values.add(value); } } } catch (UnsupportedEncodingException exc) { exc.printStackTrace(); } catch (IOException exc) { System.err.println("Cannot retrieve record for " + resourceName); } catch (SAXException exc) { System.err.println("Cannot parse record for " + resourceName); } return values; } Code Sample 2: 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); } }
00
Code Sample 1: public String getMD5String(String par1Str) { try { String s = (new StringBuilder()).append(field_27370_a).append(par1Str).toString(); MessageDigest messagedigest = MessageDigest.getInstance("MD5"); messagedigest.update(s.getBytes(), 0, s.length()); return (new BigInteger(1, messagedigest.digest())).toString(16); } catch (NoSuchAlgorithmException nosuchalgorithmexception) { throw new RuntimeException(nosuchalgorithmexception); } } Code Sample 2: public void setBckImg(String newPath) { try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = null; try { out = new FileOutputStream(outputFile); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } int c; if (out != null) { while ((c = in.read()) != -1) out.write(c); out.close(); } in.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } setPath(newPath); bckImg = new ImageIcon(getPath()); }
00
Code Sample 1: private boolean doesURLExists(String programURIStr) throws Exception { boolean retVal = true; TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); URL url = new URL(programURIStr); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setConnectTimeout(30000); urlConn.connect(); log.debug("HTTP Status code: " + urlConn.getResponseCode() + " for URL: " + programURIStr); if (HttpURLConnection.HTTP_OK != urlConn.getResponseCode()) { urlConn.disconnect(); throw new Exception("HTTP status code " + urlConn.getResponseCode() + " for " + programURIStr); } urlConn.disconnect(); return retVal; } Code Sample 2: private static void copyFile(File src, File dst) throws IOException { FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dst).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); }
00
Code Sample 1: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); } Code Sample 2: public static String hash(String plainTextPwd) { MessageDigest hashAlgo; try { hashAlgo = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new QwickException(e); } hashAlgo.update(plainTextPwd.getBytes()); return new String(hashAlgo.digest()); }
11
Code Sample 1: public void createIndex(File indexDir) throws SearchLibException, IOException { if (!indexDir.mkdir()) throw new SearchLibException("directory creation failed (" + indexDir + ")"); InputStream is = null; FileWriter target = null; for (String resource : resources) { String res = rootPath + '/' + resource; is = getClass().getResourceAsStream(res); if (is == null) is = getClass().getResourceAsStream("common" + '/' + resource); if (is == null) throw new SearchLibException("Unable to find resource " + res); try { File f = new File(indexDir, resource); if (f.getParentFile() != indexDir) f.getParentFile().mkdirs(); target = new FileWriter(f); IOUtils.copy(is, target); } finally { if (target != null) target.close(); if (is != null) is.close(); } } } Code Sample 2: private static boolean genMovieRatingFile(String completePath, String masterFile, String CustLocationsFileName, String MovieRatingFileName) { try { File inFile1 = new File(completePath + fSep + "SmartGRAPE" + fSep + masterFile); FileChannel inC1 = new FileInputStream(inFile1).getChannel(); int fileSize1 = (int) inC1.size(); int totalNoDataRows = fileSize1 / 7; ByteBuffer mappedBuffer = inC1.map(FileChannel.MapMode.READ_ONLY, 0, fileSize1); System.out.println("Loaded master binary file"); File inFile2 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustLocationsFileName); FileChannel inC2 = new FileInputStream(inFile2).getChannel(); int fileSize2 = (int) inC2.size(); System.out.println(fileSize2); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieRatingFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); for (int i = 0; i < 1; i++) { ByteBuffer locBuffer = inC2.map(FileChannel.MapMode.READ_ONLY, i * fileSize2, fileSize2); System.out.println("Loaded cust location file chunk: " + i); while (locBuffer.hasRemaining()) { int locationToRead = locBuffer.getInt(); mappedBuffer.position((locationToRead - 1) * 7); short movieName = mappedBuffer.getShort(); int customer = mappedBuffer.getInt(); byte rating = mappedBuffer.get(); ByteBuffer outBuf = ByteBuffer.allocate(3); outBuf.putShort(movieName); outBuf.put(rating); outBuf.flip(); outC.write(outBuf); } } mappedBuffer.clear(); inC1.close(); inC2.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
11
Code Sample 1: public static boolean writeFileB2C(InputStream pIs, File pFile, boolean pAppend) { boolean flag = false; try { FileWriter fw = new FileWriter(pFile, pAppend); IOUtils.copy(pIs, fw); fw.flush(); fw.close(); pIs.close(); flag = true; } catch (Exception e) { LOG.error("将字节流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; } Code Sample 2: public static void copy(File src, File dest) throws IOException { if (dest.exists() && dest.isFile()) { logger.fine("cp " + src + " " + dest + " -- Destination file " + dest + " already exists. Deleting..."); dest.delete(); } final File parent = dest.getParentFile(); if (!parent.exists()) { logger.info("Directory to contain destination does not exist. Creating..."); parent.mkdirs(); } final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dest); final byte[] b = new byte[2048]; int n; while ((n = fis.read(b)) != -1) fos.write(b, 0, n); fis.close(); fos.close(); }
00
Code Sample 1: @Override public Reader openReader(final Charset charset) throws LocatorException { try { if (charset != null) { return new InputStreamReader(url.openStream(), charset); } return new InputStreamReader(url.openStream()); } catch (final IOException e) { throw new LocatorException("Failed to read from URL: " + url, e); } } 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: private String hashString(String key) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(key.getBytes()); byte[] hash = digest.digest(); BigInteger bi = new BigInteger(1, hash); return String.format("%0" + (hash.length << 1) + "X", bi) + KERNEL_VERSION; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return "" + key.hashCode(); } } Code Sample 2: protected void createGraphicalViewer(Composite parent) { final RulerComposite rc = new RulerComposite(parent, SWT.NONE); viewer = new ScrollingGraphicalViewer(); viewer.createControl(rc); editDomain.addViewer(viewer); rc.setGraphicalViewer(viewer); viewer.getControl().setBackground(ColorConstants.white); viewer.setEditPartFactory(new EditPartFactory() { public EditPart createEditPart(EditPart context, Object model) { return new RecorderEditPart(TopLevelModel.getRecorderModel()); } }); viewer.setContents(TopLevelModel.getRecorderModel()); Control control = viewer.getControl(); System.out.println("widget: " + control); DropTarget dt = new DropTarget(control, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_DEFAULT); dt.setTransfer(new Transfer[] { TextTransfer.getInstance() }); dt.addDropListener(new SensorTransferDropTargetListener(viewer)); }
11
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 void copyFile(File file, String pathExport) throws IOException { File out = new File(pathExport); FileChannel sourceChannel = new FileInputStream(file).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
00
Code Sample 1: public void deleteProposal(String id) throws Exception { String tmp = ""; PreparedStatement prepStmt = null; try { if (id == null || id.length() == 0) throw new Exception("Invalid parameter"); con = database.getConnection(); String delProposal = "delete from proposal where PROPOSAL_ID='" + id + "'"; prepStmt = con.prepareStatement(delProposal); prepStmt.executeUpdate(); con.commit(); prepStmt.close(); con.close(); } catch (Exception e) { if (!con.isClosed()) { con.rollback(); prepStmt.close(); con.close(); } throw e; } } Code Sample 2: public void uploadFile(File inputFile, String targetFile) throws IOException { System.out.println("Uploading " + inputFile.getName() + " to " + targetFile); File outputFile = new File(targetFile); if (targetFile.endsWith("/")) { outputFile = new File(outputFile, inputFile.getName()); } else if (outputFile.getParentFile().exists() == false) { outputFile.getParentFile().mkdirs(); } if (inputFile.renameTo(outputFile) == false) { InputStream in = new FileInputStream(inputFile); OutputStream out = new FileOutputStream(outputFile); byte[] line = new byte[16384]; int bytes = -1; while ((bytes = in.read(line)) != -1) out.write(line, 0, bytes); in.close(); out.close(); } }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile) throws IOException { FileChannel inputFileChannel = new FileInputStream(sourceFile).getChannel(); FileChannel outputFileChannel = new FileOutputStream(destFile).getChannel(); long offset = 0L; long length = inputFileChannel.size(); final long MAXTRANSFERBUFFERLENGTH = 1024 * 1024; try { for (; offset < length; ) { offset += inputFileChannel.transferTo(offset, MAXTRANSFERBUFFERLENGTH, outputFileChannel); inputFileChannel.position(offset); } } finally { try { outputFileChannel.close(); } catch (Exception ignore) { } try { inputFileChannel.close(); } catch (IOException ignore) { } } } Code Sample 2: public int extract() throws Exception { int count = 0; if (VERBOSE) System.out.println("IAAE:Extractr.extract: getting ready to extract " + getArtDir().toString()); ITCFileFilter iff = new ITCFileFilter(); RecursiveFileIterator rfi = new RecursiveFileIterator(getArtDir(), iff); FileTypeDeterminer ftd = new FileTypeDeterminer(); File artFile = null; File targetFile = null; broadcastStart(); while (rfi.hasMoreElements()) { artFile = (File) rfi.nextElement(); targetFile = getTargetFile(artFile); if (VERBOSE) System.out.println("IAAE:Extractr.extract: working ont " + artFile.toString()); BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream((new FileInputStream(artFile))); out = new BufferedOutputStream((new FileOutputStream(targetFile))); byte[] buffer = new byte[10240]; int read = 0; int total = 0; read = in.read(buffer); while (read != -1) { if ((total <= 491) && (read > 491)) { out.write(buffer, 492, (read - 492)); } else if ((total <= 491) && (read <= 491)) { } else { out.write(buffer, 0, read); } total = total + read; read = in.read(buffer); } } catch (Exception e) { e.printStackTrace(); broadcastFail(); } finally { in.close(); out.close(); } broadcastSuccess(); count++; } broadcastDone(); return count; }
11
Code Sample 1: public String getHash(String type, String text, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance(type); byte[] hash = new byte[md.getDigestLength()]; if (!salt.isEmpty()) { md.update(salt.getBytes("iso-8859-1"), 0, salt.length()); } md.update(text.getBytes("iso-8859-1"), 0, text.length()); hash = md.digest(); return convertToHex(hash); } Code Sample 2: private String endcodePassword(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); Base64 base64 = new Base64(); String hash = new String(base64.encode(raw)); return hash; }
11
Code Sample 1: protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ManagerResponse loginResponse; if (socket == null) { connect(); } if (!socket.isConnected()) { connect(); } synchronized (protocolIdentifier) { if (protocolIdentifier.value == null) { try { protocolIdentifier.wait(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (protocolIdentifier.value == null) { disconnect(); if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } else { throw new TimeoutException("Timeout waiting for protocol identifier"); } } } challengeAction = new ChallengeAction("MD5"); try { challengeResponse = sendAction(challengeAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send challenge action", e); } if (challengeResponse instanceof ChallengeResponse) { challenge = ((ChallengeResponse) challengeResponse).getChallenge(); } else { disconnect(); throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage()); } try { MessageDigest md; md = MessageDigest.getInstance("MD5"); if (challenge != null) { md.update(challenge.getBytes()); } if (password != null) { md.update(password.getBytes()); } key = ManagerUtil.toHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } loginAction = new LoginAction(username, "MD5", key, eventMask); try { loginResponse = sendAction(loginAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send login action", e); } if (loginResponse instanceof ManagerError) { disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } version = determineVersion(); writer.setTargetVersion(version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); } Code Sample 2: public static String crypt(String passwd, boolean pad) { try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(passwd.getBytes()); String c = new String(sha.digest()); return toNumeric(c, pad, true); } catch (java.security.NoSuchAlgorithmException e) { Log.error(Login.class, "couldn't crypt()", e); return ""; } }
00
Code Sample 1: public void shouldAllowClosingInputStreamTwice() throws IOException { OutputStream outputStream = fileSystem.createOutputStream(_("hello"), OutputMode.OVERWRITE); outputStream.write(new byte[] { 1, 2, 3 }); outputStream.close(); InputStream inputStream = fileSystem.createInputStream(_("hello")); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copy(inputStream, buffer); inputStream.close(); inputStream.close(); } Code Sample 2: public void testDatastreamWork3() throws FedoraConnectionException, DigitalObjectManager.DigitalObjectNotFoundException, StoreException, ParseException, IOException { String content = "ahsddksjgldskdlfnskl\nlskdfjlsjdf\n"; String pid = fedoraConnector.newObject(); assertTrue(fedoraConnector.exists(pid)); assertTrue(fedoraConnector.isPlanetsObject(pid)); assertTrue(fedoraConnector.isDataObject(pid)); assertTrue(fedoraConnector.isWritable(pid)); try { fedoraConnector.getDatastreamString(pid, "CONTENT"); fail("Datastream should not be there"); } catch (DigitalObjectManager.DigitalObjectNotFoundException e) { } fedoraConnector.modifyDatastream(pid, "CONTENT", content, null); URL url = fedoraConnector.getDatastreamURL(pid, "CONTENT"); InputStream stream = url.openStream(); String storedContent = convertStreamToString(stream); assertEquals(content, storedContent); fedoraConnector.purgeObject(pid); }
00
Code Sample 1: public static String get(String strUrl) { try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(true); conn.setAllowUserInteraction(true); conn.setFollowRedirects(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-Agent:", "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; de-de) AppleWebKit/523.12.2 (KHTML, like Gecko) Version/3.0.4 Safari/523.12.2"); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String s = ""; String sRet = ""; while ((s = in.readLine()) != null) { sRet += '\n' + s; } return sRet; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } Code Sample 2: public WordEntry[] getVariants(String word) throws MatchPackException { String upperWord = word.toUpperCase(); if (variantsDictionary == null) { try { long start = System.currentTimeMillis(); URL url = this.getClass().getResource("varlex.dic"); ObjectInputStream si = new ObjectInputStream(url.openStream()); variantsDictionary = (Map) si.readObject(); long end = System.currentTimeMillis(); System.out.println("loaded " + (end - start) + "ms"); si.close(); } catch (Exception e) { throw new MatchPackException("cannot load: varlex.dic " + e.getMessage()); } } List l = (List) variantsDictionary.get(upperWord); if (l == null) { return new WordEntry[0]; } return (WordEntry[]) l.toArray(new WordEntry[0]); }
11
Code Sample 1: @RequestMapping(value = "/verdocumentoFisico.html", method = RequestMethod.GET) public String editFile(ModelMap model, @RequestParam("id") int idAnexo) { Anexo anexo = anexoService.selectById(idAnexo); model.addAttribute("path", anexo.getAnexoCaminho()); try { InputStream is = new FileInputStream(new File(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho())); FileOutputStream fos = new FileOutputStream(new File(config.baseDir + "/temp/" + anexo.getAnexoCaminho())); IOUtils.copy(is, fos); Runtime.getRuntime().exec("chmod 777 " + config.tempDir + anexo.getAnexoCaminho()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "verdocumentoFisico"; } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void upgradeSingleFileModelToDirectory(File modelFile) throws IOException { byte[] buf = new byte[8192]; int bytesRead = 0; File backupModelFile = new File(modelFile.getPath() + ".bak"); FileInputStream oldModelIn = new FileInputStream(modelFile); FileOutputStream backupModelOut = new FileOutputStream(backupModelFile); while ((bytesRead = oldModelIn.read(buf)) >= 0) { backupModelOut.write(buf, 0, bytesRead); } backupModelOut.close(); oldModelIn.close(); buf = null; modelFile.delete(); modelFile.mkdir(); BufferedReader oldModelsBuff = new BomStrippingInputStreamReader(new FileInputStream(backupModelFile), "UTF-8"); File metaDataFile = new File(modelFile, ConstantParameters.FILENAMEOFModelMetaData); BufferedWriter metaDataBuff = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(metaDataFile), "UTF-8")); for (int i = 0; i < 8; i++) { metaDataBuff.write(oldModelsBuff.readLine()); metaDataBuff.write('\n'); } metaDataBuff.close(); int classIndex = 1; BufferedWriter modelWriter = null; String line = null; while ((line = oldModelsBuff.readLine()) != null) { if (line.startsWith("Class=") && line.contains("numTraining=") && line.contains("numPos=")) { if (modelWriter != null) { modelWriter.close(); } File nextModel = new File(modelFile, String.format(ConstantParameters.FILENAMEOFPerClassModel, Integer.valueOf(classIndex++))); modelWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(nextModel), "UTF-8")); } modelWriter.write(line); modelWriter.write('\n'); } if (modelWriter != null) { modelWriter.close(); } }
11
Code Sample 1: public static void zipMapBos(DitaBoundedObjectSet mapBos, File outputZipFile, MapBosProcessorOptions options) throws Exception { log.debug("Determining zip file organization..."); BosVisitor visitor = new DxpFileOrganizingBosVisitor(); visitor.visit(mapBos); if (!options.isQuiet()) log.info("Creating DXP package \"" + outputZipFile.getAbsolutePath() + "\"..."); OutputStream outStream = new FileOutputStream(outputZipFile); ZipOutputStream zipOutStream = new ZipOutputStream(outStream); ZipEntry entry = null; URI rootMapUri = mapBos.getRoot().getEffectiveUri(); URI baseUri = null; try { baseUri = AddressingUtil.getParent(rootMapUri); } catch (URISyntaxException e) { throw new BosException("URI syntax exception getting parent URI: " + e.getMessage()); } Set<String> dirs = new HashSet<String>(); if (!options.isQuiet()) log.info("Constructing DXP package..."); for (BosMember member : mapBos.getMembers()) { if (!options.isQuiet()) log.info("Adding member " + member + " to zip..."); URI relativeUri = baseUri.relativize(member.getEffectiveUri()); File temp = new File(relativeUri.getPath()); String parentPath = temp.getParent(); if (parentPath != null && !"".equals(parentPath) && !parentPath.endsWith("/")) { parentPath += "/"; } log.debug("parentPath=\"" + parentPath + "\""); if (!"".equals(parentPath) && parentPath != null && !dirs.contains(parentPath)) { entry = new ZipEntry(parentPath); zipOutStream.putNextEntry(entry); zipOutStream.closeEntry(); dirs.add(parentPath); } entry = new ZipEntry(relativeUri.getPath()); zipOutStream.putNextEntry(entry); IOUtils.copy(member.getInputStream(), zipOutStream); zipOutStream.closeEntry(); } zipOutStream.close(); if (!options.isQuiet()) log.info("DXP package \"" + outputZipFile.getAbsolutePath() + "\" created."); } Code Sample 2: public static void entering(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new BufferedInputStream(new FileInputStream(args[0]))); int constantIndex = writer.getStringConstantIndex("Entering "); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int printlnRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); int printRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "print", "(Ljava/lang/String;)V"); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); if (method.getName().equals("readConstant")) continue; CodeAttribute attribute = method.getCodeAttribute(); ArrayList instructions = new ArrayList(10); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("dup"), 0, null, false)); instructions.add(Instruction.appropriateLdc(constantIndex, false)); operands = new byte[2]; NetByte.intToPair(printRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(Instruction.appropriateLdc(writer.getStringConstantIndex(method.getName()), false)); operands = new byte[2]; NetByte.intToPair(printlnRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); attribute.insertInstructions(0, 0, instructions); attribute.codeCheck(); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); }
11
Code Sample 1: @Override public void doExecute(String[] args) { if (args.length != 2) { printUsage(); } else { int fileNo = 0; try { fileNo = Integer.parseInt(args[1]) - 1; } catch (NumberFormatException e) { printUsage(); return; } if (fileNo < 0) { printUsage(); return; } StorageFile[] files = (StorageFile[]) ctx.getRemoteDir().listFiles(); try { StorageFile file = files[fileNo]; File outFile = getOutFile(file); FileOutputStream out = new FileOutputStream(outFile); InputStream in = file.openStream(); IOUtils.copy(in, out); IOUtils.closeQuietly(out); afterSave(outFile); if (outFile.exists()) { print("File written to: " + outFile.getAbsolutePath()); } } catch (IOException e) { printError("Failed to load file. " + e.getMessage()); } catch (Exception e) { printUsage(); return; } } } Code Sample 2: public static void copyFile(String input, String output) { try { File inputFile = new File(input); File outputFile = new File(output); FileReader in; in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public String uploadZtree(ArrayList c) { try { String id = generateRandomId(); Iterator iter = c.iterator(); URL url = new URL(ZorobotSystem.props.getProperty("zoro.url") + "auplo1.jsp"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print("id=" + id + "&"); StringBuffer sb = new StringBuffer(); int gg = 0; while (iter.hasNext()) { if (gg++ >= 500) break; String st = (String) iter.next(); sb.append("a="); sb.append(URLEncoder.encode(st, "UTF-8")); if (iter.hasNext() && gg < 500) sb.append("&"); } out.println(sb.toString()); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; if ((inputLine = in.readLine()) != null) { if (!inputLine.equals("OK!") && inputLine.length() > 3) { System.out.println("Not OK: " + inputLine); return "xxxxxxxxxx"; } } in.close(); return id; } catch (Exception e) { e.printStackTrace(); } return null; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } long time = System.currentTimeMillis(); FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size && continueWriting(pos, size)) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); } } finally { output.close(); IOUtils.closeQuietly(fos); input.close(); IOUtils.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { if (DiskManager.isLocked()) throw new IOException("Copy stopped since VtM was working"); else throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } else { time = System.currentTimeMillis() - time; long speed = (destFile.length() / time) / 1000; DiskManager.addDiskSpeed(speed); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }