label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public boolean copy(String file, String path) { try { File file_in = new File(file); String tmp1, tmp2; tmp1 = file; tmp2 = path; while (tmp2.contains("\\")) { tmp2 = tmp2.substring(tmp2.indexOf("\\") + 1); tmp1 = tmp1.substring(tmp1.indexOf("\\") + 1); } tmp1 = file.substring(0, file.length() - tmp1.length()) + tmp2 + tmp1.substring(tmp1.indexOf("\\")); File file_out = new File(tmp1); 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; } } Code Sample 2: public static void download(String address, String localFileName, String rawClass, double newVer, int newStage) { OutputStream out = null; URLConnection conn = null; InputStream in = null; int totalBytes = 0; int dlBytes = 0; try { if (!Main.Updates.current.hasFile(rawClass)) { Main.Updates.current.addFile(newVer, newStage, rawClass); } Main.Updates.current.getFile(rawClass).downloading = true; Main.Updates.setImage(rawClass, "refresh.png"); java.io.File folder = new java.io.File(localFileName); folder.createNewFile(); URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); conn = url.openConnection(); in = conn.getInputStream(); totalBytes = conn.getContentLength(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; double incr = java.lang.Math.floor(totalBytes / 1000); Main.Interface.Update.prgStatus.setMaximum(1000); Main.Interface.Update.prgStatus.setString("0.0%"); while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; dlBytes += numRead; int newVal = (dlBytes != totalBytes ? (int) java.lang.Math.floor(dlBytes / incr) : 1000); Main.Interface.Update.prgStatus.setValue(newVal); Main.Interface.Update.prgStatus.setString((newVal / 10) + "." + (newVal % 10) + "%"); } Main.Updates.current.getFile(rawClass).downloading = false; Main.Updates.current.getFile(rawClass).version = newVer; Main.Updates.current.getFile(rawClass).stage = newStage; Main.Updates.setImage(rawClass, "updater.png"); Main.Updates.updateTable(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException ioe) { } } }
00
Code Sample 1: Bitmap downloadImage(String uri) { try { mGetMethod.setURI(new URI(uri)); HttpResponse resp = mClient.execute(mGetMethod); if (resp.getStatusLine().getStatusCode() < 400) { InputStream is = resp.getEntity().getContent(); String tmp = convertStreamToString(is); Log.d(TAG, "hoge" + tmp); is.close(); return null; } } catch (Exception e) { e.printStackTrace(); } return null; } Code Sample 2: public void createZipCopy(IUIContext ui, final String zipFileName, final File[] filesToZip, final FilenameFilter fileFilter, Timestamp timestamp) { TestCase.assertNotNull(ui); TestCase.assertNotNull(zipFileName); TestCase.assertFalse(zipFileName.trim().length() == 0); TestCase.assertNotNull(filesToZip); TestCase.assertNotNull(timestamp); String nameCopy = zipFileName; if (nameCopy.endsWith(".zip")) { nameCopy = nameCopy.substring(0, zipFileName.length() - 4); } nameCopy = nameCopy + "_" + timestamp.toString() + ".zip"; final String finalZip = nameCopy; IWorkspaceRunnable noResourceChangedEventsRunner = new IWorkspaceRunnable() { public void run(IProgressMonitor runnerMonitor) throws CoreException { try { Map<String, File> projectFiles = new HashMap<String, File>(); IPath basePath = new Path("/"); for (File nextLocation : filesToZip) { projectFiles.putAll(getFilesToZip(nextLocation, basePath, fileFilter)); } if (projectFiles.isEmpty()) { PlatformActivator.logDebug("Zip file (" + zipFileName + ") not created because there were no files to zip"); return; } IPath resultsPath = PlatformActivator.getDefault().getResultsPath(); File copyRoot = resultsPath.toFile(); copyRoot.mkdirs(); IPath zipFilePath = resultsPath.append(new Path(finalZip)); String zipFileName = zipFilePath.toPortableString(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String filePath : projectFiles.keySet()) { File nextFile = projectFiles.get(filePath); FileInputStream fin = new FileInputStream(nextFile); try { out.putNextEntry(new ZipEntry(filePath)); try { byte[] bin = new byte[4096]; int bread = fin.read(bin, 0, 4096); while (bread != -1) { out.write(bin, 0, bread); bread = fin.read(bin, 0, 4096); } } finally { out.closeEntry(); } } finally { fin.close(); } } } finally { out.close(); } } catch (FileNotFoundException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } catch (IOException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } } }; try { IWorkspace workspace = ResourcesPlugin.getWorkspace(); workspace.run(noResourceChangedEventsRunner, workspace.getRoot(), IWorkspace.AVOID_UPDATE, new NullProgressMonitor()); } catch (CoreException ce) { PlatformActivator.logException(ce); } }
11
Code Sample 1: public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(imageFile.separator) + 1, path.length())); File imageFile = new File(path); directoryPath = "Images" + imageFile.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + imageFile.separator + "Images" + imageFile.separator + imageName.substring(0, 1).toUpperCase() + imageFile.separator + imageName; File newFile = new File(imagePath); int i = 1; while (newFile.exists()) { imagePath = "." + imageFile.separator + "Images" + imageFile.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); newFile = new File(imagePath); i++; } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); dataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { try { int thumbWidth = PREVIEW_WIDTH; int thumbHeight = PREVIEW_HEIGHT; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getIconWidth(); int imageHeight = image.getIconHeight(); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image.getImage(), 0, 0, thumbWidth, thumbHeight, null); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePathThumb)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 100; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } } } Code Sample 2: public void render(HttpServletRequest request, HttpServletResponse response, File file, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } if (file.length() > Integer.MAX_VALUE) { throw new IllegalArgumentException("Cannot send file greater than 2GB"); } response.setContentLength((int) file.length()); IOUtils.copy(new FileInputStream(file), response.getOutputStream()); }
00
Code Sample 1: protected void convertInternal(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream, DocumentFormat outputFormat) { File inputFile = null; File outputFile = null; try { inputFile = File.createTempFile("document", "." + inputFormat.getFileExtension()); OutputStream inputFileStream = null; try { inputFileStream = new FileOutputStream(inputFile); IOUtils.copy(inputStream, inputFileStream); } finally { IOUtils.closeQuietly(inputFileStream); } outputFile = File.createTempFile("document", "." + outputFormat.getFileExtension()); convert(inputFile, inputFormat, outputFile, outputFormat); InputStream outputFileStream = null; try { outputFileStream = new FileInputStream(outputFile); IOUtils.copy(outputFileStream, outputStream); } finally { IOUtils.closeQuietly(outputFileStream); } } catch (IOException ioException) { throw new OpenOfficeException("conversion failed", ioException); } finally { if (inputFile != null) { inputFile.delete(); } if (outputFile != null) { outputFile.delete(); } } } Code Sample 2: static String encodeEmailAsUserId(String email) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(email.toLowerCase().getBytes()); StringBuilder builder = new StringBuilder(); builder.append("1"); for (byte b : md5.digest()) { builder.append(String.format("%02d", new Object[] { Integer.valueOf(b & 0xFF) })); } return builder.toString().substring(0, 20); } catch (NoSuchAlgorithmException ex) { } return ""; }
00
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: public boolean download(String address, String localFileName) { OutputStream out = null; URLConnection conn = null; InputStream in = null; try { URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } return true; } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } } return false; }
00
Code Sample 1: public static boolean downloadFile(String srcUri, String srcDest) { try { URL url = new URL(srcUri); InputStream is = url.openStream(); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(srcDest)); byte[] buff = new byte[10000]; int b; while ((b = is.read(buff)) > 0) bos.write(buff, 0, b); is.close(); bos.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } Code Sample 2: public static 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(); } } }
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 static void transfer(File src, File dest, boolean removeSrc) throws FileNotFoundException, IOException { Log.warning("source: " + src); Log.warning("dest: " + dest); if (!src.canRead()) { throw new IOException("can not read src file: " + src); } if (!dest.getParentFile().isDirectory()) { if (!dest.getParentFile().mkdirs()) { throw new IOException("failed to make directories: " + dest.getParent()); } } FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); Log.warning("starting transfer from position " + fcin.position() + " to size " + fcin.size()); fcout.transferFrom(fcin, 0, fcin.size()); Log.warning("closing streams and channels"); fcin.close(); fcout.close(); fis.close(); fos.close(); if (removeSrc) { Log.warning("deleting file " + src); src.delete(); } }
11
Code Sample 1: private static void copierScriptChargement(File webInfDir, String initialDataChoice) { File chargementInitialDir = new File(webInfDir, "chargementInitial"); File fichierChargement = new File(chargementInitialDir, "ScriptChargementInitial.sql"); File fichierChargementAll = new File(chargementInitialDir, "ScriptChargementInitial-All.sql"); File fichierChargementTypesDocument = new File(chargementInitialDir, "ScriptChargementInitial-TypesDocument.sql"); File fichierChargementVide = new File(chargementInitialDir, "ScriptChargementInitial-Vide.sql"); if (fichierChargement.exists()) { fichierChargement.delete(); } File fichierUtilise = null; if ("all".equals(initialDataChoice)) { fichierUtilise = fichierChargementAll; } else if ("typesDocument".equals(initialDataChoice)) { fichierUtilise = fichierChargementTypesDocument; } else if ("empty".equals(initialDataChoice)) { fichierUtilise = fichierChargementVide; } if (fichierUtilise != null && fichierUtilise.exists()) { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(fichierUtilise).getChannel(); destination = new FileOutputStream(fichierChargement).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (Exception e) { throw new RuntimeException(e); } finally { if (source != null) { try { source.close(); } catch (Exception e) { e.printStackTrace(); } } if (destination != null) { try { destination.close(); } catch (Exception e) { e.printStackTrace(); } } } } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private String postData(String requestUrl, String atom) throws AuthenticationException, IOException { URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); String header; try { header = oauthAuthenticator.getHttpAuthorizationHeader(url.toString(), "POST", profile.getOAuthToken(), profile.getOAuthTokenSecret()); } catch (OAuthException e) { throw new AuthenticationException(e); } conn.setRequestProperty("Authorization", header); conn.setRequestProperty("Content-Type", "application/atom+xml"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); writer.write(atom); writer.close(); if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new AuthenticationException(); } InputStreamReader reader = new InputStreamReader(conn.getInputStream()); char[] buffer = new char[1024]; int bytesRead = 0; StringBuilder data = new StringBuilder(); while ((bytesRead = reader.read(buffer)) != -1) { data.append(buffer, 0, bytesRead); } reader.close(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new IOException(conn.getResponseCode() + " " + conn.getResponseMessage() + "\n" + data); } return data.toString(); } Code Sample 2: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
11
Code Sample 1: private static void userAuth(String challenge) throws IOException { try { MessageDigest md = MessageDigest.getInstance("BrokenMD4"); String passwd = null; if (System.getProperty("jarsync.password.gui") != null) { JPasswordField pass = new JPasswordField(); JPanel panel = new JPanel(new GridLayout(2, 1)); panel.add(new JLabel("Password:")); panel.add(pass); JOptionPane.showMessageDialog(null, panel, remoteUser + '@' + remoteHost + "'s Password", JOptionPane.QUESTION_MESSAGE); passwd = new String(pass.getPassword()); } else { System.out.print(remoteUser + '@' + remoteHost + "'s password: "); passwd = Util.readLine(System.in); System.out.println(); } md.update(new byte[4]); md.update(passwd.getBytes("US-ASCII")); md.update(challenge.getBytes("US-ASCII")); byte[] response = md.digest(); Util.writeASCII(out, remoteUser + " " + Util.base64(response) + '\n'); out.flush(); } catch (NoSuchAlgorithmException nsae) { throw new IOException("could not create message digest."); } } Code Sample 2: public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
00
Code Sample 1: public static InputStream getInputStream(String path) throws ResourceException { URL url = getURL(path); if (url != null) { try { return url.openConnection().getInputStream(); } catch (IOException e) { throw new ResourceException(e); } } else { throw new ResourceException("Error obtaining resource, invalid path: " + path); } } Code Sample 2: public String sendRequest(HttpRequest request) throws IOException, AuthenticationException, RedmineException, NotFoundException { logger.debug(request.getRequestLine().toString()); DefaultHttpClient httpclient = HttpUtil.getNewHttpClient(); configureProxy(httpclient); if (login != null) { final String credentials = String.valueOf(Base64Encoder.encode((login + ':' + password).getBytes(CHARSET))); request.addHeader("Authorization", "Basic: " + credentials); } request.addHeader("Accept-Encoding", "gzip,deflate"); HttpResponse httpResponse = httpclient.execute((HttpUriRequest) request); int responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode == HttpStatus.SC_UNAUTHORIZED) { throw new AuthenticationException("Authorization error. Please check if you provided a valid API access key or Login and Password and REST API service is enabled on the server."); } if (responseCode == HttpStatus.SC_FORBIDDEN) { throw new AuthenticationException("Forbidden. Please check the user has proper permissions."); } HttpEntity responseEntity = httpResponse.getEntity(); String responseBody = EntityUtils.toString(responseEntity); if (responseCode == HttpStatus.SC_NOT_FOUND) { throw new NotFoundException("Server returned '404 not found'. response body:" + responseBody); } if (responseCode == HttpStatus.SC_UNPROCESSABLE_ENTITY) { List<String> errors = RedmineXMLParser.parseErrors(responseBody); throw new RedmineException(errors); } httpclient.getConnectionManager().shutdown(); return responseBody; }
11
Code Sample 1: public static boolean copyMerge(FileSystem srcFS, Path srcDir, FileSystem dstFS, Path dstFile, boolean deleteSource, Configuration conf, String addString) throws IOException { dstFile = checkDest(srcDir.getName(), dstFS, dstFile, false); if (!srcFS.getFileStatus(srcDir).isDir()) return false; OutputStream out = dstFS.create(dstFile); try { FileStatus contents[] = srcFS.listStatus(srcDir); for (int i = 0; i < contents.length; i++) { if (!contents[i].isDir()) { InputStream in = srcFS.open(contents[i].getPath()); try { IOUtils.copyBytes(in, out, conf, false); if (addString != null) out.write(addString.getBytes("UTF-8")); } finally { in.close(); } } } } finally { out.close(); } if (deleteSource) { return srcFS.delete(srcDir, true); } else { return true; } } Code Sample 2: @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object msg = e.getMessage(); if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) { ctx.sendUpstream(e); return; } HttpMessage currentMessage = this.currentMessage; File localFile = this.file; if (currentMessage == null) { HttpMessage m = (HttpMessage) msg; if (m.isChunked()) { final String localName = UUID.randomUUID().toString(); List<String> encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); encodings.remove(HttpHeaders.Values.CHUNKED); if (encodings.isEmpty()) { m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING); } this.currentMessage = m; this.file = new File(Play.tmpDir, localName); this.out = new FileOutputStream(file, true); } else { ctx.sendUpstream(e); } } else { final HttpChunk chunk = (HttpChunk) msg; if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) { currentMessage.setHeader(HttpHeaders.Names.WARNING, "play.netty.content.length.exceeded"); } else { IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out); if (chunk.isLast()) { this.out.flush(); this.out.close(); currentMessage.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(localFile.length())); currentMessage.setContent(new FileChannelBuffer(localFile)); this.out = null; this.currentMessage = null; this.file = null; Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress()); } } } }
00
Code Sample 1: public long add(T t) throws BaseException { Connection conn = null; PreparedStatement pstmt = null; long result = -1L; boolean flag = false; try { conn = getConnection(); if (conn != null) { flag = true; } else { conn = ConnectionManager.getConn(getStrConnection()); conn.setAutoCommit(false); } pstmt = getAdd(conn, t, this.getTableName()); pstmt.executeUpdate(); result = t.getId(); } catch (SQLException e) { try { if (!flag) { conn.rollback(); } } catch (Exception ex) { log.error("add(T " + t.toString() + ")回滚出错,错误信息:" + ex.getMessage()); } log.error("add(T " + t.toString() + ")方法出错:" + e.getMessage()); } catch (BaseException e) { throw e; } finally { try { if (!flag) { conn.setAutoCommit(true); } } catch (Exception e) { log.error("add(T " + t.toString() + ")方法设置自动提交出错,信息为:" + e.getMessage()); } ConnectionManager.closePreparedStatement(pstmt); if (!flag) { ConnectionManager.closeConn(conn); } } return result; } Code Sample 2: private boolean readRemoteFile() { InputStream inputstream; Concept concept = new Concept(); try { inputstream = url.openStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputStreamReader); String s4; while ((s4 = bufferedreader.readLine()) != null && s4.length() > 0) { if (!parseLine(s4, concept)) { return false; } } } catch (MalformedURLException e) { logger.fatal("malformed URL, trying to read local file"); return readLocalFile(); } catch (IOException e1) { logger.fatal("Error reading URL file, trying to read local file"); return readLocalFile(); } catch (Exception x) { logger.fatal("Failed to readRemoteFile " + x.getMessage() + ", trying to read local file"); return readLocalFile(); } return true; }
00
Code Sample 1: public synchronized List<AnidbSearchResult> getAnimeTitles() throws Exception { URL url = new URL("http", host, "/api/animetitles.dat.gz"); ResultCache cache = getCache(); @SuppressWarnings("unchecked") List<AnidbSearchResult> anime = (List) cache.getSearchResult(null, Locale.ROOT); if (anime != null) { return anime; } Pattern pattern = Pattern.compile("^(?!#)(\\d+)[|](\\d)[|]([\\w-]+)[|](.+)$"); Map<Integer, String> primaryTitleMap = new HashMap<Integer, String>(); Map<Integer, Map<String, String>> officialTitleMap = new HashMap<Integer, Map<String, String>>(); Map<Integer, Map<String, String>> synonymsTitleMap = new HashMap<Integer, Map<String, String>>(); Scanner scanner = new Scanner(new GZIPInputStream(url.openStream()), "UTF-8"); try { while (scanner.hasNextLine()) { Matcher matcher = pattern.matcher(scanner.nextLine()); if (matcher.matches()) { int aid = Integer.parseInt(matcher.group(1)); String type = matcher.group(2); String language = matcher.group(3); String title = matcher.group(4); if (type.equals("1")) { primaryTitleMap.put(aid, title); } else if (type.equals("2") || type.equals("4")) { Map<Integer, Map<String, String>> titleMap = (type.equals("4") ? officialTitleMap : synonymsTitleMap); Map<String, String> languageTitleMap = titleMap.get(aid); if (languageTitleMap == null) { languageTitleMap = new HashMap<String, String>(); titleMap.put(aid, languageTitleMap); } languageTitleMap.put(language, title); } } } } finally { scanner.close(); } anime = new ArrayList<AnidbSearchResult>(primaryTitleMap.size()); for (Entry<Integer, String> entry : primaryTitleMap.entrySet()) { Map<String, String> localizedTitles = new HashMap<String, String>(); if (synonymsTitleMap.containsKey(entry.getKey())) { localizedTitles.putAll(synonymsTitleMap.get(entry.getKey())); } if (officialTitleMap.containsKey(entry.getKey())) { localizedTitles.putAll(officialTitleMap.get(entry.getKey())); } anime.add(new AnidbSearchResult(entry.getKey(), entry.getValue(), localizedTitles)); } return cache.putSearchResult(null, Locale.ROOT, anime); } Code Sample 2: private static Result request(AbstractHttpClient client, HttpUriRequest request) throws ClientProtocolException, IOException { HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); Result result = new Result(); result.setStatusCode(response.getStatusLine().getStatusCode()); result.setHeaders(response.getAllHeaders()); result.setCookie(assemblyCookie(client.getCookieStore().getCookies())); result.setHttpEntity(entity); return result; }
11
Code Sample 1: static void copyFile(File file, File destDir) { File destFile = new File(destDir, file.getName()); if (destFile.exists() && (!destFile.canWrite())) { throw new SyncException("Cannot overwrite " + destFile + " because " + "it is read-only"); } try { FileInputStream in = new FileInputStream(file); try { FileOutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[BUFFER_SIZE]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new SyncException("I/O error copying " + file + " to " + destDir + " (message: " + e.getMessage() + ")", e); } if (!destFile.setLastModified(file.lastModified())) { throw new SyncException("Could not set last modified timestamp " + "of " + destFile); } } Code Sample 2: public static boolean compress(File source, File target, Manifest manifest) { try { if (!(source.exists() & source.isDirectory())) return false; if (target.exists()) target.delete(); ZipOutputStream output = null; boolean isJar = target.getName().toLowerCase().endsWith(".jar"); if (isJar) { File manifestDir = new File(source, "META-INF"); remove(manifestDir); if (manifest != null) output = new JarOutputStream(new FileOutputStream(target), manifest); else output = new JarOutputStream(new FileOutputStream(target)); } else output = new ZipOutputStream(new FileOutputStream(target)); ArrayList list = getContents(source); String baseDir = source.getAbsolutePath().replace('\\', '/'); if (!baseDir.endsWith("/")) baseDir = baseDir + "/"; int baseDirLength = baseDir.length(); byte[] buffer = new byte[1024]; int bytesRead; for (int i = 0, n = list.size(); i < n; i++) { File file = (File) list.get(i); FileInputStream f_in = new FileInputStream(file); String filename = file.getAbsolutePath().replace('\\', '/'); if (filename.startsWith(baseDir)) filename = filename.substring(baseDirLength); if (isJar) output.putNextEntry(new JarEntry(filename)); else output.putNextEntry(new ZipEntry(filename)); while ((bytesRead = f_in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); f_in.close(); output.closeEntry(); } output.close(); } catch (Exception exc) { exc.printStackTrace(); return false; } return true; }
11
Code Sample 1: private void copyEntries() { if (zipFile != null) { Enumeration<? extends ZipEntry> enumerator = zipFile.entries(); while (enumerator.hasMoreElements()) { ZipEntry entry = enumerator.nextElement(); if (!entry.isDirectory() && !toIgnore.contains(normalizePath(entry.getName()))) { ZipEntry originalEntry = new ZipEntry(entry.getName()); try { zipOutput.putNextEntry(originalEntry); IOUtils.copy(getInputStream(entry.getName()), zipOutput); zipOutput.closeEntry(); } catch (IOException e) { e.printStackTrace(); } } } } } Code Sample 2: public static DownloadedContent downloadContent(final InputStream is) throws IOException { if (is == null) { return new DownloadedContent.InMemory(new byte[] {}); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int nbRead; try { while ((nbRead = is.read(buffer)) != -1) { bos.write(buffer, 0, nbRead); if (bos.size() > MAX_IN_MEMORY) { final File file = File.createTempFile("htmlunit", ".tmp"); file.deleteOnExit(); final FileOutputStream fos = new FileOutputStream(file); bos.writeTo(fos); IOUtils.copyLarge(is, fos); fos.close(); return new DownloadedContent.OnFile(file); } } } finally { IOUtils.closeQuietly(is); } return new DownloadedContent.InMemory(bos.toByteArray()); }
00
Code Sample 1: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } Code Sample 2: public static void writeInputStreamToFile(final InputStream stream, final File target) { long size = 0; FileOutputStream fileOut; try { fileOut = new FileOutputStream(target); size = IOUtils.copyLarge(stream, fileOut); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (log.isInfoEnabled()) { log.info("Wrote " + size + " bytes to " + target.getAbsolutePath()); } else { System.out.println("Wrote " + size + " bytes to " + target.getAbsolutePath()); } }
00
Code Sample 1: public static void decoupe(String input_file_path) { final int BUFFER_SIZE = 2000000; try { FileInputStream fr = new FileInputStream(input_file_path); byte[] cbuf = new byte[BUFFER_SIZE]; int n_read = 0; int i = 0; boolean bContinue = true; while (bContinue) { n_read = fr.read(cbuf, 0, BUFFER_SIZE); if (n_read == -1) break; FileOutputStream fo = new FileOutputStream("f_" + ++i); fo.write(cbuf, 0, n_read); fo.close(); } fr.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { InputStream urlStream = url.openStream(); AudioFileFormat fileFormat = null; try { fileFormat = getFMT(urlStream, false); } finally { if (fileFormat == null) { urlStream.close(); } } return new AudioInputStream(urlStream, fileFormat.getFormat(), fileFormat.getFrameLength()); }
00
Code Sample 1: public String readBaseLib() throws Exception { if (_BASE_LIB_JS == null) { StringBuffer js = new StringBuffer(); try { URL url = AbstractRunner.class.getResource(_BASELIB_FILENAME); if (url != null) { InputStream is = url.openStream(); InputStreamReader reader = new InputStreamReader(is); BufferedReader bfReader = new BufferedReader(reader); String tmp = null; do { tmp = bfReader.readLine(); if (tmp != null) { js.append(tmp).append('\n'); } } while (tmp != null); bfReader.close(); reader.close(); is.close(); } } catch (Exception e) { e.printStackTrace(); throw e; } _BASE_LIB_JS = js.toString(); } return _BASE_LIB_JS; } Code Sample 2: public void process(String dir) { String[] list = new File(dir).list(); if (list == null) return; int n = list.length; long[] bubblesort = new long[list.length + 1]; if (!statustext) { IJ.log("Current Directory is: " + dir); IJ.log(" "); IJ.log("DICOM File Name / " + prefix1 + " / " + prefix2 + " / " + prefix3 + " / " + pick); IJ.log(" "); } for (int i = 0; i < n; i++) { IJ.showStatus(i + "/" + n); File f = new File(dir + list[i]); if (!f.isDirectory()) { ImagePlus img = new Opener().openImage(dir, list[i]); if (img != null && img.getStackSize() == 1) { if (!scoutengine(img)) return; if (!statustext) { IJ.log(list[i] + "/" + whichprefix1 + "/" + whichprefix2 + "/" + whichprefix3 + "/" + whichcase); } int lastDigit = whichcase.length() - 1; while (lastDigit > 0) { if (!Character.isDigit(whichcase.charAt(lastDigit))) lastDigit -= 1; else break; } if (lastDigit < whichcase.length() - 1) whichcase = whichcase.substring(0, lastDigit + 1); bubblesort[i] = Long.parseLong(whichcase); } } } if (statussorta || statussortd || statustext) { boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < n - 1; i++) { if (statussorta) { if (bubblesort[i] > bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } else { if (bubblesort[i] < bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } } } IJ.log(" "); for (int i = 0; i < n; i++) { if (!statustext) { IJ.log(list[i] + " / " + bubblesort[i]); } else { IJ.log(dir + list[i]); } } } if (open_as_stack || only_images) { boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < n - 1; i++) { if (bubblesort[i] > bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } } if (only_images) { Opener o = new Opener(); int counter = 0; IJ.log(" "); for (int i = 0; i < n; i++) { String path = (dir + list[i]); if (path == null) break; else { ImagePlus imp = o.openImage(path); counter++; if (imp != null) { IJ.log(counter + " + " + path); imp.show(); } else IJ.log(counter + " - " + path); } } return; } int width = 0, height = 0, type = 0; ImageStack stack = null; double min = Double.MAX_VALUE; double max = -Double.MAX_VALUE; int k = 0; try { for (int i = 0; i < n; i++) { String path = (dir + list[i]); if (path == null) break; if (list[i].endsWith(".txt")) continue; ImagePlus imp = new Opener().openImage(path); if (imp != null && stack == null) { width = imp.getWidth(); height = imp.getHeight(); type = imp.getType(); ColorModel cm = imp.getProcessor().getColorModel(); if (halfSize) stack = new ImageStack(width / 2, height / 2, cm); else stack = new ImageStack(width, height, cm); } if (stack != null) k = stack.getSize() + 1; IJ.showStatus(k + "/" + n); IJ.showProgress((double) k / n); if (imp == null) IJ.log(list[i] + ": unable to open"); else if (imp.getWidth() != width || imp.getHeight() != height) IJ.log(list[i] + ": wrong dimensions"); else if (imp.getType() != type) IJ.log(list[i] + ": wrong type"); else { ImageProcessor ip = imp.getProcessor(); if (grayscale) ip = ip.convertToByte(true); if (halfSize) ip = ip.resize(width / 2, height / 2); if (ip.getMin() < min) min = ip.getMin(); if (ip.getMax() > max) max = ip.getMax(); String label = imp.getTitle(); String info = (String) imp.getProperty("Info"); if (info != null) label += "\n" + info; stack.addSlice(label, ip); } System.gc(); } } catch (OutOfMemoryError e) { IJ.outOfMemory("FolderOpener"); stack.trim(); } if (stack != null && stack.getSize() > 0) { ImagePlus imp2 = new ImagePlus("Stack", stack); if (imp2.getType() == ImagePlus.GRAY16 || imp2.getType() == ImagePlus.GRAY32) imp2.getProcessor().setMinAndMax(min, max); imp2.show(); } IJ.showProgress(1.0); } }
00
Code Sample 1: public void login(String UID, String PWD, int CTY) throws Exception { sSideURL = sSideURLCollection[CTY]; sUID = UID; sPWD = PWD; iCTY = CTY; sLoginLabel = getLoginLabel(sSideURL); String sParams = getLoginParams(); CookieHandler.setDefault(new ListCookieHandler()); URL url = new URL(sSideURL + sLoginURL); URLConnection conn = url.openConnection(); setRequestProperties(conn); conn.setDoInput(true); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(sParams); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = rd.readLine(); while (line != null) { sb.append(line + "\n"); line = rd.readLine(); } wr.close(); rd.close(); String sPage = sb.toString(); Pattern p = Pattern.compile(">Dein Penner<"); Matcher matcher = p.matcher(sPage); LogedIn = matcher.find(); } Code Sample 2: public void fetchFile(String ID) { String url = "http://www.nal.usda.gov/cgi-bin/agricola-ind?bib=" + ID + "&conf=010000++++++++++++++&screen=MA"; System.out.println(url); try { PrintWriter pw = new PrintWriter(new FileWriter("MARC" + ID + ".txt")); if (!id.contains("MARC" + ID + ".txt")) { id.add("MARC" + ID + ".txt"); } in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); in.readLine(); String inputLine, stx = ""; StringBuffer sb = new StringBuffer(); while ((inputLine = in.readLine()) != null) { if (inputLine.startsWith("<TR><TD><B>")) { String sts = (inputLine.substring(inputLine.indexOf("B>") + 2, inputLine.indexOf("</"))); int i = 0; try { i = Integer.parseInt(sts); } catch (NumberFormatException nfe) { } if (i > 0) { stx = stx + "\n" + sts + " - "; } else { stx += sts; } } if (!(inputLine.startsWith("<") || inputLine.startsWith(" <") || inputLine.startsWith(">"))) { String tx = inputLine.trim(); stx += tx; } } pw.println(stx); pw.close(); } catch (Exception e) { System.out.println("Couldn't open stream"); System.out.println(e); } }
11
Code Sample 1: public void copyFile(File s, File t) { try { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); } catch (Exception e) { System.out.println(e); } } Code Sample 2: @Test public void config() throws IOException { Reader reader = new FileReader(new File("src/test/resources/test.yml")); Writer writer = new FileWriter(new File("src/site/apt/config.apt")); writer.write("------\n"); writer.write(FileUtils.readFully(reader)); writer.flush(); writer.close(); }
00
Code Sample 1: protected Icon newIcon(String iconName) { URL url = Utils.getResource(getFullPath(iconName, "/"), getClass()); if (url == null) { if (getParent() != null) return getParent().getIcon(iconName); return null; } try { MethodCall getImage = new MethodCaller("org.apache.sanselan.Sanselan", null, "getBufferedImage", new Object[] { InputStream.class }).getMethodCall(); getImage.setArgumentValue(0, url.openStream()); return new ImageIcon((BufferedImage) getImage.call()); } catch (Throwable e) { return new ImageIcon(url); } } Code Sample 2: public List<MytemHistory> getMytemHistories(String janCode) throws GaeException { HttpClient client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); HttpConnectionParams.setSoTimeout(httpParams, 10000); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); BufferedReader reader = null; StringBuffer request = new StringBuffer(address); request.append("api/mytems/history?jan="); request.append(janCode); try { HttpGet httpGet = new HttpGet(request.toString()); HttpResponse httpResponse = client.execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == NOT_FOUND) { return null; } if (statusCode >= 400) { throw new GaeException("Status Error = " + Integer.toString(statusCode)); } reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { builder.append(line); } return createMytemHistories(builder.toString()); } catch (ClientProtocolException e) { throw new GaeException(e); } catch (SocketTimeoutException e) { throw new GaeException(e); } catch (IOException exception) { throw new GaeException(exception); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
00
Code Sample 1: private boolean copy(File in, File out) { try { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); FileChannel readableChannel = fis.getChannel(); FileChannel writableChannel = fos.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); fis.close(); fos.close(); return true; } catch (IOException ioe) { System.out.println("Copy Error: IOException during copy\r\n" + ioe.getMessage()); return false; } } Code Sample 2: public void login(LoginData loginData) throws ConnectionEstablishException, AccessDeniedException { try { int reply; this.ftpClient.connect(loginData.getFtpServer()); reply = this.ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { this.ftpClient.disconnect(); throw (new ConnectionEstablishException("FTP server refused connection.")); } } catch (IOException e) { if (this.ftpClient.isConnected()) { try { this.ftpClient.disconnect(); } catch (IOException f) { } } e.printStackTrace(); throw (new ConnectionEstablishException("Could not connect to server.", e)); } try { if (!this.ftpClient.login(loginData.getFtpBenutzer(), loginData.getFtpPasswort())) { this.logout(); throw (new AccessDeniedException("Could not login into server.")); } } catch (IOException ioe) { ioe.printStackTrace(); throw (new AccessDeniedException("Could not login into server.", ioe)); } }
00
Code Sample 1: public boolean compile(URL url) { try { final InputStream stream = url.openStream(); final InputSource input = new InputSource(stream); input.setSystemId(url.toString()); return compile(input, _className); } catch (IOException e) { _parser.reportError(Constants.FATAL, new ErrorMsg(e)); return false; } } Code Sample 2: private static void copySmallFile(File sourceFile, File targetFile) throws BusinessException { LOG.debug("Copying SMALL file '" + sourceFile.getAbsolutePath() + "' to '" + targetFile.getAbsolutePath() + "'."); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(sourceFile).getChannel(); outChannel = new FileOutputStream(targetFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new BusinessException("Could not copy file from '" + sourceFile.getAbsolutePath() + "' to '" + targetFile.getAbsolutePath() + "'!", e); } finally { try { if (inChannel != null) inChannel.close(); } catch (IOException e) { LOG.error("Could not close input stream!", e); } try { if (outChannel != null) outChannel.close(); } catch (IOException e) { LOG.error("Could not close output stream!", e); } } }
00
Code Sample 1: private void btnOkActionPerformed(java.awt.event.ActionEvent evt) { if (validateData()) { LoginUser me = AdministrationPanelView.getMe(); Connection dbConnection = null; try { DriverManager.registerDriver(new com.mysql.jdbc.Driver()); dbConnection = DriverManager.getConnection(me.getSqlReportsURL(), me.getSqlReportsUser(), me.getSqlReportsPassword()); dbConnection.setAutoCommit(false); dbConnection.setSavepoint(); String sql = "INSERT INTO campaigns (type, name, dateCreated, createdBy) VALUES (?, ?, ?, ?)"; PreparedStatement statement = dbConnection.prepareStatement(sql); statement.setByte(1, (optTypeAgents.isSelected()) ? CampaignStatics.CAMP_TYPE_AGENT : CampaignStatics.CAMP_TYPE_IVR); statement.setString(2, txtCampaignName.getText()); statement.setTimestamp(3, new Timestamp(Calendar.getInstance().getTime().getTime())); statement.setLong(4, me.getId()); statement.executeUpdate(); ResultSet rs = statement.getGeneratedKeys(); rs.next(); long campaignId = rs.getLong(1); sql = "INSERT INTO usercampaigns (userid, campaignid, role) VALUES (?, ?, ?)"; statement = dbConnection.prepareStatement(sql); statement.setLong(1, me.getId()); statement.setLong(2, campaignId); statement.setString(3, "admin"); statement.executeUpdate(); dbConnection.commit(); dbConnection.close(); CampaignAdmin ca = new CampaignAdmin(); ca.setCampaign(txtCampaignName.getText()); ca.setVisible(true); dispose(); } catch (SQLException ex) { try { dbConnection.rollback(); } catch (SQLException ex1) { Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex1); } JOptionPane.showMessageDialog(this.getRootPane(), ex.getLocalizedMessage(), "Error", JOptionPane.ERROR_MESSAGE); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex); } } } Code Sample 2: private ArrayList<String> loadProperties(String filename) throws DevFailed, IOException { java.net.URL url = getClass().getResource(filename); if (url == null) { Except.throw_exception("LOAD_PROPERTY_FAILED", "URL for property file (" + filename + ") is null !", "PogoProperty.loadProperties()"); return null; } InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ArrayList<String> vs = new ArrayList<String>(); String str; while ((str = br.readLine()) != null) { str = str.trim(); if (!str.startsWith("#")) if (str.length() > 0) vs.add(str); } br.close(); return vs; }
00
Code Sample 1: public static void writeDataResourceText(GenericValue dataResource, String mimeTypeId, Locale locale, Map templateContext, CmsOFBizRemoteClient remoteClient, Writer out, boolean cache) throws IOException, GeneralException { Map context = (Map) templateContext.get("context"); if (context == null) { context = FastMap.newInstance(); } String webSiteId = (String) templateContext.get("webSiteId"); if (UtilValidate.isEmpty(webSiteId)) { if (context != null) webSiteId = (String) context.get("webSiteId"); } String https = (String) templateContext.get("https"); if (UtilValidate.isEmpty(https)) { if (context != null) https = (String) context.get("https"); } Map fields = dataResource.getAllFields(); String dataResourceId = (String) fields.get("dataResourceId"); String dataResourceTypeId = (String) fields.get("dataResourceTypeId"); if (UtilValidate.isEmpty(dataResourceTypeId)) { dataResourceTypeId = "SHORT_TEXT"; } if ("SHORT_TEXT".equals(dataResourceTypeId) || "LINK".equals(dataResourceTypeId)) { String text = (String) fields.get("objectInfo"); writeText(remoteClient, dataResource, text, templateContext, mimeTypeId, locale, out); } else if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)) { GenericValue electronicText; if (cache) { electronicText = remoteClient.findByPrimaryKeyCache("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId)); } else { electronicText = remoteClient.findByPrimaryKey("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId)); } fields = electronicText.getAllFields(); String text = (String) fields.get("textData"); writeText(remoteClient, dataResource, text, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.endsWith("_OBJECT")) { String text = (String) fields.get("dataResourceId"); writeText(remoteClient, dataResource, text, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.equals("URL_RESOURCE")) { String text = null; URL url = new URL((String) fields.get("objectInfo")); if (url.getHost() != null) { InputStream in = url.openStream(); int c; StringWriter sw = new StringWriter(); while ((c = in.read()) != -1) { sw.write(c); } sw.close(); text = sw.toString(); } else { String prefix = DataResourceWorker.buildRequestPrefix(remoteClient, locale, webSiteId, https); String sep = ""; if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) { sep = "/"; } String fixedUrlStr = prefix + sep + url.toString(); URL fixedUrl = new URL(fixedUrlStr); text = (String) fixedUrl.getContent(); } out.write(text); } else if (dataResourceTypeId.endsWith("_FILE_BIN")) { writeText(remoteClient, dataResource, dataResourceId, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.endsWith("_FILE")) { String dataResourceMimeTypeId = (String) fields.get("mimeTypeId"); String objectInfo = (String) fields.get("objectInfo"); String rootDir = (String) context.get("rootDir"); if (dataResourceMimeTypeId == null || dataResourceMimeTypeId.startsWith("text")) { renderFile(dataResourceTypeId, objectInfo, rootDir, out); } else { writeText(remoteClient, dataResource, dataResourceId, templateContext, mimeTypeId, locale, out); } } else { throw new GeneralException("The dataResourceTypeId [" + dataResourceTypeId + "] is not supported in renderDataResourceAsText"); } } Code Sample 2: @Override public Result sendSMS(String number, String text, Proxy proxy) { try { DefaultHttpClient client = new DefaultHttpClient(); if (proxy != null) { HttpHost prox = new HttpHost(proxy.host, proxy.port); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, prox); } String target = "http://www.smsbilliger.de/free-sms.html"; HttpGet get = new HttpGet(target); HttpResponse response = client.execute(get); HttpEntity e = response.getEntity(); Document doc = ref.getDocumentFromInputStream(e.getContent()); List<Element> forms = ref.selectByXPathOnDocument(doc, "//<ns>FORM", doc.getRootElement().getNamespaceURI()); if (forms.size() == 0) return new Result(Result.SMS_LIMIT_REACHED); Element form = forms.get(0); List<NameValuePair> formparas = new ArrayList<NameValuePair>(); List<Element> inputs = ref.selectByXPathOnElement(form, "//<ns>INPUT|//<ns>TEXTAREA|//<ns>SELECT", form.getNamespaceURI()); Iterator<Element> it = inputs.iterator(); while (it.hasNext()) { Element input = it.next(); String type = input.getAttributeValue("type"); String name = input.getAttributeValue("name"); String value = input.getAttributeValue("value"); if (type != null && type.equals("hidden")) { formparas.add(new BasicNameValuePair(name, value)); } else if (name != null && name.equals(FORM_NUMBER)) { formparas.add(new BasicNameValuePair(name, this.getNumberPart(number))); } else if (name != null && name.equals(FORM_TEXT)) { formparas.add(new BasicNameValuePair(name, text)); } else if (name != null && name.equals(FORM_AGB)) { formparas.add(new BasicNameValuePair(name, "true")); } } formparas.add(new BasicNameValuePair("dialing_code", this.getPrefixPart(number))); formparas.add(new BasicNameValuePair("no_schedule", "yes")); List<Element> captchas = ref.selectByXPathOnDocument(doc, "//<ns>IMG[@id='code_img']", doc.getRootElement().getNamespaceURI()); Element captcha = captchas.get(0); String url = "http://www.smsbilliger.de/" + captcha.getAttributeValue("src"); HttpGet imgcall = new HttpGet(url); HttpResponse imgres = client.execute(imgcall); HttpEntity imge = imgres.getEntity(); BufferedImage img = ImageIO.read(imge.getContent()); imge.getContent().close(); Icon icon = new ImageIcon(img); String result = (String) JOptionPane.showInputDialog(null, "Bitte Captcha eingeben:", "Captcha", JOptionPane.INFORMATION_MESSAGE, icon, null, ""); formparas.add(new BasicNameValuePair(FORM_CAPTCHA, result)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparas, "UTF-8"); HttpPost post = new HttpPost(target); post.setEntity(entity); response = client.execute(post); e = response.getEntity(); doc = ref.getDocumentFromInputStream(e.getContent()); List<Element> fonts = ref.selectByXPathOnDocument(doc, "//<ns>H3", doc.getRootElement().getNamespaceURI()); Iterator<Element> it2 = fonts.iterator(); while (it2.hasNext()) { Element font = it2.next(); String txt = font.getText(); if (txt.contains("Die SMS wurde erfolgreich versendet.")) { return new Result(Result.SMS_SEND); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } return new Result(Result.UNKNOWN_ERROR); }
00
Code Sample 1: public synchronized String getEncryptedPassword(String plaintext, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; try { md = MessageDigest.getInstance(algorithm); md.update(plaintext.getBytes("UTF-8")); } catch (NoSuchAlgorithmException nsae) { throw nsae; } catch (UnsupportedEncodingException uee) { throw uee; } return (new BigInteger(1, md.digest())).toString(16); } Code Sample 2: public void removeForwardAddress(final List<NewUser> forwardAddresses) { try { final List<Integer> usersToRemoveFromCache = new ArrayList<Integer>(); connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("userForwardAddresses.delete")); Iterator<NewUser> iter = forwardAddresses.iterator(); Iterator<Integer> iter2; NewUser newUser; while (iter.hasNext()) { newUser = iter.next(); iter2 = newUser.forwardAddressIds.iterator(); while (iter2.hasNext()) { psImpl.setInt(1, iter2.next()); psImpl.executeUpdate(); } usersToRemoveFromCache.add(newUser.userId); } } }); connection.commit(); cmDB.removeUsers(usersToRemoveFromCache); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } }
00
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public byte[] encryptMsg(String encryptString) { byte[] encryptByte = null; try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(encryptString.getBytes()); encryptByte = messageDigest.digest(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return encryptByte; }
11
Code Sample 1: public static void copy(URL url, String outPath) throws IOException { System.out.println("copying from: " + url + " to " + outPath); InputStream in = url.openStream(); FileOutputStream fout = new FileOutputStream(outPath); byte[] data = new byte[8192]; int read = -1; while ((read = in.read(data)) != -1) { fout.write(data, 0, read); } fout.close(); } Code Sample 2: public byte[] getBytesMethod(String url) { logger.info("Facebook: @executing facebookGetMethod():" + url); byte[] responseBytes = null; try { HttpGet loginGet = new HttpGet(url); loginGet.addHeader("Accept-Encoding", "gzip"); HttpResponse response = httpClient.execute(loginGet); HttpEntity entity = response.getEntity(); logger.trace("Facebook: getBytesMethod: " + response.getStatusLine()); if (entity != null) { InputStream in = response.getEntity().getContent(); if (response.getEntity().getContentEncoding().getValue().equals("gzip")) { in = new GZIPInputStream(in); } ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] b = new byte[4096]; int n; while ((n = in.read(b)) != -1) { out.write(b, 0, n); } responseBytes = out.toByteArray(); in.close(); entity.consumeContent(); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { logger.warn("Facebook: Error Occured! Status Code = " + statusCode); responseBytes = null; } logger.info("Facebook: Get Bytes Method done(" + statusCode + "), response bytes length: " + (responseBytes == null ? 0 : responseBytes.length)); } catch (IOException e) { logger.warn("Facebook: ", e); } return responseBytes; }
00
Code Sample 1: public boolean addTextGroup(String key, URL url) { if (_textGroups.contains(key)) return false; String s; Hashtable tg = new Hashtable(); String sGroupKey = "default"; String sGroup[]; Vector vGroup = new Vector(); int cntr; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((s = in.readLine()) != null) { if (s.startsWith("[")) { if (vGroup.size() > 0) { sGroup = new String[vGroup.size()]; for (cntr = 0; cntr < vGroup.size(); ++cntr) sGroup[cntr] = (String) vGroup.elementAt(cntr); tg.put(sGroupKey, sGroup); vGroup.removeAllElements(); } sGroupKey = s.substring(1, s.indexOf(']')); } else { vGroup.addElement(s); } } if (vGroup.size() > 0) { sGroup = new String[vGroup.size()]; for (cntr = 0; cntr < vGroup.size(); ++cntr) sGroup[cntr] = (String) vGroup.elementAt(cntr); tg.put(sGroupKey, sGroup); } in.close(); } catch (IOException ioe) { System.err.println("Error reading file for " + key); System.err.println(ioe.getMessage()); return false; } _textGroups.put(key, tg); return true; } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } } Code Sample 2: public static String md5Encode(String pass) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); byte[] result = md.digest(); return bytes2hexStr(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("La librería java.security no implemente MD5"); } }
00
Code Sample 1: static Object read(String path, String encoding, boolean return_string) throws IOException { InputStream in; if (path.startsWith("classpath:")) { path = path.substring("classpath:".length()); URL url = Estimate.class.getClassLoader().getResource(path); if (url == null) { throw new IllegalArgumentException("Not found " + path + " in classpath."); } System.out.println("read content from:" + url.getFile()); in = url.openStream(); } else { File f = new File(path); if (!f.exists()) { throw new IllegalArgumentException("Not found " + path + " in system."); } System.out.println("read content from:" + f.getAbsolutePath()); in = new FileInputStream(f); } Reader re; if (encoding != null) { re = new InputStreamReader(in, encoding); } else { re = new InputStreamReader(in); } if (!return_string) { return re; } char[] chs = new char[1024]; int count; StringBuffer content = new StringBuffer(); while ((count = re.read(chs)) != -1) { content.append(chs, 0, count); } re.close(); return content.toString(); } Code Sample 2: public static void copyFile(String target, String source) { try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { ExceptionHelper.showErrorDialog(e); } }
11
Code Sample 1: public boolean renameTo(File dest) throws IOException { if (dest == null) { throw new NullPointerException("dest"); } if (!file.renameTo(dest)) { FileInputStream inputStream = new FileInputStream(file); FileOutputStream outputStream = new FileOutputStream(dest); FileChannel in = inputStream.getChannel(); FileChannel out = outputStream.getChannel(); long destsize = in.transferTo(0, size, out); in.close(); out.close(); if (destsize == size) { file.delete(); file = dest; isRenamed = true; return true; } else { dest.delete(); return false; } } file = dest; isRenamed = true; return true; } Code Sample 2: public static void copyFile5(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copyLarge(in, out); in.close(); out.close(); }
00
Code Sample 1: private void validateODFDoc(String url, String ver, ValidationReport commentary) throws IOException, MalformedURLException { logger.debug("Beginning document validation ..."); synchronized (ODFValidationSession.class) { PropertyMapBuilder builder = new PropertyMapBuilder(); String[] segments = url.split("/"); CommentatingErrorHandler h = new CommentatingErrorHandler(commentary, segments[segments.length - 1]); ValidateProperty.ERROR_HANDLER.put(builder, h); ValidationDriver driver = new ValidationDriver(builder.toPropertyMap()); InputStream candidateStream = null; try { logger.debug("Loading schema version " + ver); byte[] schemaBytes = getSchemaForVersion(ver); driver.loadSchema(new InputSource(new ByteArrayInputStream(schemaBytes))); URLConnection conn = new URL(url).openConnection(); candidateStream = conn.getInputStream(); logger.debug("Calling validate()"); commentary.incIndent(); boolean isValid = driver.validate(new InputSource(candidateStream)); logger.debug("Errors in instance:" + h.getInstanceErrCount()); if (h.getInstanceErrCount() > CommentatingErrorHandler.THRESHOLD) { commentary.addComment("(<i>" + (h.getInstanceErrCount() - CommentatingErrorHandler.THRESHOLD) + " error(s) omitted for the sake of brevity</i>)"); } commentary.decIndent(); if (isValid) { commentary.addComment("The document is valid"); } else { commentary.addComment("ERROR", "The document is invalid"); } } catch (SAXException e) { commentary.addComment("FATAL", "The resource is not conformant XML: " + e.getMessage()); logger.error(e.getMessage()); } finally { Utils.streamClose(candidateStream); } } } Code Sample 2: public int doCheck(URL url) throws IOException { long start = (System.currentTimeMillis()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { } in.close(); long end = (System.currentTimeMillis()); return (int) (end - start); }
11
Code Sample 1: public static void copyFromTo(String src, String des) { staticprintln("Copying:\"" + src + "\"\nto:\"" + des + "\""); try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(des).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } Code Sample 2: private void regattaBackup() { SwingWorker sw = new SwingWorker() { Regatta lRegatta = fRegatta; public Object construct() { String fullName = lRegatta.getSaveDirectory() + lRegatta.getSaveName(); System.out.println(MessageFormat.format(res.getString("MainMessageBackingUp"), new Object[] { fullName + BAK })); try { FileInputStream fis = new FileInputStream(new File(fullName)); FileOutputStream fos = new FileOutputStream(new File(fullName + BAK)); int bufsize = 1024; byte[] buffer = new byte[bufsize]; int n = 0; while ((n = fis.read(buffer, 0, bufsize)) >= 0) fos.write(buffer, 0, n); fos.flush(); fos.close(); } catch (java.io.IOException ex) { Util.showError(ex, true); } return null; } }; sw.start(); }
11
Code Sample 1: private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: public RawCandidate getRawCandidate(long candId) throws BookKeeprCommunicationException { try { synchronized (httpClient) { HttpGet req = new HttpGet(remoteHost.getUrl() + "/cand/" + Long.toHexString(candId)); req.setHeader("Accept-Encoding", "gzip"); HttpResponse resp = httpClient.execute(req); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { try { InputStream in = resp.getEntity().getContent(); Header hdr = resp.getFirstHeader("Content-Encoding"); String enc = ""; if (hdr != null) { enc = resp.getFirstHeader("Content-Encoding").getValue(); } if (enc.equals("gzip")) { in = new GZIPInputStream(in); } XMLAble xmlable = XMLReader.read(in); in.close(); if (xmlable instanceof RawCandidate) { RawCandidate p = (RawCandidate) xmlable; return p; } else { throw new BookKeeprCommunicationException("BookKeepr returned the wrong thing for candId"); } } catch (SAXException ex) { Logger.getLogger(BookKeeprConnection.class.getName()).log(Level.WARNING, "Got a malformed message from the bookkeepr", ex); throw new BookKeeprCommunicationException(ex); } } else { resp.getEntity().consumeContent(); throw new BookKeeprCommunicationException("Got a " + resp.getStatusLine().getStatusCode() + " from the BookKeepr"); } } } catch (HttpException ex) { throw new BookKeeprCommunicationException(ex); } catch (IOException ex) { throw new BookKeeprCommunicationException(ex); } catch (URISyntaxException ex) { throw new BookKeeprCommunicationException(ex); } } Code Sample 2: 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: @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: public Constructor run() throws Exception { String path = "META-INF/services/" + ComponentApplicationContext.class.getName(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> urls; if (loader == null) { urls = ComponentApplicationContext.class.getClassLoader().getResources(path); } else { urls = loader.getResources(path); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String className = null; while ((className = reader.readLine()) != null) { final String name = className.trim(); if (!name.startsWith("#") && !name.startsWith(";") && !name.startsWith("//")) { final Class<?> cls; if (loader == null) { cls = Class.forName(name); } else { cls = Class.forName(name, true, loader); } int m = cls.getModifiers(); if (ComponentApplicationContext.class.isAssignableFrom(cls) && !Modifier.isAbstract(m) && !Modifier.isInterface(m)) { Constructor constructor = cls.getDeclaredConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { constructor.setAccessible(true); } return constructor; } else { throw new ClassCastException(cls.getName()); } } } } finally { reader.close(); } } throw new ComponentApplicationException("No " + "ComponentApplicationContext implementation " + "found."); }
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 copyResourceFileTo(String destFileName, String resourceFileName) { if (destFileName == null || resourceFileName == null) throw new IllegalArgumentException("Argument cannot be null."); try { FileInputStream in = null; FileOutputStream out = null; URL url = HelperMethods.class.getResource(resourceFileName); if (url == null) { System.out.println("URL " + resourceFileName + " cannot be created."); return; } String fileName = url.getFile(); fileName = fileName.replaceAll("%20", " "); File resourceFile = new File(fileName); if (!resourceFile.isFile()) { System.out.println(fileName + " cannot be opened."); return; } in = new FileInputStream(resourceFile); out = new FileOutputStream(new File(destFileName)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ex) { ex.printStackTrace(); } }
11
Code Sample 1: public static void copyDirs(File sourceDir, File destDir) throws IOException { if (!destDir.exists()) destDir.mkdirs(); for (File file : sourceDir.listFiles()) { if (file.isDirectory()) { copyDirs(file, new File(destDir, file.getName())); } else { FileChannel srcChannel = new FileInputStream(file).getChannel(); File out = new File(destDir, file.getName()); out.createNewFile(); FileChannel dstChannel = new FileOutputStream(out).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } } Code Sample 2: private long generateUnixInstallShell(File unixShellFile, String instTemplate, File instClassFile) throws IOException { FileOutputStream byteWriter = new FileOutputStream(unixShellFile); InputStream is = getClass().getResourceAsStream("/" + instTemplate); InputStreamReader isr = new InputStreamReader(is); LineNumberReader reader = new LineNumberReader(isr); String content = ""; String installClassStartStr = "000000000000"; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassStartStr.length()); int installClassStartPos = 0; long installClassOffset = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallShell")); String line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassStart"))) { content += line + "\n"; line = reader.readLine(); } content += "InstallClassStart=" + installClassStartStr + "\n"; installClassStartPos = content.length() - 1 - 1 - installClassStartStr.length(); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassSize"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassSize=" + instClassFile.length() + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassName"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassName=" + instClassName_ + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# Install class"))) { content += line + "\n"; line = reader.readLine(); } if (line != null) content += line + "\n"; byteWriter.write(content.substring(0, installClassStartPos + 1).getBytes()); byteWriter.write(nf.format(content.length()).getBytes()); byteWriter.write(content.substring(installClassStartPos + 1 + installClassStartStr.length()).getBytes()); installClassOffset = content.length(); content = null; FileInputStream classStream = new FileInputStream(instClassFile); byte[] buf = new byte[2048]; int read = classStream.read(buf); while (read > 0) { byteWriter.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); reader.close(); byteWriter.close(); return installClassOffset; }
00
Code Sample 1: private String encryptUserPassword(int userId, String password) { password = password.trim(); if (password.length() == 0) { return ""; } else { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException ex) { throw new BoardRuntimeException(ex); } md.update(String.valueOf(userId).getBytes()); md.update(password.getBytes()); byte b[] = md.digest(); StringBuffer sb = new StringBuffer(1 + b.length * 2); for (int i = 0; i < b.length; i++) { int ii = b[i]; if (ii < 0) { ii = 256 + ii; } sb.append(getHexadecimalValue2(ii)); } return sb.toString(); } } 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); } } }
11
Code Sample 1: public static String encryption(String oldPass) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } md.update(oldPass.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { buf.append("0"); } buf.append(Integer.toHexString(i)); } String pass32 = buf.toString(); return pass32; } Code Sample 2: static void invalidSlave(String msg, Socket sock) throws IOException { BufferedReader _sinp = null; PrintWriter _sout = null; try { _sout = new PrintWriter(sock.getOutputStream(), true); _sinp = new BufferedReader(new InputStreamReader(sock.getInputStream())); _sout.println(msg); logger.info("NEW< " + msg); String txt = AsyncSlaveListener.readLine(_sinp, 30); String sname = ""; String spass = ""; String shash = ""; try { String[] items = txt.split(" "); sname = items[1].trim(); spass = items[2].trim(); shash = items[3].trim(); } catch (Exception e) { throw new IOException("Slave Inititalization Faailed"); } String pass = sname + spass + _pass; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(pass.getBytes()); String hash = AsyncSlaveListener.hash2hex(md5.digest()).toLowerCase(); if (!hash.equals(shash)) { throw new IOException("Slave Inititalization Faailed"); } } catch (Exception e) { } throw new IOException("Slave Inititalization Faailed"); }
00
Code Sample 1: private String handleRequest(String url, boolean get) { HttpURLConnection c = null; InputStream is = null; ByteArrayInputStream bais; byte[] buf; String temp, ret = ""; int response, len, i; try { c = (HttpURLConnection) new URL(url).openConnection(); if (get) c.setRequestMethod("GET"); else c.setRequestMethod("HEAD"); response = c.getResponseCode(); if (get) { is = c.getInputStream(); len = (int) c.getContentLength(); if (len > 0) { byte[] data = new byte[len]; for (i = 0; i < len; i++) { data[i] = (byte) is.read(); } bytein += data.length; bais = new ByteArrayInputStream(data); while (bais.available() > 0) { buf = Utils.readLine(bais); if (buf != null) { temp = byteArrayToString(buf, encoding, utf8detect); inqueue.addElement(temp); } } } } if (is != null) is.close(); if (c != null) c.disconnect(); } catch (Exception e) { ret += "Request failed, continuing..."; return ret; } if (response != HttpStatus.SC_OK) { if (response != HttpStatus.SC_NOT_FOUND) { ret += "Error in connection to IRC server, aborting... "; ret += "Error: HTTP response code: " + response; } connected = false; return ret; } else return null; } Code Sample 2: public static final long copyFile(final File srcFile, final File dstFile, final long cpySize) throws IOException { if ((null == srcFile) || (null == dstFile)) return (-1L); final File dstFolder = dstFile.getParentFile(); if ((!dstFolder.exists()) && (!dstFolder.mkdirs())) throw new IOException("Failed to created destination folder(s)"); FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(srcFile).getChannel(); dstChannel = new FileOutputStream(dstFile).getChannel(); final long srcLen = srcFile.length(), copyLen = dstChannel.transferFrom(srcChannel, 0, (cpySize < 0L) ? srcLen : cpySize); if ((cpySize < 0L) && (copyLen != srcLen)) return (-2L); return copyLen; } finally { FileUtil.closeAll(srcChannel, dstChannel); } }
11
Code Sample 1: public static void copyFile(String inputFile, String outputFile) throws IOException { FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); for (int b = fis.read(); b != -1; b = fis.read()) fos.write(b); fos.close(); fis.close(); } Code Sample 2: public void searchEntity(HttpServletRequest req, HttpServletResponse resp, SearchCommand command) { setHeader(resp); logger.debug("Search: Looking for the entity with the id:" + command.getSearchedid()); String login = command.getLogin(); String password = command.getPassword(); SynchronizableUser currentUser = userAccessControl.authenticate(login, password); if (currentUser != null) { try { File tempFile = File.createTempFile("medoo", "search"); OutputStream fos = new FileOutputStream(tempFile); syncServer.searchEntity(currentUser, command.getSearchedid(), fos); InputStream fis = new FileInputStream(tempFile); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); } catch (IOException ioe) { logger.error(ioe.getMessage(), ioe); } catch (ImogSerializationException ex) { logger.error(ex.getMessage(), ex); } } else { try { OutputStream out = resp.getOutputStream(); out.write("-ERROR-".getBytes()); out.flush(); out.close(); logger.debug("Search: user " + login + " has not been authenticated"); } catch (IOException ioe) { ioe.printStackTrace(); } } }
11
Code Sample 1: public static void fileCopy(File sourceFile, File destFile) throws IOException { FileChannel source = null; FileChannel destination = null; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(sourceFile); fos = new FileOutputStream(destFile); source = fis.getChannel(); destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); } finally { fis.close(); fos.close(); if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public OOXMLSignatureService(InputStream documentInputStream, OutputStream documentOutputStream, SignatureFacet signatureFacet, String role, IdentityDTO identity, byte[] photo, RevocationDataService revocationDataService, TimeStampService timeStampService, DigestAlgo signatureDigestAlgo) throws IOException { super(signatureDigestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".ooxml"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(signatureFacet); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); XAdESSignatureFacet xadesSignatureFacet = super.getXAdESSignatureFacet(); xadesSignatureFacet.setRole(role); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } }
11
Code Sample 1: public void xtestGetThread() throws Exception { GMSearchOptions options = new GMSearchOptions(); options.setFrom(loginInfo.getUsername() + "*"); options.setSubject("message*"); GMSearchResponse mail = client.getMail(options); for (Iterator it = mail.getThreadSnapshots().iterator(); it.hasNext(); ) { GMThreadSnapshot threadSnapshot = (GMThreadSnapshot) it.next(); GMThread thread = client.getThread(threadSnapshot.getThreadID()); log.info("Most Recent Thread: " + thread); for (Iterator iter = thread.getMessages().iterator(); iter.hasNext(); ) { GMMessage message = (GMMessage) iter.next(); log.info("Message: " + message); Iterable<GMAttachment> attachments = message.getAttachments(); for (Iterator iterator = attachments.iterator(); iterator.hasNext(); ) { GMAttachment attachment = (GMAttachment) iterator.next(); String ext = FilenameUtils.getExtension(attachment.getFilename()); if (ext.trim().length() > 0) ext = "." + ext; String base = FilenameUtils.getBaseName(attachment.getFilename()); File file = File.createTempFile(base, ext, new File(System.getProperty("user.home"))); log.info("Saving attachment: " + file.getPath()); InputStream attStream = client.getAttachmentAsStream(attachment.getId(), message.getMessageID()); IOUtils.copy(attStream, new FileOutputStream(file)); attStream.close(); assertEquals(file.length(), attachment.getSize()); log.info("Done. Successfully saved: " + file.getPath()); file.delete(); } } } } Code Sample 2: public static final void copyFile(String srcFilename, String dstFilename) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; FileChannel ifc = null; FileChannel ofc = null; Util.copyBuffer.clear(); try { fis = new FileInputStream(srcFilename); ifc = fis.getChannel(); fos = new FileOutputStream(dstFilename); ofc = fos.getChannel(); int sz = (int) ifc.size(); int n = 0; while (n < sz) { if (ifc.read(Util.copyBuffer) < 0) { break; } Util.copyBuffer.flip(); n += ofc.write(Util.copyBuffer); Util.copyBuffer.compact(); } } finally { try { if (ifc != null) { ifc.close(); } else if (fis != null) { fis.close(); } } catch (IOException exc) { } try { if (ofc != null) { ofc.close(); } else if (fos != null) { fos.close(); } } catch (IOException exc) { } } }
11
Code Sample 1: public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(""); fc.setMultiSelectionEnabled(false); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); int option = 0; boolean save = m_data != null; if (save) option = fc.showSaveDialog(this); else option = fc.showOpenDialog(this); if (option != JFileChooser.APPROVE_OPTION) return; File file = fc.getSelectedFile(); if (file == null) return; log.info(file.toString()); try { if (save) { FileOutputStream os = new FileOutputStream(file); byte[] buffer = (byte[]) m_data; os.write(buffer); os.flush(); os.close(); log.config("Save to " + file + " #" + buffer.length); } else { FileInputStream is = new FileInputStream(file); ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 8]; int length = -1; while ((length = is.read(buffer)) != -1) os.write(buffer, 0, length); is.close(); byte[] data = os.toByteArray(); m_data = data; log.config("Load from " + file + " #" + data.length); os.close(); } } catch (Exception ex) { log.log(Level.WARNING, "Save=" + save, ex); } try { fireVetoableChange(m_columnName, null, m_data); } catch (PropertyVetoException pve) { } } Code Sample 2: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
11
Code Sample 1: public static void copyFile(File src, File dest, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file: " + dest); } } byte[] buffer = new byte[1]; 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(); } } } } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public IOCacheArray(final File file, int capacity, final IIOCacheArrayObjectMaker iomaker, int chunkSize, String name) { super(capacity, null, chunkSize, name); generator = new ICacheArrayObjectMaker() { FileOutputStream outStream; FileInputStream inStream; FileChannel outChannel; FileChannel inChannel; boolean inited = false; private synchronized void init() { if (!inited) { try { outStream = new FileOutputStream(file); inStream = new FileInputStream(file); outChannel = outStream.getChannel(); inChannel = inStream.getChannel(); } catch (FileNotFoundException foe) { Logging.errorln("IOCacheArray constuctor error: Could not open file " + file + ". Exception " + foe); Logging.errorln("outStream " + outStream + " inStream " + inStream + " outchan " + outChannel + " inchannel " + inChannel); } } inited = true; } public Object make(int itemIndex, int baseIndex, Object[] data) { init(); return iomaker.read(inChannel, itemIndex, baseIndex, data); } public boolean flush(int baseIndex, Object[] data) { init(); return iomaker.write(outChannel, baseIndex, data); } public CacheArrayBlockSummary summarize(int baseIndex, Object[] data) { init(); return iomaker.summarize(baseIndex, data); } }; } Code Sample 2: private void channelCopy(File source, File dest) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { srcChannel.close(); dstChannel.close(); } }
11
Code Sample 1: public static String encode(String text) { try { byte[] hash = new byte[32]; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("UTF-8"), 0, text.length()); hash = md.digest(); return MD5.toHex(hash); } catch (NoSuchAlgorithmException ex) { return ex.getMessage(); } catch (UnsupportedEncodingException ex) { return ex.getMessage(); } } Code Sample 2: private static synchronized byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance(algoritmo); md.update(frase.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { return null; } }
11
Code Sample 1: protected int insertRecord(PutMetadataRequest request, PutMetadataInfo info) throws ImsServiceException, SQLException { Connection con = null; boolean autoCommit = true; PreparedStatement st = null; ResultSet rs = null; int nRows = 0; String sXml = info.getXml(); String sUuid = info.getUuid(); String sName = info.getName(); String sThumbnailBinary = info.getThumbnailBinary(); String sTable = this.getResourceTableName(); String sDataTable = this.getResourceDataTableName(); long id = doesRecordExist(sTable, sUuid); try { ManagedConnection mc = returnConnection(); con = mc.getJdbcConnection(); autoCommit = con.getAutoCommit(); con.setAutoCommit(false); if (id < 0) { StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO ").append(sTable); sql.append(" ("); sql.append("DOCUUID,"); sql.append("TITLE,"); sql.append("OWNER"); sql.append(")"); sql.append(" VALUES(?,?,?)"); logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); int n = 1; st.setString(n++, sUuid); st.setString(n++, sName); st.setInt(n++, this.publisher.getLocalID()); nRows = st.executeUpdate(); closeStatement(st); if (nRows > 0) { if (getIsDbCaseSensitive(this.getRequestContext())) { st = con.prepareStatement("SELECT id FROM " + sTable + " WHERE UPPER(docuuid)=?"); } else { st = con.prepareStatement("SELECT id FROM " + sTable + " WHERE docuuid=?"); } st.setString(1, sUuid.toUpperCase()); rs = st.executeQuery(); rs.next(); id = rs.getLong(1); closeStatement(st); request.setActionStatus(ImsRequest.ACTION_STATUS_OK); sql = new StringBuffer(); sql.append("INSERT INTO ").append(sDataTable); sql.append(" (DOCUUID,ID,XML)"); sql.append(" VALUES(?,?,?)"); logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); st.setString(1, sUuid); st.setLong(2, id); st.setString(3, sXml); st.executeUpdate(); } } else { this.authorize(request, sUuid); StringBuffer sql = new StringBuffer(); sql.append("UPDATE ").append(sTable); sql.append(" SET "); if (!request.getLockTitle()) { sql.append("TITLE=?, "); } sql.append("OWNER=?, "); sql.append("UPDATEDATE=?"); sql.append(" WHERE DOCUUID=?"); logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); int n = 1; if (!request.getLockTitle()) { st.setString(n++, sName); } st.setInt(n++, this.publisher.getLocalID()); st.setTimestamp(n++, new Timestamp(System.currentTimeMillis())); st.setString(n++, sUuid); nRows = st.executeUpdate(); if (nRows > 0) { request.setActionStatus(ImsRequest.ACTION_STATUS_REPLACED); } closeStatement(st); sql = new StringBuffer(); if (doesRecordExist(sDataTable, sUuid) >= 0) { sql.append("UPDATE ").append(sDataTable); sql.append(" SET DOCUUID=?, XML=?, THUMBNAIL=?"); sql.append(" WHERE ID=?"); } else { sql.append("INSERT INTO ").append(sDataTable); sql.append(" (DOCUUID, XML,THUMBNAIL,ID)"); sql.append(" VALUES(?,?,?,?)"); } logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); st.setString(1, sUuid); st.setString(2, sXml); st.setBytes(3, null); st.setLong(4, id); st.executeUpdate(); } con.commit(); } catch (ImsServiceException ex) { if (con != null) { con.rollback(); } throw ex; } catch (SQLException ex) { if (con != null) { con.rollback(); } throw ex; } finally { closeResultSet(rs); closeStatement(st); if (con != null) { con.setAutoCommit(autoCommit); } } if ((sThumbnailBinary != null) && (sThumbnailBinary.length() > 0)) { this.updateThumbnail(sThumbnailBinary, sUuid); } return nRows; } Code Sample 2: public ProgramSymbol deleteProgramSymbol(int id) throws AdaptationException { ProgramSymbol programSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramSymbols " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete program symbol failed."; log.error(msg); throw new AdaptationException(msg); } programSymbol = getProgramSymbol(resultSet); query = "DELETE FROM ProgramSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProgramSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return programSymbol; }
11
Code Sample 1: private void copyFile(File source, File dest) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: protected static StringBuffer doRESTOp(String urlString) throws Exception { StringBuffer result = new StringBuffer(); String restUrl = urlString; int p = restUrl.indexOf("://"); if (p < 0) restUrl = System.getProperty("fedoragsearch.protocol") + "://" + System.getProperty("fedoragsearch.hostport") + "/" + System.getProperty("fedoragsearch.path") + restUrl; URL url = null; url = new URL(restUrl); URLConnection conn = null; conn = url.openConnection(); conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode((System.getProperty("fedoragsearch.fgsUserName") + ":" + System.getProperty("fedoragsearch.fgsPassword")).getBytes())); conn.connect(); content = null; content = conn.getContent(); String line; BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) content)); while ((line = br.readLine()) != null) result.append(line); return result; } Code Sample 2: List<String> HttpGet(URL url) throws IOException { List<String> responseList = new ArrayList<String>(); Logger.getInstance().logInfo("HTTP GET: " + url, null, null); URLConnection con = url.openConnection(); con.setAllowUserInteraction(false); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) responseList.add(inputLine); in.close(); return responseList; }
00
Code Sample 1: protected String encrypt(final String data, final String key) throws CryptographicFailureException { Validate.notNull(data, "Provided data cannot be null."); Validate.notNull(key, "Provided key name cannot be null."); final PublicKey pk = getPublicKey(key); if (pk == null) { throw new CryptographicFailureException("PublicKeyNotFound", String.format("Cannot find public key '%s'", key)); } try { final Cipher cipher = Cipher.getInstance(pk.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, pk); final ByteArrayInputStream bin = new ByteArrayInputStream(data.getBytes()); final CipherInputStream cin = new CipherInputStream(bin, cipher); final ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(cin, bout); return new String(Base64.encodeBase64(bout.toByteArray())); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(String.format("Cannot find instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (NoSuchPaddingException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (InvalidKeyException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (IOException e) { throw new IllegalStateException("Cannot build in-memory cipher copy", e); } } Code Sample 2: public static String md5(String str) { StringBuffer buf = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] data = new byte[32]; md.update(str.getBytes(md5Encoding), 0, str.length()); data = md.digest(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } } catch (Exception e) { errorLog("{Malgn.md5} " + e.getMessage()); } return buf.toString(); }
11
Code Sample 1: public static void copyFileTo(String destFileName, String resourceFileName) { if (destFileName == null || resourceFileName == null) throw new IllegalArgumentException("Argument cannot be null."); try { FileInputStream in = null; FileOutputStream out = null; File resourceFile = new File(resourceFileName); if (!resourceFile.isFile()) { System.out.println(resourceFileName + " cannot be opened."); return; } in = new FileInputStream(resourceFile); out = new FileOutputStream(new File(destFileName)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ex) { ex.printStackTrace(); } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String zOntoJsonApiUrl = getInitParameter("zOntoJsonApiServletUrl"); URL url = new URL(zOntoJsonApiUrl + "?" + req.getQueryString()); resp.setContentType("text/html"); InputStreamReader bf = new InputStreamReader(url.openStream()); BufferedReader bbf = new BufferedReader(bf); String response = ""; String line = bbf.readLine(); PrintWriter out = resp.getWriter(); while (line != null) { response += line; line = bbf.readLine(); } out.print(response); out.close(); } Code Sample 2: public long saveDB(Connection con, long id, boolean commit) throws SQLException { StringBuffer SQL = null; Statement statement = null; ResultSet result_set = null; try { statement = con.createStatement(); if (id < 0) { id = QueryUtils.sequenceGetNextID(con, "PATTERN_OUTLINE"); } else { deleteDB(con, id); } SQL = new StringBuffer("insert into "); SQL.append("PATTERN_OUTLINE values ("); SQL.append(id); SQL.append(","); SQL.append(XColor.toInt(pattern.getPatternColor())); SQL.append(","); SQL.append(pattern.getPatternStyle()); SQL.append(","); SQL.append(pattern.getPatternDensity()); SQL.append(","); SQL.append(XColor.toInt(pattern.getBackgroundColor())); SQL.append(","); SQL.append(XColor.toInt(outline.getColor())); SQL.append(","); SQL.append(outline.getStyle()); SQL.append(","); SQL.append(outline.getWidth()); SQL.append(")"); statement.executeUpdate(new String(SQL)); SQL = null; if (commit) { con.commit(); } } catch (SQLException e) { System.err.println(getClass().getName() + ":" + e + " SQL:=" + SQL); if (commit) { con.rollback(); } throw e; } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { } } } return saveDB(con, id, false); }
11
Code Sample 1: public String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public static URL getAuthenticationURL(String apiKey, String permission, String sharedSecret) throws Exception { String apiSig = sharedSecret + "api_key" + apiKey + "perms" + permission; MessageDigest m = MessageDigest.getInstance("MD5"); m.update(apiSig.getBytes(), 0, apiSig.length()); apiSig = new BigInteger(1, m.digest()).toString(16); StringBuffer buffer = new StringBuffer(); buffer.append("http://flickr.com/services/auth/?"); buffer.append("api_key=" + apiKey); buffer.append("&").append("perms=").append(permission); buffer.append("&").append("api_sig=").append(apiSig); return new URL(buffer.toString()); }
11
Code Sample 1: private String hash(String message) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(12345); md.update(saltString.getBytes()); md.update(message.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString().trim(); return digestStr; } Code Sample 2: @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnRegister) { Error.log(6002, "Bot�o cadastrar pressionado por " + login + "."); if (nameUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo nome requerido"); nameUser.setFocusable(true); return; } if (loginUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo login requerido"); loginUser.setFocusable(true); return; } String group = ""; if (groupUser.getSelectedIndex() == 0) group = "admin"; else if (groupUser.getSelectedIndex() == 1) group = "user"; else { JOptionPane.showMessageDialog(null, "Campo grupo n�o selecionado"); return; } if (new String(passwordUser1.getPassword()).compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo senha requerido"); passwordUser1.setFocusable(true); return; } String password1 = new String(passwordUser1.getPassword()); String password2 = new String(passwordUser2.getPassword()); if (password1.compareTo(password2) != 0) { JOptionPane.showMessageDialog(null, "Senhas n�o casam"); passwordUser1.setText(""); passwordUser2.setText(""); passwordUser1.setFocusable(true); return; } char c = passwordUser1.getPassword()[0]; int i = 1; for (i = 1; i < password1.length(); i++) { if (passwordUser1.getPassword()[i] != c) { break; } c = passwordUser1.getPassword()[i]; } if (i == password1.length()) { JOptionPane.showMessageDialog(null, "Senha fraca"); return; } if (password1.length() < 6) { JOptionPane.showMessageDialog(null, "Senha deve ter mais que 6 digitos"); return; } if (numPasswordOneUseUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo n�mero de senhas de uso �nico requerido"); return; } if (!(Integer.parseInt(numPasswordOneUseUser.getText()) > 0 && Integer.parseInt(numPasswordOneUseUser.getText()) < 41)) { JOptionPane.showMessageDialog(null, "N�mero de senhas de uso �nico entre 1 e 40"); return; } ResultSet rs; Statement stmt; String sql; String result = ""; sql = "select login from Usuarios where login='" + loginUser.getText() + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("login"); } rs.close(); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (result.compareTo("") != 0) { JOptionPane.showMessageDialog(null, "Login " + result + " j� existe"); loginUser.setText(""); loginUser.setFocusable(true); return; } String outputDigest = ""; try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password1.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); outputDigest = bigInt.toString(16); } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } sql = "insert into Usuarios (login,password,tries_personal,tries_one_use," + "grupo,description) values " + "('" + loginUser.getText() + "','" + outputDigest + "',0,0,'" + group + "','" + nameUser.getText() + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r; Vector<Integer> passwordVector = new Vector<Integer>(); for (i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(loginUser.getText() + ".txt", false)); for (i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + loginUser.getText() + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException exception) { exception.printStackTrace(); } JOptionPane.showMessageDialog(null, "Usu�rio " + loginUser.getText() + " foi cadastrado com sucesso."); dispose(); } if (e.getSource() == btnCancel) { Error.log(6003, "Bot�o voltar de cadastrar para o menu principal pressionado por " + login + "."); dispose(); } }
11
Code Sample 1: @Override public void actionPerformed(ActionEvent event) { if (event.getSource() == btnChange) { Error.log(7002, "Bot�o alterar pressionado por " + login + "."); if (new String(passwordUser1.getPassword()).compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo senha requerido"); passwordUser1.setFocusable(true); return; } String password1 = new String(passwordUser1.getPassword()); String password2 = new String(passwordUser2.getPassword()); if (password1.compareTo(password2) != 0) { JOptionPane.showMessageDialog(null, "Senhas n�o casam"); passwordUser1.setText(""); passwordUser2.setText(""); passwordUser1.setFocusable(true); return; } char c = passwordUser1.getPassword()[0]; int j = 1; for (j = 1; j < password1.length(); j++) { if (passwordUser1.getPassword()[j] != c) { break; } c = passwordUser1.getPassword()[j]; } if (j == password1.length()) { JOptionPane.showMessageDialog(null, "Senha fraca"); return; } if (password1.length() < 6) { JOptionPane.showMessageDialog(null, "Senha deve ter mais que 6 digitos"); return; } if (numPasswordOneUseUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo n�mero de senhas de uso �nico requerido"); return; } if (!(Integer.parseInt(numPasswordOneUseUser.getText()) > 0 && Integer.parseInt(numPasswordOneUseUser.getText()) < 41)) { JOptionPane.showMessageDialog(null, "N�mero de senhas de uso �nico entre 1 e 40"); return; } String outputDigest = ""; try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password1.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); outputDigest = bigInt.toString(16); } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } Statement stmt; String sql; sql = "update Usuarios set password = '" + outputDigest + "' where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } sql = "delete from Senhas_De_Unica_Vez where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r; Vector<Integer> passwordVector = new Vector<Integer>(); for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(login + ".txt", false)); for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + login + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException exception) { exception.printStackTrace(); } JOptionPane.showMessageDialog(null, "Usu�rio " + login + " foi alterado com sucesso."); dispose(); } if (event.getSource() == btnCancel) { Error.log(7003, "Bot�o voltar de alterar para o menu principal pressionado por " + login + "."); dispose(); } } Code Sample 2: private String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
11
Code Sample 1: protected void setTestContent(IDfDocument document, String testFileName) throws Exception { InputStream testFileIs = new BufferedInputStream(FileHelper.getFileAsStreamFromClassPath(testFileName)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(testFileIs, baos); String contentType = formatHelper.getFormatForExtension(FileHelper.getFileExtension(testFileName)); document.setContentType(contentType); document.setContent(baos); } Code Sample 2: private void appendArchive(File instClass) throws IOException { FileOutputStream out = new FileOutputStream(instClass.getName(), true); FileInputStream zipStream = new FileInputStream("install.jar"); byte[] buf = new byte[2048]; int read = zipStream.read(buf); while (read > 0) { out.write(buf, 0, read); read = zipStream.read(buf); } zipStream.close(); out.close(); }
11
Code Sample 1: public String getScenarioData(String urlForSalesData) throws IOException, Exception { InputStream inputStream = null; BufferedReader bufferedReader = null; DataInputStream input = null; StringBuffer sBuf = new StringBuffer(); Proxy proxy; if (httpWebProxyServer != null && Integer.toString(httpWebProxyPort) != null) { SocketAddress address = new InetSocketAddress(httpWebProxyServer, httpWebProxyPort); proxy = new Proxy(Proxy.Type.HTTP, address); } else { proxy = null; } proxy = null; URL url; try { url = new URL(urlForSalesData); HttpURLConnection httpUrlConnection; if (proxy != null) httpUrlConnection = (HttpURLConnection) url.openConnection(proxy); else httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setDoInput(true); httpUrlConnection.setRequestMethod("GET"); String name = rb.getString("WRAP_NAME"); String password = rb.getString("WRAP_PASSWORD"); Credentials simpleAuthCrentials = new Credentials(TOKEN_TYPE.SimpleApiAuthToken, name, password); ACSTokenProvider tokenProvider = new ACSTokenProvider(httpWebProxyServer, httpWebProxyPort, simpleAuthCrentials); String requestUriStr1 = "https://" + solutionName + "." + acmHostName + "/" + serviceName; String appliesTo1 = rb.getString("SIMPLEAPI_APPLIES_TO"); String token = tokenProvider.getACSToken(requestUriStr1, appliesTo1); httpUrlConnection.addRequestProperty("token", "WRAPv0.9 " + token); httpUrlConnection.addRequestProperty("solutionName", solutionName); httpUrlConnection.connect(); if (httpUrlConnection.getResponseCode() == HttpServletResponse.SC_UNAUTHORIZED) { List<TestSalesOrderService> salesOrderServiceBean = new ArrayList<TestSalesOrderService>(); TestSalesOrderService response = new TestSalesOrderService(); response.setResponseCode(HttpServletResponse.SC_UNAUTHORIZED); response.setResponseMessage(httpUrlConnection.getResponseMessage()); salesOrderServiceBean.add(response); } inputStream = httpUrlConnection.getInputStream(); input = new DataInputStream(inputStream); bufferedReader = new BufferedReader(new InputStreamReader(input)); String str; while (null != ((str = bufferedReader.readLine()))) { sBuf.append(str); } String responseString = sBuf.toString(); return responseString; } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } } Code Sample 2: public static void readTestData(String getDkpUrl) throws Exception { final URL url = new URL(getDkpUrl); final InputStream is = url.openStream(); try { final LineNumberReader rd = new LineNumberReader(new BufferedReader(new InputStreamReader(is))); String line = rd.readLine(); while (line != null) { System.out.println(line); line = rd.readLine(); } } finally { is.close(); } }
11
Code Sample 1: @Override public void copyFile2File(final File src, final File dest, final boolean force) throws C4JException { if (dest.exists()) if (force && !dest.delete()) throw new C4JException(format("Copying ‘%s’ to ‘%s’ failed; cannot overwrite existing file.", src.getPath(), dest.getPath())); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dest).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (src.canExecute()) dest.setExecutable(true, false); } catch (final IOException e) { throw new C4JException(format("Could not copy ‘%s’ to ‘%s’.", src.getPath(), dest.getPath()), e); } finally { if (inChannel != null) try { try { inChannel.close(); } catch (final IOException e) { throw new C4JException(format("Could not close input stream for ‘%s’.", src.getPath()), e); } } finally { if (outChannel != null) try { outChannel.close(); } catch (final IOException e) { throw new C4JException(format("Could not close output stream for ‘%s’.", dest.getPath()), e); } } } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static final void copy(File src, File dest) throws IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; if (!src.exists()) { throw new IOException("Source not found: " + src); } if (!src.canRead()) { throw new IOException("Source is unreadable: " + src); } if (src.isFile()) { if (!dest.exists()) { File parentdir = parent(dest); if (!parentdir.exists()) { parentdir.mkdir(); } } else if (dest.isDirectory()) { dest = new File(dest + File.separator + src); } } else if (src.isDirectory()) { if (dest.isFile()) { throw new IOException("Cannot copy directory " + src + " to file " + dest); } if (!dest.exists()) { dest.mkdir(); } } if (src.isFile()) { try { source = new FileInputStream(src); destination = new FileOutputStream(dest); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) { break; } destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { } } if (destination != null) { try { destination.close(); } catch (IOException e) { } } } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); for (int i = 0; i < files.length; i++) { targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target), new File(targetdest)); } else { try { source = new FileInputStream(target); destination = new FileOutputStream(targetdest); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) { break; } destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { } } if (destination != null) { try { destination.close(); } catch (IOException e) { } } } } } } } Code Sample 2: public static Document convertHtmlToXml(final InputStream htmlInputStream, final String classpathXsltResource, final String encoding) { Parser p = new Parser(); javax.xml.parsers.DocumentBuilder db; try { db = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error("", e); throw new RuntimeException(); } Document document = db.newDocument(); InputStream is = htmlInputStream; if (log.isDebugEnabled()) { ByteArrayOutputStream baos; baos = new ByteArrayOutputStream(); try { IOUtils.copy(is, baos); } catch (IOException e) { log.error("Fail to make input stream copy.", e); } IOUtils.closeQuietly(is); ByteArrayInputStream byteArrayInputStream; byteArrayInputStream = new ByteArrayInputStream(baos.toByteArray()); try { IOUtils.toString(new ByteArrayInputStream(baos.toByteArray()), "UTF-8"); } catch (IOException e) { log.error("", e); } IOUtils.closeQuietly(byteArrayInputStream); is = new ByteArrayInputStream(baos.toByteArray()); } try { InputSource iSource = new InputSource(is); iSource.setEncoding(encoding); Source transformerSource = new SAXSource(p, iSource); Result result = new DOMResult(document); Transformer xslTransformer = getTransformerByName(classpathXsltResource, false); try { xslTransformer.transform(transformerSource, result); } catch (TransformerException e) { throw new RuntimeException(e); } } finally { try { is.close(); } catch (Exception e) { log.warn("", e); } } return document; }
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 static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) dir.mkdir(); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); 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: private void saveFile(Folder folder, Object key, InputStream stream) throws FileManagerException { File file = new File(folder, key.toString()); LOGGER.debug("Writing file: " + file.getAbsolutePath()); Writer writer = null; Writer encodedWriter = null; try { encodedWriter = new OutputStreamWriter(new FileOutputStream(file), getEncodeCharset()); IOUtils.copy(stream, encodedWriter, getDecodeCharset()); LOGGER.info("saveFile(), decode charset: " + getDecodeCharset() + ", encode charset: " + getEncodeCharset()); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } finally { try { encodedWriter.close(); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } } } Code Sample 2: public static int save(File inputFile, File outputFile) throws IOException { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(inputFile); outputFile.getParentFile().mkdirs(); out = new FileOutputStream(outputFile); } catch (Exception e) { e.getMessage(); } try { return IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); try { if (out != null) { out.close(); } } catch (IOException ioe) { ioe.getMessage(); } try { if (in != null) { in.close(); } } catch (IOException ioe) { ioe.getMessage(); } } }
11
Code Sample 1: public static void generateCode(File flowFile, String packagePath, File destDir, File scriptRootFolder) throws IOException { InputStream javaSrcIn = generateCode(flowFile, packagePath, scriptRootFolder); File outputFolder = new File(destDir, packagePath.replace('.', File.separatorChar)); String fileName = flowFile.getName(); fileName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + Consts.FILE_EXTENSION_GROOVY; File outputFile = new File(outputFolder, fileName); OutputStream javaSrcOut = new FileOutputStream(outputFile); IOUtils.copyBufferedStream(javaSrcIn, javaSrcOut); javaSrcIn.close(); javaSrcOut.close(); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private void copyfile(File srcFile, File dstDir) throws FileNotFoundException, IOException { if (srcFile.isDirectory()) { File newDestDir = new File(dstDir, srcFile.getName()); newDestDir.mkdir(); String fileNameList[] = srcFile.list(); for (int i = 0; i < fileNameList.length; i++) { File newSouceFile = new File(srcFile, fileNameList[i]); copyfile(newSouceFile, newDestDir); } } else { File newDestFile = new File(dstDir, srcFile.getName()); FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(newDestFile); FileChannel inChannel = in.getChannel(); FileChannel outChannel = out.getChannel(); long i; Logger.log("copyFile before- copiedSize = " + copiedSize); for (i = 0; i < srcFile.length() - BLOCK_LENGTH; i += BLOCK_LENGTH) { synchronized (this) { inChannel.transferTo(i, BLOCK_LENGTH, outChannel); copiedSize += BLOCK_LENGTH; } } synchronized (this) { inChannel.transferTo(i, srcFile.length() - i, outChannel); copiedSize += srcFile.length() - i; } Logger.log("copyFile after copy- copiedSize = " + copiedSize + "srcFile.length = " + srcFile.length() + "diff = " + (copiedSize - srcFile.length())); in.close(); out.close(); outChannel = null; Logger.log("File copied."); } } Code Sample 2: public static void checkAndUpdateGameData() { new ErrThread() { @Override public void handledRun() throws Throwable { try { URL url = new URL(ONLINE_CLIENT_DATA + "gamedata.xml"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); int lastversion = 0; String readHeader1 = br.readLine(); String readHeader2 = br.readLine(); String[] parts = readHeader2.split(" "); lastversion = new Integer(parts[1]); GameDatabase.loadVersion(); if (GameDatabase.version < lastversion) { Logger.log(LogTypes.LOG, "Downloading new gamedata"); BufferedOutputStream bo = null; File destfile = new File(GameDatabase.dataFilePath); if (!destfile.createNewFile()) { destfile.delete(); destfile.createNewFile(); } bo = new BufferedOutputStream(new FileOutputStream(destfile)); bo.write((readHeader1 + "\n").getBytes()); bo.write((readHeader2 + "\n").getBytes()); int readedbyte; while ((readedbyte = br.read()) != -1) { bo.write(readedbyte); } bo.flush(); try { br.close(); bo.close(); } catch (Exception ex) { Logger.log(ex); } } } catch (java.net.UnknownHostException unknownHost) { Logger.log("Sourceforge is down, cannot update gamedata"); } catch (Exception e) { JOptionPane.showMessageDialog(FrameOrganizer.getClientFrame(), "The gamedata is outdated, but Coopnet couldn't update it!", "Gamedata outdated", JOptionPane.INFORMATION_MESSAGE); throw e; } finally { GameDatabase.loadVersion(); GameDatabase.load("", GameDatabase.dataFilePath); GameDatabase.detectGames(); } } }.start(); }
11
Code Sample 1: private void saveAttachment(long messageId, Part attachment, boolean saveAsNew) throws IOException, MessagingException { long attachmentId = -1; Uri contentUri = null; int size = -1; File tempAttachmentFile = null; if ((!saveAsNew) && (attachment instanceof LocalAttachmentBodyPart)) { attachmentId = ((LocalAttachmentBodyPart) attachment).getAttachmentId(); } if (attachment.getBody() != null) { Body body = attachment.getBody(); if (body instanceof LocalAttachmentBody) { contentUri = ((LocalAttachmentBody) body).getContentUri(); } else { InputStream in = attachment.getBody().getInputStream(); tempAttachmentFile = File.createTempFile("att", null, mAttachmentsDir); FileOutputStream out = new FileOutputStream(tempAttachmentFile); size = IOUtils.copy(in, out); in.close(); out.close(); } } if (size == -1) { String disposition = attachment.getDisposition(); if (disposition != null) { String s = MimeUtility.getHeaderParameter(disposition, "size"); if (s != null) { size = Integer.parseInt(s); } } } if (size == -1) { size = 0; } String storeData = Utility.combine(attachment.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA), ','); String name = MimeUtility.getHeaderParameter(attachment.getContentType(), "name"); String contentId = attachment.getContentId(); if (attachmentId == -1) { ContentValues cv = new ContentValues(); cv.put("message_id", messageId); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); cv.put("store_data", storeData); cv.put("size", size); cv.put("name", name); cv.put("mime_type", attachment.getMimeType()); cv.put("content_id", contentId); attachmentId = mDb.insert("attachments", "message_id", cv); } else { ContentValues cv = new ContentValues(); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); cv.put("size", size); cv.put("content_id", contentId); cv.put("message_id", messageId); mDb.update("attachments", cv, "id = ?", new String[] { Long.toString(attachmentId) }); } if (tempAttachmentFile != null) { File attachmentFile = new File(mAttachmentsDir, Long.toString(attachmentId)); tempAttachmentFile.renameTo(attachmentFile); attachment.setBody(new LocalAttachmentBody(contentUri, mContext)); ContentValues cv = new ContentValues(); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); mDb.update("attachments", cv, "id = ?", new String[] { Long.toString(attachmentId) }); } if (attachment instanceof LocalAttachmentBodyPart) { ((LocalAttachmentBodyPart) attachment).setAttachmentId(attachmentId); } } Code Sample 2: public Void doInBackground() { setProgress(0); for (int i = 0; i < uploadFiles.size(); i++) { String filePath = uploadFiles.elementAt(i).getFilePath(); String fileName = uploadFiles.elementAt(i).getFileName(); String fileMsg = "Uploading file " + (i + 1) + "/" + uploadFiles.size() + "\n"; this.publish(fileMsg); try { File inFile = new File(filePath); FileInputStream in = new FileInputStream(inFile); byte[] inBytes = new byte[(int) chunkSize]; int count = 1; int maxCount = (int) (inFile.length() / chunkSize); if (inFile.length() % chunkSize > 0) { maxCount++; } int readCount = 0; readCount = in.read(inBytes); while (readCount > 0) { File splitFile = File.createTempFile("upl", null, null); String splitName = splitFile.getPath(); FileOutputStream out = new FileOutputStream(splitFile); out.write(inBytes, 0, readCount); out.close(); boolean chunkFinal = (count == maxCount); fileMsg = " - Sending chunk " + count + "/" + maxCount + ": "; this.publish(fileMsg); boolean uploadSuccess = false; int uploadTries = 0; while (!uploadSuccess && uploadTries <= 5) { uploadTries++; boolean uploadStatus = upload(splitName, fileName, count, chunkFinal); if (uploadStatus) { fileMsg = "OK\n"; this.publish(fileMsg); uploadSuccess = true; } else { fileMsg = "ERROR\n"; this.publish(fileMsg); uploadSuccess = false; } } if (!uploadSuccess) { fileMsg = "There was an error uploading your files. Please let the pipeline administrator know about this problem. Cut and paste the messages in this box, and supply them.\n"; this.publish(fileMsg); errorFlag = true; return null; } float thisProgress = (count * 100) / (maxCount); float completeProgress = (i * (100 / uploadFiles.size())); float totalProgress = completeProgress + (thisProgress / uploadFiles.size()); setProgress((int) totalProgress); splitFile.delete(); readCount = in.read(inBytes); count++; } } catch (Exception e) { this.publish(e.toString()); } } return null; }
11
Code Sample 1: public boolean authenticate() { if (empresaFeta == null) empresaFeta = new AltaEmpresaBean(); log.info("authenticating {0}", credentials.getUsername()); boolean bo; try { String passwordEncriptat = credentials.getPassword(); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(passwordEncriptat.getBytes(), 0, passwordEncriptat.length()); passwordEncriptat = new BigInteger(1, m.digest()).toString(16); Query q = entityManager.createQuery("select usuari from Usuaris usuari where usuari.login=? and usuari.password=?"); q.setParameter(1, credentials.getUsername()); q.setParameter(2, passwordEncriptat); Usuaris usuari = (Usuaris) q.getSingleResult(); bo = (usuari != null); if (bo) { if (usuari.isEsAdministrador()) { identity.addRole("admin"); } else { carregaDadesEmpresa(); log.info("nom de l'empresa: " + empresaFeta.getInstance().getNom()); } } } catch (Throwable t) { log.error(t); bo = false; } log.info("L'usuari {0} s'ha identificat bé? : {1} ", credentials.getUsername(), bo ? "si" : "no"); return bo; } Code Sample 2: private final String createMD5(String pwd) throws Exception { MessageDigest md = (MessageDigest) MessageDigest.getInstance("MD5").clone(); md.update(pwd.getBytes("UTF-8")); byte[] pd = md.digest(); StringBuffer app = new StringBuffer(); for (int i = 0; i < pd.length; i++) { String s2 = Integer.toHexString(pd[i] & 0xFF); app.append((s2.length() == 1) ? "0" + s2 : s2); } return app.toString(); }
00
Code Sample 1: @Override public HttpResponse execute() throws IOException { if (this.method == HttpMethod.GET) { String url = this.toString(); if (url.length() > this.cutoff) { if (log.isLoggable(Level.FINER)) log.finer("URL length " + url.length() + " too long, converting GET to POST: " + url); String rebase = this.baseURL + "?method=GET"; return this.execute(HttpMethod.POST, rebase); } } return super.execute(); } Code Sample 2: public boolean createUser(String username, String password, String name) throws Exception { boolean user_created = false; try { statement = connect.prepareStatement("SELECT COUNT(*) from toepen.users WHERE username = ? LIMIT 1"); statement.setString(1, username); resultSet = statement.executeQuery(); resultSet.next(); if (resultSet.getInt(1) == 0) { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); long ctime = System.currentTimeMillis() / 1000; statement = connect.prepareStatement("INSERT INTO toepen.users " + "(username, password, name, ctime) " + "VALUES (?, ?, ?, ?)"); statement.setString(1, username); statement.setString(2, password_hash); statement.setString(3, name); statement.setLong(4, ctime); if (statement.executeUpdate() > 0) { user_created = true; } } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_created; } }
11
Code Sample 1: private void loadMap() { final String wordList = "vietwordlist.txt"; try { File dataFile = new File(supportDir, wordList); if (!dataFile.exists()) { final ReadableByteChannel input = Channels.newChannel(ClassLoader.getSystemResourceAsStream("dict/" + dataFile.getName())); final FileChannel output = new FileOutputStream(dataFile).getChannel(); output.transferFrom(input, 0, 1000000L); input.close(); output.close(); } long fileLastModified = dataFile.lastModified(); if (map == null) { map = new HashMap<String, String>(); } else { if (fileLastModified <= mapLastModified) { return; } map.clear(); } mapLastModified = fileLastModified; BufferedReader bs = new BufferedReader(new InputStreamReader(new FileInputStream(dataFile), "UTF-8")); String accented; while ((accented = bs.readLine()) != null) { String plain = VietUtilities.stripDiacritics(accented); map.put(plain.toLowerCase(), accented); } bs.close(); } catch (IOException e) { map = null; e.printStackTrace(); JOptionPane.showMessageDialog(this, myResources.getString("Cannot_find_\"") + wordList + myResources.getString("\"_in\n") + supportDir.toString(), VietPad.APP_NAME, JOptionPane.ERROR_MESSAGE); } } Code Sample 2: private void fileCopy(File filename) throws IOException { if (this.stdOut) { this.fileDump(filename); return; } File source_file = new File(spoolPath + "/" + filename); File destination_file = new File(copyPath + "/" + filename); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("no such source file: " + source_file); if (!source_file.canRead()) throw new FileCopyException("source file is unreadable: " + source_file); if (destination_file.exists()) { if (destination_file.isFile()) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); if (!destination_file.canWrite()) throw new FileCopyException("destination file is unwriteable: " + destination_file); if (!this.overwrite) { System.out.print("File " + destination_file + " already exists. Overwrite? (Y/N): "); System.out.flush(); if (!in.readLine().toUpperCase().equals("Y")) throw new FileCopyException("copy cancelled."); } } else throw new FileCopyException("destination is not a file: " + destination_file); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("destination directory doesn't exist: " + destination_file); if (!parentdir.canWrite()) throw new FileCopyException("destination directory is unwriteable: " + destination_file); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while ((bytes_read = source.read(buffer)) != -1) { destination.write(buffer, 0, bytes_read); } System.out.println("File " + filename + " successfull copied to " + destination_file); if (this.keep == false && source_file.isFile()) { try { source.close(); } catch (Exception e) { } if (source_file.delete()) { new File(this.spoolPath + "/info/" + filename + ".desc").delete(); } } } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.flush(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } }
00
Code Sample 1: public void copyFile(File from, File to) { try { InputStream in = new FileInputStream(from); OutputStream out = new FileOutputStream(to); int readCount; byte[] bytes = new byte[1024]; while ((readCount = in.read(bytes)) != -1) { out.write(bytes, 0, readCount); } out.flush(); in.close(); out.close(); } catch (Exception ex) { throw new BuildException(ex.getMessage(), ex); } } Code Sample 2: private void sortMasters() { masterCounter = 0; for (int i = 0; i < maxID; i++) { if (users[i].getMasterPoints() > 0) { masterHandleList[masterCounter] = users[i].getHandle(); masterPointsList[masterCounter] = users[i].getMasterPoints(); masterCounter = masterCounter + 1; } } for (int i = masterCounter; --i >= 0; ) { for (int j = 0; j < i; j++) { if (masterPointsList[j] > masterPointsList[j + 1]) { int tempp = masterPointsList[j]; String temppstring = masterHandleList[j]; masterPointsList[j] = masterPointsList[j + 1]; masterHandleList[j] = masterHandleList[j + 1]; masterPointsList[j + 1] = tempp; masterHandleList[j + 1] = temppstring; } } } }
00
Code Sample 1: public void generateHtmlPage(String real_filename, String url_filename) { String str_content = ""; URL m_url = null; URLConnection m_urlcon = null; try { m_url = new URL(url_filename); m_urlcon = m_url.openConnection(); InputStream in_stream = m_urlcon.getInputStream(); byte[] bytes = new byte[1]; Vector v_bytes = new Vector(); while (in_stream.read(bytes) != -1) { v_bytes.add(bytes); bytes = new byte[1]; } byte[] all_bytes = new byte[v_bytes.size()]; for (int i = 0; i < v_bytes.size(); i++) all_bytes[i] = ((byte[]) v_bytes.get(i))[0]; str_content = new String(all_bytes, "GBK"); } catch (Exception urle) { } try { oaFileOperation file_control = new oaFileOperation(); file_control.writeFile(str_content, real_filename, true); String strPath = url_filename.substring(0, url_filename.lastIndexOf("/") + 1); String strUrlFileName = url_filename.substring(url_filename.lastIndexOf("/") + 1); if (strUrlFileName.indexOf(".jsp") > 0) { strUrlFileName = strUrlFileName.substring(0, strUrlFileName.indexOf(".jsp")) + "_1.jsp"; m_url = new URL(strPath + strUrlFileName); m_url.openConnection(); } intWriteFileCount++; intWriteFileCount = (intWriteFileCount > 100000) ? 0 : intWriteFileCount; } catch (Exception e) { } m_urlcon = null; } Code Sample 2: public static void insertTableData(Connection dest, TableMetaData tableMetaData) throws Exception { PreparedStatement ps = null; try { dest.setAutoCommit(false); String sql = "INSERT INTO " + tableMetaData.getSchema() + "." + tableMetaData.getTableName() + " ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += columnName + ","; } sql = sql.substring(0, sql.length() - 1); sql += ") VALUES ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += "?" + ","; } sql = sql.substring(0, sql.length() - 1); sql += ")"; IOHelper.writeInfo(sql); ps = dest.prepareStatement(sql); for (Row r : tableMetaData.getData()) { try { int param = 1; for (String columnName : tableMetaData.getColumnsNames()) { if (dest instanceof OracleConnection) { if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("BLOB")) { BLOB blob = new BLOB((OracleConnection) dest, (byte[]) r.getRowData().get(columnName)); ((OraclePreparedStatement) ps).setBLOB(param, blob); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("CLOB")) { ((OraclePreparedStatement) ps).setStringForClob(param, (String) r.getRowData().get(columnName)); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("LONG")) { ps.setBytes(param, (byte[]) r.getRowData().get(columnName)); } } else { IOHelper.writeInfo(columnName + " = " + r.getRowData().get(columnName)); ps.setObject(param, r.getRowData().get(columnName)); } param++; } if (ps.executeUpdate() != 1) { dest.rollback(); updateTableData(dest, tableMetaData, r); } } catch (Exception ex) { try { dest.rollback(); updateTableData(dest, tableMetaData, r); } catch (Exception ex2) { IOHelper.writeError("Error in update " + sql, ex2); } } ps.clearParameters(); } dest.commit(); dest.setAutoCommit(true); } finally { if (ps != null) ps.close(); } }
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 { closeQuietly(in); closeQuietly(out); } return success; } Code Sample 2: public TempFileTextBody(InputStream is, String mimeCharset) throws IOException { this.mimeCharset = mimeCharset; TempPath tempPath = TempStorage.getInstance().getRootTempPath(); tempFile = tempPath.createTempFile("attachment", ".txt"); OutputStream out = tempFile.getOutputStream(); IOUtils.copy(is, out); out.close(); }
00
Code Sample 1: public void updateFailedStatus(THLEventStatus failedEvent, ArrayList<THLEventStatus> events) throws THLException { Timestamp now = new Timestamp(System.currentTimeMillis()); Statement stmt = null; PreparedStatement pstmt = null; try { conn.setAutoCommit(false); if (events != null && events.size() > 0) { String seqnoList = buildCommaSeparatedList(events); stmt = conn.createStatement(); stmt.executeUpdate("UPDATE history SET status = " + THLEvent.FAILED + ", comments = 'Event was rollbacked due to failure while processing event#" + failedEvent.getSeqno() + "'" + ", processed_tstamp = " + conn.getNowFunction() + " WHERE seqno in " + seqnoList); } pstmt = conn.prepareStatement("UPDATE history SET status = ?" + ", comments = ?" + ", processed_tstamp = ?" + " WHERE seqno = ?"); pstmt.setShort(1, THLEvent.FAILED); pstmt.setString(2, truncate(failedEvent.getException() != null ? failedEvent.getException().getMessage() : "Unknown failure", commentLength)); pstmt.setTimestamp(3, now); pstmt.setLong(4, failedEvent.getSeqno()); pstmt.executeUpdate(); conn.commit(); } catch (SQLException e) { THLException exception = new THLException("Failed to update events status"); exception.initCause(e); try { conn.rollback(); } catch (SQLException e1) { THLException exception2 = new THLException("Failed to rollback after failure while updating events status"); e1.initCause(exception); exception2.initCause(e1); exception = exception2; } throw exception; } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException ignore) { } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException ignore) { } } try { conn.setAutoCommit(true); } catch (SQLException ignore) { } } } Code Sample 2: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } long time = System.currentTimeMillis(); FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size && continueWriting(pos, size)) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); } } finally { output.close(); IOUtils.closeQuietly(fos); input.close(); IOUtils.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { if (DiskManager.isLocked()) throw new IOException("Copy stopped since VtM was working"); else throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } else { time = System.currentTimeMillis() - time; long speed = (destFile.length() / time) / 1000; DiskManager.addDiskSpeed(speed); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
11
Code Sample 1: public static void copyfile(String src, String dst) throws IOException { dst = new File(dst).getAbsolutePath(); new File(new File(dst).getParent()).mkdirs(); FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public String insertBuilding() { homeMap = homeMapDao.getHomeMapById(homeMap.getId()); homeBuilding.setHomeMap(homeMap); Integer id = homeBuildingDao.saveHomeBuilding(homeBuilding); String dir = "E:\\ganymede_workspace\\training01\\web\\user_buildings\\"; FileOutputStream fos; try { fos = new FileOutputStream(dir + id); IOUtils.copy(new FileInputStream(imageFile), fos); IOUtils.closeQuietly(fos); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return execute(); }
00
Code Sample 1: public String getClass(EmeraldjbBean eb) throws EmeraldjbException { Entity entity = (Entity) eb; StringBuffer sb = new StringBuffer(); String myPackage = getPackageName(eb); sb.append("package " + myPackage + ";\n"); sb.append("\n"); DaoValuesGenerator valgen = new DaoValuesGenerator(); String values_class_name = valgen.getClassName(entity); sb.append("\n"); List importList = new Vector(); importList.add("java.io.*;"); importList.add("java.sql.Date;"); importList.add("com.emeraldjb.runtime.patternXmlObj.*;"); importList.add("javax.xml.parsers.*;"); importList.add("java.text.ParseException;"); importList.add("org.xml.sax.*;"); importList.add("org.xml.sax.helpers.*;"); importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";"); Iterator it = importList.iterator(); while (it.hasNext()) { String importName = (String) it.next(); sb.append("import " + importName + "\n"); } sb.append("\n"); String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1"); boolean short_version = entity.getPatternBooleanValue(GeneratorConst.PATTERN_STREAM_XML_SHORT, false); StringBuffer preface = new StringBuffer(); StringBuffer consts = new StringBuffer(); StringBuffer f_writer = new StringBuffer(); StringBuffer f_writer_short = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); StringBuffer end_elems = new StringBuffer(); boolean end_elem_needs_catch = false; consts.append("\n public static final String EL_CLASS_TAG=\"" + values_class_name + "\";"); preface.append("\n xos.print(\"<!-- This format is optimised for space, below are the column mappings\");"); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); int col_num = 0; while (it.hasNext()) { col_num++; Member member = (Member) it.next(); String nm = member.getName(); preface.append("\n xos.print(\"c" + col_num + " = " + nm + "\");"); String elem_name = nm; String elem_name_short = "c" + col_num; String el_name = nm.toUpperCase(); if (member.getColLen() > 0 || !member.isNullAllowed()) { end_elem_needs_catch = true; } String element_const = "EL_" + el_name; String element_const_short = "EL_" + el_name + "_SHORT"; consts.append("\n public static final String " + element_const + "=\"" + elem_name + "\";" + "\n public static final String " + element_const_short + "=\"" + elem_name_short + "\";"); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "values_." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToXmlCode(pad, element_const, getter + "()")); f_writer_short.append(gen_type.getToXmlCode(pad, element_const_short, getter + "()")); end_elems.append(gen_type.getFromXmlCode(pad, element_const, setter)); end_elems.append("\n //and also the short version"); end_elems.append(gen_type.getFromXmlCode(pad, element_const_short, setter)); } preface.append("\n xos.print(\"-->\");"); String body_part = f_writer.toString(); String body_part_short = preface.toString() + f_writer_short.toString(); String reader_vars = ""; String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + " extends DefaultHandler implements TSParser\n"); sb.append("{" + consts + "\n public static final int PROTO_VERSION=" + proto_version + ";" + "\n private transient StringBuffer cdata_=new StringBuffer();" + "\n private transient String endElement_;" + "\n private transient TSParser parentParser_;" + "\n private transient XMLReader theReader_;\n" + "\n private " + values_class_name + " values_;"); sb.append("\n\n"); sb.append("\n /**" + "\n * This is really only here as an example. It is very rare to write a single" + "\n * object to a file - far more likely to have a collection or object graph. " + "\n * in which case you can write something similar - maybe using the writeXmlShort" + "\n * version instread." + "\n */" + "\n public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileOutputStream fos = new FileOutputStream(file_nm);" + "\n XmlOutputFilter xos = new XmlOutputFilter(fos);" + "\n xos.openElement(\"FILE_\"+EL_CLASS_TAG);" + "\n writeXml(xos, obj);" + "\n xos.closeElement();" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException, SAXException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileInputStream fis = new FileInputStream(file_nm);" + "\n DataInputStream dis = new DataInputStream(fis);" + "\n marshalFromXml(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeXml(XmlOutputFilter xos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n xos.openElement(EL_CLASS_TAG);" + body_part + "\n xos.closeElement();" + "\n } // end of writeXml" + "\n" + "\n public static void writeXmlShort(XmlOutputFilter xos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n xos.openElement(EL_CLASS_TAG);" + body_part_short + "\n xos.closeElement();" + "\n } // end of writeXml" + "\n" + "\n public " + streamer_class_name + "(" + values_class_name + " obj) {" + "\n values_ = obj;" + "\n } // end of ctor" + "\n"); String xml_bit = addXmlFunctions(streamer_class_name, values_class_name, end_elem_needs_catch, end_elems, f_reader); String close = "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"; return sb.toString() + xml_bit + close; } Code Sample 2: public static void main(String[] args) { Stopwatch.start(""); HtmlParser parser = new HtmlParser(); try { Stopwatch.printTimeReset("", "> ParserDelegator"); ParserDelegator del = new ParserDelegator(); Stopwatch.printTimeReset("", "> url"); URL url = new URL(args[0]); Stopwatch.printTimeReset("", "> openStrem"); InputStream is = url.openStream(); Stopwatch.printTimeReset("", "< parse"); del.parse(new InputStreamReader(is), parser, true); Stopwatch.printTimeReset("", "< parse"); } catch (Throwable t) { t.printStackTrace(); } Stopwatch.printTimeReset("", "> traversal"); TreeTraversal.traverse(parser.startTag, "eachChild", new Function() { String lastPath = null; public void apply(Object obj) { if (obj instanceof String) { System.out.print(lastPath + ":"); System.out.println(obj); return; } Tag t = (Tag) obj; lastPath = Utils.tagPath(t); System.out.println(lastPath); } }); Stopwatch.printTimeReset("", "< traversal"); }
00
Code Sample 1: public static byte[] generateHash(String strPassword, byte[] salt) { try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(strPassword.getBytes(CHAR_ENCODING)); md.update(salt); return md.digest(); } catch (Exception e) { e.printStackTrace(); } return null; } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static 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: @Override public HttpResponse makeRequest() throws RequestCancelledException, IllegalStateException, IOException { checkState(); OutputStream out = null; InputStream in = null; try { out = new BufferedOutputStream(new FileOutputStream(destFile)); URLConnection conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[BUFFRE_SIZE]; int numRead; long totalSize = conn.getContentLength(); long transferred = 0; started(totalSize); while (!checkAbortFlag() && (numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); out.flush(); transferred += numRead; progress(transferred); } if (checkAbortFlag()) { cancelled(); } else { finished(); } if (checkAbortFlag()) { throw new RequestCancelledException(); } } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } return null; }
00
Code Sample 1: public void login(String UID, String PWD, int CTY) throws Exception { sSideURL = sSideURLCollection[CTY]; sUID = UID; sPWD = PWD; iCTY = CTY; sLoginLabel = getLoginLabel(sSideURL); String sParams = getLoginParams(); CookieHandler.setDefault(new ListCookieHandler()); URL url = new URL(sSideURL + sLoginURL); URLConnection conn = url.openConnection(); setRequestProperties(conn); conn.setDoInput(true); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(sParams); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = rd.readLine(); while (line != null) { sb.append(line + "\n"); line = rd.readLine(); } wr.close(); rd.close(); String sPage = sb.toString(); Pattern p = Pattern.compile(">Dein Penner<"); Matcher matcher = p.matcher(sPage); LogedIn = matcher.find(); } Code Sample 2: public static void main(String[] args) throws Exception { InputStream in = null; try { in = new URL(args[0]).openStream(); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } }
11
Code Sample 1: public static String SHA(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(s.getBytes(), 0, s.getBytes().length); byte[] hash = md.digest(); StringBuilder sb = new StringBuilder(); int msb; int lsb = 0; int i; for (i = 0; i < hash.length; i++) { msb = ((int) hash[i] & 0x000000FF) / 16; lsb = ((int) hash[i] & 0x000000FF) % 16; sb.append(hexChars[msb]); sb.append(hexChars[lsb]); } return sb.toString(); } catch (NoSuchAlgorithmException e) { return null; } } Code Sample 2: private static String processStr(String srcStr, String sign) throws NoSuchAlgorithmException, NullPointerException { if (null == srcStr) { throw new java.lang.NullPointerException("��Ҫ���ܵ��ַ�ΪNull"); } MessageDigest digest; String algorithm = "MD5"; String result = ""; digest = MessageDigest.getInstance(algorithm); digest.update(srcStr.getBytes()); byte[] byteRes = digest.digest(); int length = byteRes.length; for (int i = 0; i < length; i++) { result = result + byteHEX(byteRes[i], sign); } return result; }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: @Test public void testEncryptDecrypt() throws IOException { BlockCipher cipher = new SerpentEngine(); Random rnd = new Random(); byte[] key = new byte[256 / 8]; rnd.nextBytes(key); byte[] iv = new byte[cipher.getBlockSize()]; rnd.nextBytes(iv); byte[] data = new byte[1230000]; new Random().nextBytes(data); ByteArrayOutputStream bout = new ByteArrayOutputStream(); CryptOutputStream eout = new CryptOutputStream(bout, cipher, key); eout.write(data); eout.close(); byte[] eData = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(eData); CryptInputStream din = new CryptInputStream(bin, cipher, key); bout = new ByteArrayOutputStream(); IOUtils.copy(din, bout); eData = bout.toByteArray(); Assert.assertTrue(Arrays.areEqual(data, eData)); }
00
Code Sample 1: public void service(TranslationRequest request, TranslationResponse response) { try { Thread.sleep((long) Math.random() * 250); } catch (InterruptedException e1) { } hits.incrementAndGet(); String key = getKey(request); RequestResponse cachedResponse = cache.get(key); if (cachedResponse == null) { response.setEndState(new ResponseStateBean(ResponseCode.ERROR, "response not found for " + key)); return; } response.addHeaders(cachedResponse.getExpectedResponse().getHeaders()); response.setTranslationCount(cachedResponse.getExpectedResponse().getTranslationCount()); response.setFailCount(cachedResponse.getExpectedResponse().getFailCount()); if (cachedResponse.getExpectedResponse().getLastModified() != -1) { response.setLastModified(cachedResponse.getExpectedResponse().getLastModified()); } try { OutputStream output = response.getOutputStream(); InputStream input = cachedResponse.getExpectedResponse().getInputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } catch (IOException e) { response.setEndState(new ResponseStateException(e)); return; } response.setEndState(cachedResponse.getExpectedResponse().getEndState()); } Code Sample 2: private URL resolveRedirects(URL url, int redirectCount) throws IOException { URLConnection uc = url.openConnection(); if (uc instanceof HttpURLConnection) { HttpURLConnection huc = (HttpURLConnection) uc; huc.setInstanceFollowRedirects(false); huc.connect(); int responseCode = huc.getResponseCode(); String location = huc.getHeaderField("location"); huc.disconnect(); if ((responseCode == HttpURLConnection.HTTP_MOVED_TEMP) && (redirectCount < 5)) { try { URL newUrl = new URL(location); return resolveRedirects(newUrl, redirectCount + 1); } catch (MalformedURLException ex) { return url; } } else return url; } else return url; }
00
Code Sample 1: public void openAndClose(ZKEntry zke, LinkedList toOpen, LinkedList toRemove) throws SQLException { conn.setAutoCommit(false); try { Statement stm = conn.createStatement(); ResultSet rset = stm.executeQuery("SELECT now();"); rset.next(); Timestamp now = rset.getTimestamp("now()"); for (int i = 0; i < toRemove.size(); i++) { Workitem wi = (Workitem) toRemove.get(i); rset = stm.executeQuery("SELECT intime, part FROM stampzk WHERE stampzkid = '" + wi.getStampZkId() + "';"); rset.next(); long diff = now.getTime() - rset.getLong("intime"); float diffp = diff * rset.getFloat("part"); stm.executeUpdate("UPDATE stampzk SET outtime='" + now.getTime() + "', diff='" + diff + "', diffp='" + diffp + "' WHERE stampzkid='" + wi.getStampZkId() + "';"); } rset = stm.executeQuery("SELECT COUNT(*) FROM stampzk WHERE personalid='" + zke.getWorker().getPersonalId() + "' AND outtime='0';"); rset.next(); int count = rset.getInt("COUNT(*)") + toOpen.size(); rset = stm.executeQuery("SELECT * FROM stampzk WHERE personalid='" + zke.getWorker().getPersonalId() + "' AND outtime='0';"); while (rset.next()) { long diff = now.getTime() - rset.getLong("intime"); float diffp = diff * rset.getFloat("part"); int firstId = rset.getInt("firstid"); if (firstId == 0) firstId = rset.getInt("stampzkid"); Statement ust = conn.createStatement(); ust.executeUpdate("UPDATE stampzk SET outtime='" + now.getTime() + "', diff='" + diff + "', diffp='" + diffp + "' WHERE stampzkid='" + rset.getInt("stampzkid") + "';"); ust.executeUpdate("INSERT INTO stampzk SET zeitkid='" + rset.getInt("zeitkid") + "', personalid='" + zke.getWorker().getPersonalId() + "', funcsid='" + rset.getInt("funcsid") + "', part='" + (float) 1f / count + "', intime='" + now.getTime() + "', firstid='" + firstId + "';"); } for (int i = 0; i < toOpen.size(); i++) { stm.executeUpdate("INSERT INTO stampzk SET zeitkid='" + zke.getZeitKId() + "', personalid='" + zke.getWorker().getPersonalId() + "', intime='" + now.getTime() + "', funcsid='" + ((Workitem) toOpen.get(i)).getWorkType() + "', part='" + (float) 1f / count + "';"); } } catch (SQLException sqle) { conn.rollback(); conn.setAutoCommit(true); throw sqle; } conn.commit(); conn.setAutoCommit(true); } Code Sample 2: private static String fetchImageViaHttp(URL imgUrl) throws IOException { String sURL = imgUrl.toString(); String imgFile = imgUrl.getPath(); HttpURLConnection cnx = (HttpURLConnection) imgUrl.openConnection(); String uri = null; try { cnx.setAllowUserInteraction(false); cnx.setDoOutput(true); cnx.addRequestProperty("Cache-Control", "no-cache"); RequestContext ctx = RequestContext.get(); if (ctx != null) cnx.addRequestProperty("User-Agent", ctx.header("user-agent")); else cnx.addRequestProperty("User-Agent", user_agent); cnx.addRequestProperty("Referer", sURL.substring(0, sURL.indexOf('/', sURL.indexOf('.')) + 1)); cnx.connect(); if (cnx.getResponseCode() != HttpURLConnection.HTTP_OK) return null; InputStream imgData = cnx.getInputStream(); String ext = FilenameUtils.getExtension(imgFile).toLowerCase(); if (!Multimedia.isImageFile("aa." + ext)) ext = "jpg"; uri = FMT_FN.format(new Date()) + RandomStringUtils.randomAlphanumeric(4) + '.' + ext; File fileDest = new File(img_path + uri); if (!fileDest.getParentFile().exists()) fileDest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(fileDest); try { IOUtils.copy(imgData, fos); } finally { IOUtils.closeQuietly(imgData); IOUtils.closeQuietly(fos); } } finally { cnx.disconnect(); } return RequestContext.get().contextPath() + "/uploads/img/" + uri; }
00
Code Sample 1: private <T> Collection<T> loadProviders(final Class<T> providerClass) throws ModelException { try { final String providerNamePrefix = providerClass.getName() + "."; final Map<String, T> providers = new TreeMap<String, T>(new Comparator<String>() { public int compare(final String key1, final String key2) { return key1.compareTo(key2); } }); final File platformProviders = new File(this.getPlatformProviderLocation()); if (platformProviders.exists()) { if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("processing", platformProviders.getAbsolutePath()), null); } InputStream in = null; boolean suppressExceptionOnClose = true; final java.util.Properties p = new java.util.Properties(); try { in = new FileInputStream(platformProviders); p.load(in); suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (suppressExceptionOnClose) { this.log(Level.SEVERE, getMessage(e), e); } else { throw e; } } } for (Map.Entry<Object, Object> e : p.entrySet()) { if (e.getKey().toString().startsWith(providerNamePrefix)) { final String configuration = e.getValue().toString(); if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("providerInfo", platformProviders.getAbsolutePath(), providerClass.getName(), configuration), null); } providers.put(e.getKey().toString(), this.createProviderObject(providerClass, configuration, platformProviders.toURI().toURL())); } } } final Enumeration<URL> classpathProviders = this.findResources(this.getProviderLocation() + '/' + providerClass.getName()); int count = 0; final long t0 = System.currentTimeMillis(); while (classpathProviders.hasMoreElements()) { count++; final URL url = classpathProviders.nextElement(); if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("processing", url.toExternalForm()), null); } BufferedReader reader = null; boolean suppressExceptionOnClose = true; try { reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { if (line.contains("#")) { continue; } if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("providerInfo", url.toExternalForm(), providerClass.getName(), line), null); } providers.put(providerNamePrefix + providers.size(), this.createProviderObject(providerClass, line, url)); } suppressExceptionOnClose = false; } finally { try { if (reader != null) { reader.close(); } } catch (final IOException e) { if (suppressExceptionOnClose) { this.log(Level.SEVERE, getMessage(e), e); } else { throw new ModelException(getMessage(e), e); } } } } if (this.isLoggable(Level.FINE)) { this.log(Level.FINE, getMessage("contextReport", count, this.getProviderLocation() + '/' + providerClass.getName(), Long.valueOf(System.currentTimeMillis() - t0)), null); } return providers.values(); } catch (final IOException e) { throw new ModelException(getMessage(e), e); } } Code Sample 2: public HttpURLConnection execute(S3Bucket pBucket, S3Object pObject, S3OperationParameters pOpParams) throws S3Exception { S3OperationParameters opParams = pOpParams; if (opParams == null) opParams = new S3OperationParameters(); HttpURLConnection result = null; URL url = getURL(pBucket, pObject, opParams.getQueryParameters()); mLogger.log(Level.FINEST, "URL: " + url.toString()); opParams.addDateHeader(); switch(mStyle) { case Path: opParams.addHostHeader(BASE_DOMAIN); break; case Subdomain: if (pBucket == null) opParams.addHostHeader(BASE_DOMAIN); else opParams.addHostHeader(pBucket.getName() + "." + BASE_DOMAIN); break; case VirtualHost: if (pBucket == null) opParams.addHostHeader(BASE_DOMAIN); else opParams.addHostHeader(pBucket.getName()); break; } if (opParams.isSign()) { StringBuilder sb = new StringBuilder(); sb.append(opParams.getVerb().toString()); sb.append(NEWLINE); sb.append(posHeader(MD5, opParams.getRequestHeaders())); sb.append(posHeader(TYPE, opParams.getRequestHeaders())); if (opParams.getQueryParameters().has(EXPIRES)) { sb.append(opParams.getQueryParameters().get(EXPIRES).getValue()); sb.append(NEWLINE); } else { sb.append(posHeader(DATE, opParams.getRequestHeaders())); } sb.append(canonicalizeAmazonHeaders(opParams.getRequestHeaders())); try { sb.append("/"); if (pBucket != null) { sb.append(URLEncoder.encode(pBucket.getName(), URL_ENCODING)); sb.append("/"); if (pObject != null) { sb.append(URLEncoder.encode(pObject.getKey(), URL_ENCODING)); } } sb.append(opParams.getQueryParameters().getAmazonSubresources().toQueryString()); String signThis = sb.toString(); mLogger.log(Level.FINEST, "String being signed: " + signThis); String sig = encode(mCredential.getMSecretAccessKey(), signThis, false); sb = new StringBuilder(); sb.append("AWS "); sb.append(mCredential.getMAccessKeyID()); sb.append(":"); sb.append(sig); opParams.addAuthorizationHeader(sb.toString()); } catch (UnsupportedEncodingException e) { throw new S3Exception("URL encoding not supported: " + URL_ENCODING, e); } } try { killHostVerifier(); URLConnection urlConn = url.openConnection(); if (!(urlConn instanceof HttpURLConnection)) throw new S3Exception("URLConnection is not instance of HttpURLConnection!"); result = (HttpURLConnection) urlConn; result.setRequestMethod(opParams.getVerb().toString()); mLogger.log(Level.FINEST, "HTTP Operation: " + opParams.getVerb().toString()); if (opParams.getVerb() == HttpVerb.PUT) { result.setDoOutput(true); } result.setRequestProperty(TYPE, ""); for (AWSParameter param : opParams.getRequestHeaders()) { result.setRequestProperty(param.getName(), param.getValue()); mLogger.log(Level.FINEST, "Header " + param.getName() + ": " + param.getValue()); } } catch (IOException e) { throw new S3Exception("Problem opening connection to URL: " + url.toString(), e); } return result; }
11
Code Sample 1: private void googleImageSearch() { bottomShowing = true; googleSearched = true; googleImageLocation = 0; googleImages = new Vector<String>(); custom = ""; int r = JOptionPane.showConfirmDialog(this, "Customize google search?", "Google Search", JOptionPane.YES_NO_OPTION); if (r == JOptionPane.YES_OPTION) { custom = JOptionPane.showInputDialog("Custom Search", ""); } else { custom = artist; } try { String u = "http://images.google.com/images?q=" + custom; if (u.contains(" ")) { u = u.replace(" ", "+"); } URL url = new URL(u); HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); httpcon.addRequestProperty("User-Agent", "Mozilla/4.76"); BufferedReader readIn = new BufferedReader(new InputStreamReader(httpcon.getInputStream())); googleImages.clear(); String lin = new String(); while ((lin = readIn.readLine()) != null) { while (lin.contains("href=\"/imgres?imgurl=")) { while (!lin.contains(">")) { lin += readIn.readLine(); } String s = lin.substring(lin.indexOf("href=\"/imgres?imgurl="), lin.indexOf(">", lin.indexOf("href=\"/imgres?imgurl="))); lin = lin.substring(lin.indexOf(">", lin.indexOf("href=\"/imgres?imgurl="))); if (s.contains("&amp;") && s.indexOf("http://") < s.indexOf("&amp;")) { s = s.substring(s.indexOf("http://"), s.indexOf("&amp;")); } else { s = s.substring(s.indexOf("http://"), s.length()); } googleImages.add(s); } } readIn.close(); } catch (Exception ex4) { MusicBoxView.showErrorDialog(ex4); } jButton1.setEnabled(false); getContentPane().remove(jLabel1); ImageIcon icon; try { icon = new ImageIcon(new URL(googleImages.elementAt(googleImageLocation))); int h = icon.getIconHeight(); int w = icon.getIconWidth(); jLabel1.setSize(w, h); jLabel1.setIcon(icon); add(jLabel1, BorderLayout.CENTER); } catch (MalformedURLException ex) { MusicBoxView.showErrorDialog(ex); jLabel1.setIcon(MusicBoxView.noImage); } add(jPanel1, BorderLayout.PAGE_END); pack(); } 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 develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } 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 void run() throws Exception { Properties buildprops = new Properties(); try { ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("build.properties"); InputStream is = url.openStream(); ; buildprops.load(is); } catch (Exception ex) { log.error("Problem getting build props", ex); } System.out.println("Report Server v" + buildprops.getProperty("version", "unknown") + "-" + buildprops.getProperty("build", "unknown")); validate(); if (log.isInfoEnabled()) { log.info("Starting Report Server v" + buildprops.getProperty("version", "unknown") + "-" + buildprops.getProperty("build", "unknown")); } MainConfig config = MainConfig.newInstance(); basedir = config.getBaseDirectory(); if (log.isInfoEnabled()) { log.info("basedir = " + basedir); } SchedulerFactory schedFact = new StdSchedulerFactory(); sched = schedFact.getScheduler(); NodeList reports = config.getReports(); for (int x = 0; x < reports.getLength(); x++) { try { if (log.isInfoEnabled()) { log.info("Adding report at index " + x); } Node report = reports.item(x); runReport(report); } catch (Exception ex) { if (log.isErrorEnabled()) { log.error("Can't add a report at report index " + x, ex); } } } addStatsJob(); sched.start(); WebServer webserver = new WebServer(8080); webserver.setParanoid(false); webserver.start(); } Code Sample 2: public static void fileCopy(File src, File dst) throws FileNotFoundException, IOException { if (src.isDirectory() && (!dst.exists() || dst.isDirectory())) { if (!dst.exists()) { if (!dst.mkdirs()) throw new IOException("unable to mkdir " + dst); } File dst1 = new File(dst, src.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); dst = dst1; File[] files = src.listFiles(); for (File f : files) { if (f.isDirectory()) { dst1 = new File(dst, f.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); } else { dst1 = dst; } fileCopy(f, dst1); } return; } else if (dst.isDirectory()) { dst = new File(dst, src.getName()); } FileChannel ic = new FileInputStream(src).getChannel(); FileChannel oc = new FileOutputStream(dst).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
11
Code Sample 1: private String generateUniqueIdMD5(String workgroupIdString, String runIdString) { String passwordUnhashed = workgroupIdString + "-" + runIdString; MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(passwordUnhashed.getBytes(), 0, passwordUnhashed.length()); String uniqueIdMD5 = new BigInteger(1, m.digest()).toString(16); return uniqueIdMD5; } Code Sample 2: public static synchronized String encrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return new Base64(-1).encodeToString(raw); }
00
Code Sample 1: private void copyOneFile(String oldPath, String newPath) { File copiedFile = new File(newPath); try { FileInputStream source = new FileInputStream(oldPath); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } } Code Sample 2: public Point getCoordinates(String address, String city, String state, String country) { StringBuilder queryString = new StringBuilder(); StringBuilder urlString = new StringBuilder(); StringBuilder response = new StringBuilder(); if (address != null) { queryString.append(address.trim().replaceAll(" ", "+")); queryString.append("+"); } if (city != null) { queryString.append(city.trim().replaceAll(" ", "+")); queryString.append("+"); } if (state != null) { queryString.append(state.trim().replaceAll(" ", "+")); queryString.append("+"); } if (country != null) { queryString.append(country.replaceAll(" ", "+")); } urlString.append("http://maps.google.com/maps/geo?key="); urlString.append(key); urlString.append("&sensor=false&output=json&oe=utf8&q="); urlString.append(queryString.toString()); try { URL url = new URL(urlString.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); JSONObject root = (JSONObject) JSONValue.parse(response.toString()); JSONObject placemark = (JSONObject) ((JSONArray) root.get("Placemark")).get(0); JSONArray coordinates = (JSONArray) ((JSONObject) placemark.get("Point")).get("coordinates"); Point point = new Point(); point.setLatitude((Double) coordinates.get(1)); point.setLongitude((Double) coordinates.get(0)); return point; } catch (MalformedURLException ex) { return null; } catch (NullPointerException ex) { return null; } catch (IOException ex) { return null; } }
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: static void linkBlocks(File from, File to, int oldLV) throws IOException { if (!from.isDirectory()) { if (from.getName().startsWith(COPY_FILE_PREFIX)) { IOUtils.copyBytes(new FileInputStream(from), new FileOutputStream(to), 16 * 1024, true); } else { if (oldLV >= PRE_GENERATIONSTAMP_LAYOUT_VERSION) { to = new File(convertMetatadataFileName(to.getAbsolutePath())); } HardLink.createHardLink(from, to); } return; } if (!to.mkdir()) throw new IOException("Cannot create directory " + to); String[] blockNames = from.list(new java.io.FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith(BLOCK_SUBDIR_PREFIX) || name.startsWith(BLOCK_FILE_PREFIX) || name.startsWith(COPY_FILE_PREFIX); } }); for (int i = 0; i < blockNames.length; i++) linkBlocks(new File(from, blockNames[i]), new File(to, blockNames[i]), oldLV); }
11
Code Sample 1: protected static String getFileContentAsString(URL url, String encoding) throws IOException { InputStream input = null; StringWriter sw = new StringWriter(); try { System.out.println("Free mem :" + Runtime.getRuntime().freeMemory()); input = url.openStream(); IOUtils.copy(input, sw, encoding); System.out.println("Free mem :" + Runtime.getRuntime().freeMemory()); } finally { if (input != null) { input.close(); System.gc(); input = null; System.out.println("Free mem :" + Runtime.getRuntime().freeMemory()); } } return sw.toString(); } Code Sample 2: public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getName()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getName()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getName()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); 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: private void copy(File from, File to) { if (from.isDirectory()) { File[] files = from.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { File newTo = new File(to.getPath() + File.separator + files[i].getName()); newTo.mkdirs(); copy(files[i], newTo); } else { copy(files[i], to); } } } else { try { to = new File(to.getPath() + File.separator + from.getName()); to.createNewFile(); FileChannel src = new FileInputStream(from).getChannel(); FileChannel dest = new FileOutputStream(to).getChannel(); dest.transferFrom(src, 0, src.size()); dest.close(); src.close(); } catch (FileNotFoundException e) { errorLog(e.toString()); e.printStackTrace(); } catch (IOException e) { errorLog(e.toString()); e.printStackTrace(); } } } Code Sample 2: public RawTableData(int selectedId) { selectedProjectId = selectedId; String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetProjectDocuments"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "documents.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&projectid=" + selectedProjectId + "&filename=" + URLEncoder.encode(username, "UTF-8") + "documents.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("doc"); int num = nodelist.getLength(); rawTableData = new String[num][11]; imageNames = new String[num]; for (int i = 0; i < num; i++) { rawTableData[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "did")); rawTableData[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "t")); rawTableData[i][2] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "f")); rawTableData[i][3] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "d")); rawTableData[i][4] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "l")); String firstname = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "fn")); String lastname = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "ln")); rawTableData[i][5] = firstname + " " + lastname; rawTableData[i][6] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "dln")); rawTableData[i][7] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "rsid")); rawTableData[i][8] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "img")); imageNames[i] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "img")); rawTableData[i][9] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "ucin")); rawTableData[i][10] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "dtid")); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException e) { } catch (Exception ex) { System.out.println(ex); } }
11
Code Sample 1: public static HashCash mintCash(String resource, Map<String, List<String>> extensions, Calendar date, int value, int version) throws NoSuchAlgorithmException { if (version < 0 || version > 1) throw new IllegalArgumentException("Only supported versions are 0 and 1"); if (value < 0 || value > hashLength) throw new IllegalArgumentException("Value must be between 0 and " + hashLength); if (resource.contains(":")) throw new IllegalArgumentException("Resource must not contain ':'"); HashCash result = new HashCash(); MessageDigest md = MessageDigest.getInstance("SHA1"); result.myResource = resource; result.myExtensions = (null == extensions ? new HashMap<String, List<String>>() : extensions); result.myDate = date; result.myVersion = version; String prefix; SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString); switch(version) { case 0: prefix = version + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":"; result.myToken = generateCash(prefix, value, md); md.reset(); md.update(result.myToken.getBytes()); result.myValue = numberOfLeadingZeros(md.digest()); break; case 1: result.myValue = value; prefix = version + ":" + value + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":"; result.myToken = generateCash(prefix, value, md); break; default: throw new IllegalArgumentException("Only supported versions are 0 and 1"); } return result; } Code Sample 2: public String getShortToken(String md5Str) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(md5Str.getBytes(JspRunConfig.charset)); } catch (Exception e) { e.printStackTrace(); } StringBuffer token = toHex(md5.digest()); return token.substring(8, 24); }
11
Code Sample 1: public void processDeleteCompany(Company companyBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (companyBean.getId() == null) throw new IllegalArgumentException("companyId is null"); String sql = "update WM_LIST_COMPANY set is_deleted = 1 " + "where ID_FIRM = ? and ID_FIRM in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedCompanyId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_FIRM from v$_read_list_firm z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, companyBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(2, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete company"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } Code Sample 2: @Override public void delArtista(Integer numeroInscricao) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "delete from artista where numeroinscricao = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, numeroInscricao); ps.executeUpdate(); delEndereco(conn, ps, numeroInscricao); delObras(conn, ps, numeroInscricao); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } }
00
Code Sample 1: private long newIndex(String indexname) { Connection con = null; ResultSet rs = null; Statement stm = null; StringBuffer sql = new StringBuffer(); indexname = indexname.trim().toUpperCase(); try { long index = -1; synchronized (FormularContextPersistensImpl.class) { con = getConnection(); stm = con.createStatement(); if ((con != null) && (stm != null)) { con.setAutoCommit(false); sql = new StringBuffer(); sql.append("SELECT * FROM INDX_EC WHERE INDX_NAME='"); sql.append(indexname); sql.append("' FOR UPDATE"); rs = stm.executeQuery(sql.toString()); if ((rs != null) && rs.next()) { sql = new StringBuffer(); index = rs.getLong("INDX_WERT") + 1; sql.append("UPDATE INDX_EC SET INDX_WERT = "); sql.append(index); sql.append(" WHERE INDX_NAME='"); sql.append(indexname); sql.append("'"); rs.close(); rs = null; if (stm.executeUpdate(sql.toString()) == 1) { con.commit(); } else { con.rollback(); index = -1; } } else { sql = new StringBuffer(); sql.append("INSERT INTO INDX_EC (INDX_NAME, INDX_WERT) VALUES('"); sql.append(indexname); sql.append("', "); sql.append(1); sql.append(")"); if (stm.executeUpdate(sql.toString()) == 1) { con.commit(); index = 1; } else { con.rollback(); } } } } return index; } catch (Exception e) { Log.getLogger().error("Error during execute SQL-Statement: " + sql.toString(), e); return -1; } finally { if (rs != null) { try { rs.close(); } catch (Exception ignore) { } } if (stm != null) { try { stm.close(); } catch (Exception ignore) { } } if (con != null) { try { con.close(); } catch (Exception ignore) { } } } } Code Sample 2: public static void storeRemote(String sourceLocation, SourceDetail targetSourceDetail, String targetlocation, boolean isBinary) throws Exception { FTPClient client = new FTPClient(); client.connect(targetSourceDetail.getHost()); client.login(targetSourceDetail.getUser(), targetSourceDetail.getPassword()); if (isBinary) client.setFileType(FTPClient.BINARY_FILE_TYPE); File file = new File(sourceLocation); if (file.isDirectory()) { client.makeDirectory(targetlocation); FileInputStream in = null; for (File myFile : file.listFiles()) { if (myFile.isDirectory()) { storeRemote(myFile.getAbsolutePath(), targetSourceDetail, targetlocation + "/" + myFile.getName(), isBinary); } else { in = new FileInputStream(myFile.getAbsolutePath()); if (!targetlocation.endsWith("/")) client.storeFile(targetlocation + "/" + myFile.getName(), in); else client.storeFile(targetlocation + myFile.getName(), in); in.close(); } } } else { FileInputStream in = new FileInputStream(sourceLocation); client.storeFile(targetlocation, in); in.close(); } client.disconnect(); }
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 static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) throw new IOException("Source and destination cannot be the same file path"); FileChannel srcChannel = new FileInputStream(source).getChannel(); if (!dest.exists()) dest.createNewFile(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
11
Code Sample 1: public final String encrypt(String input) throws Exception { try { MessageDigest messageDigest = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); messageDigest.reset(); messageDigest.update(input.getBytes()); String output = convert(messageDigest.digest()); return output; } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Fatal Error while digesting input string", ex); } } return input; } Code Sample 2: public boolean verifySignature() { try { byte[] data = readFile(name + ".tmp1.bin"); if (data == null) return false; if (data[data.length - 0x104] != 'N' || data[data.length - 0x103] != 'G' || data[data.length - 0x102] != 'I' || data[data.length - 0x101] != 'S') return false; byte[] signature = new byte[0x100]; byte[] module = new byte[data.length - 0x104]; System.arraycopy(data, data.length - 0x100, signature, 0, 0x100); System.arraycopy(data, 0, module, 0, data.length - 0x104); BigIntegerEx power = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { 0x01, 0x00, 0x01, 0x00 }); BigIntegerEx mod = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { (byte) 0x6B, (byte) 0xCE, (byte) 0xF5, (byte) 0x2D, (byte) 0x2A, (byte) 0x7D, (byte) 0x7A, (byte) 0x67, (byte) 0x21, (byte) 0x21, (byte) 0x84, (byte) 0xC9, (byte) 0xBC, (byte) 0x25, (byte) 0xC7, (byte) 0xBC, (byte) 0xDF, (byte) 0x3D, (byte) 0x8F, (byte) 0xD9, (byte) 0x47, (byte) 0xBC, (byte) 0x45, (byte) 0x48, (byte) 0x8B, (byte) 0x22, (byte) 0x85, (byte) 0x3B, (byte) 0xC5, (byte) 0xC1, (byte) 0xF4, (byte) 0xF5, (byte) 0x3C, (byte) 0x0C, (byte) 0x49, (byte) 0xBB, (byte) 0x56, (byte) 0xE0, (byte) 0x3D, (byte) 0xBC, (byte) 0xA2, (byte) 0xD2, (byte) 0x35, (byte) 0xC1, (byte) 0xF0, (byte) 0x74, (byte) 0x2E, (byte) 0x15, (byte) 0x5A, (byte) 0x06, (byte) 0x8A, (byte) 0x68, (byte) 0x01, (byte) 0x9E, (byte) 0x60, (byte) 0x17, (byte) 0x70, (byte) 0x8B, (byte) 0xBD, (byte) 0xF8, (byte) 0xD5, (byte) 0xF9, (byte) 0x3A, (byte) 0xD3, (byte) 0x25, (byte) 0xB2, (byte) 0x66, (byte) 0x92, (byte) 0xBA, (byte) 0x43, (byte) 0x8A, (byte) 0x81, (byte) 0x52, (byte) 0x0F, (byte) 0x64, (byte) 0x98, (byte) 0xFF, (byte) 0x60, (byte) 0x37, (byte) 0xAF, (byte) 0xB4, (byte) 0x11, (byte) 0x8C, (byte) 0xF9, (byte) 0x2E, (byte) 0xC5, (byte) 0xEE, (byte) 0xCA, (byte) 0xB4, (byte) 0x41, (byte) 0x60, (byte) 0x3C, (byte) 0x7D, (byte) 0x02, (byte) 0xAF, (byte) 0xA1, (byte) 0x2B, (byte) 0x9B, (byte) 0x22, (byte) 0x4B, (byte) 0x3B, (byte) 0xFC, (byte) 0xD2, (byte) 0x5D, (byte) 0x73, (byte) 0xE9, (byte) 0x29, (byte) 0x34, (byte) 0x91, (byte) 0x85, (byte) 0x93, (byte) 0x4C, (byte) 0xBE, (byte) 0xBE, (byte) 0x73, (byte) 0xA9, (byte) 0xD2, (byte) 0x3B, (byte) 0x27, (byte) 0x7A, (byte) 0x47, (byte) 0x76, (byte) 0xEC, (byte) 0xB0, (byte) 0x28, (byte) 0xC9, (byte) 0xC1, (byte) 0xDA, (byte) 0xEE, (byte) 0xAA, (byte) 0xB3, (byte) 0x96, (byte) 0x9C, (byte) 0x1E, (byte) 0xF5, (byte) 0x6B, (byte) 0xF6, (byte) 0x64, (byte) 0xD8, (byte) 0x94, (byte) 0x2E, (byte) 0xF1, (byte) 0xF7, (byte) 0x14, (byte) 0x5F, (byte) 0xA0, (byte) 0xF1, (byte) 0xA3, (byte) 0xB9, (byte) 0xB1, (byte) 0xAA, (byte) 0x58, (byte) 0x97, (byte) 0xDC, (byte) 0x09, (byte) 0x17, (byte) 0x0C, (byte) 0x04, (byte) 0xD3, (byte) 0x8E, (byte) 0x02, (byte) 0x2C, (byte) 0x83, (byte) 0x8A, (byte) 0xD6, (byte) 0xAF, (byte) 0x7C, (byte) 0xFE, (byte) 0x83, (byte) 0x33, (byte) 0xC6, (byte) 0xA8, (byte) 0xC3, (byte) 0x84, (byte) 0xEF, (byte) 0x29, (byte) 0x06, (byte) 0xA9, (byte) 0xB7, (byte) 0x2D, (byte) 0x06, (byte) 0x0B, (byte) 0x0D, (byte) 0x6F, (byte) 0x70, (byte) 0x9E, (byte) 0x34, (byte) 0xA6, (byte) 0xC7, (byte) 0x31, (byte) 0xBE, (byte) 0x56, (byte) 0xDE, (byte) 0xDD, (byte) 0x02, (byte) 0x92, (byte) 0xF8, (byte) 0xA0, (byte) 0x58, (byte) 0x0B, (byte) 0xFC, (byte) 0xFA, (byte) 0xBA, (byte) 0x49, (byte) 0xB4, (byte) 0x48, (byte) 0xDB, (byte) 0xEC, (byte) 0x25, (byte) 0xF3, (byte) 0x18, (byte) 0x8F, (byte) 0x2D, (byte) 0xB3, (byte) 0xC0, (byte) 0xB8, (byte) 0xDD, (byte) 0xBC, (byte) 0xD6, (byte) 0xAA, (byte) 0xA6, (byte) 0xDB, (byte) 0x6F, (byte) 0x7D, (byte) 0x7D, (byte) 0x25, (byte) 0xA6, (byte) 0xCD, (byte) 0x39, (byte) 0x6D, (byte) 0xDA, (byte) 0x76, (byte) 0x0C, (byte) 0x79, (byte) 0xBF, (byte) 0x48, (byte) 0x25, (byte) 0xFC, (byte) 0x2D, (byte) 0xC5, (byte) 0xFA, (byte) 0x53, (byte) 0x9B, (byte) 0x4D, (byte) 0x60, (byte) 0xF4, (byte) 0xEF, (byte) 0xC7, (byte) 0xEA, (byte) 0xAC, (byte) 0xA1, (byte) 0x7B, (byte) 0x03, (byte) 0xF4, (byte) 0xAF, (byte) 0xC7 }); byte[] result = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, signature).modPow(power, mod).toByteArray(); byte[] digest; byte[] properResult = new byte[0x100]; for (int i = 0; i < properResult.length; i++) properResult[i] = (byte) 0xBB; MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(module); md.update("MAIEV.MOD".getBytes()); digest = md.digest(); System.arraycopy(digest, 0, properResult, 0, digest.length); for (int i = 0; i < result.length; i++) if (result[i] != properResult[i]) return false; return true; } catch (Exception e) { System.out.println("Failed to verify signature: " + e.toString()); } return false; }
11
Code Sample 1: private static void dumpUrl(URL url) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { System.out.println(s); s = reader.readLine(); } reader.close(); } Code Sample 2: public ArrayList parseFile(File newfile) throws IOException { String s; String firstname; String secondname; String direction; String header; String name = null; String[] tokens; boolean readingHArrays = false; boolean readingVArrays = false; boolean readingAArrays = false; ArrayList xturndat = new ArrayList(); ArrayList yturndat = new ArrayList(); ArrayList ampturndat = new ArrayList(); int nvalues; URL url = newfile.toURI().toURL(); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); while ((s = br.readLine()) != null) { tokens = s.split("\\s+"); nvalues = tokens.length; if (nvalues < 1) continue; firstname = tokens[0]; secondname = tokens[1]; if (secondname.startsWith("BPM")) { if (readingHArrays) dumpxData(name, xturndat); else if (readingVArrays) dumpyData(name, yturndat); else if (readingAArrays) dumpampData(name, ampturndat); direction = tokens[4]; if (direction.equals("HORIZONTAL")) { readingHArrays = true; readingVArrays = false; readingAArrays = false; } if (direction.equals("VERTICAL")) { readingVArrays = true; readingHArrays = false; readingAArrays = false; } if (direction.equals("AMPLITUDE")) { readingVArrays = false; readingHArrays = false; readingAArrays = true; } name = tokens[3]; xturndat.clear(); yturndat.clear(); ampturndat.clear(); } if (secondname.startsWith("WAVEFORM")) continue; if (nvalues == 3) { if (readingHArrays) xturndat.add(new Double(Double.parseDouble(tokens[2]))); else if (readingVArrays) yturndat.add(new Double(Double.parseDouble(tokens[2]))); else if (readingAArrays) ampturndat.add(new Double(Double.parseDouble(tokens[2]))); } } dumpampData(name, ampturndat); data.add(xdatamap); data.add(ydatamap); data.add(ampdatamap); return data; }
00
Code Sample 1: public void testDoPost() throws Exception { URL url = null; url = new URL("http://127.0.0.1:" + connector.getLocalPort() + "/test/dump/info?query=foo"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.addRequestProperty(HttpHeaders.CONTENT_TYPE, MimeTypes.FORM_ENCODED); connection.addRequestProperty(HttpHeaders.CONTENT_LENGTH, "10"); connection.getOutputStream().write("abcd=1234\n".getBytes()); connection.getOutputStream().flush(); connection.connect(); String s0 = IO.toString(connection.getInputStream()); assertTrue(s0.startsWith("<html>")); assertTrue(s0.indexOf("<td>POST</td>") > 0); assertTrue(s0.indexOf("abcd:&nbsp;</th><td>1234") > 0); } 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 Model read(String uri, String base, String lang) { try { URL url = new URL(uri); return read(url.openStream(), base, lang); } catch (IOException e) { throw new OntologyException("I/O error while reading from uri " + uri); } } Code Sample 2: private HttpsURLConnection setUpConnection(URL url) throws NoSuchAlgorithmException, KeyManagementException, IOException { HttpsURLConnection openConnection = (HttpsURLConnection) url.openConnection(); openConnection.setAllowUserInteraction(true); openConnection.setUseCaches(false); openConnection.setDoInput(true); openConnection.setDoOutput(true); SSLContext sc = SSLContext.getInstance(SSL_PROTOCOL); sc.init(new KeyManager[] { new MyKeyManager() }, new TrustManager[] { new BypassTrustManager() }, null); openConnection.setSSLSocketFactory(sc.getSocketFactory()); return openConnection; }