label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
11
| Code Sample 1:
private static String executeGet(String urlStr) { StringBuffer result = new StringBuffer(); try { Authentication.doIt(); URL url = new URL(urlStr); System.out.println("Host: " + url.getHost()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); String inputLine; while ((inputLine = in.readLine()) != null) { result.append(inputLine); } in.close(); connection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result.toString(); }
Code Sample 2:
public static void v2ljastaVeebileht(String s) throws IOException { URL url = new URL(s); InputStream is = url.openConnection().getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } } |
00
| Code Sample 1:
public void read(Model m, String url) throws JenaException { try { URLConnection conn = new URL(url).openConnection(); String encoding = conn.getContentEncoding(); if (encoding == null) read(m, conn.getInputStream(), url); else read(m, new InputStreamReader(conn.getInputStream(), encoding), url); } catch (FileNotFoundException e) { throw new DoesNotExistException(url); } catch (IOException e) { throw new JenaException(e); } }
Code Sample 2:
private InputStream urlToInputStream(URL url) throws IOException { URLConnection conn = url.openConnection(); conn.setRequestProperty("User-Agent", IE); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.connect(); String encoding = conn.getContentEncoding(); if ((encoding != null) && encoding.equalsIgnoreCase("gzip")) return new GZIPInputStream(conn.getInputStream()); else if ((encoding != null) && encoding.equalsIgnoreCase("deflate")) return new InflaterInputStream(conn.getInputStream(), new Inflater(true)); else return conn.getInputStream(); } |
11
| Code Sample 1:
private String createCSVFile(String fileName) throws FileNotFoundException, IOException { String csvFile = fileName + ".csv"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); BufferedWriter out = new BufferedWriter(new FileWriter(csvFile)); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return csvFile; }
Code Sample 2:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("Cache-Control", "max-age=" + Constants.HTTP_CACHE_SECONDS); String uuid = req.getRequestURI().substring(req.getRequestURI().indexOf(Constants.SERVLET_THUMBNAIL_PREFIX) + Constants.SERVLET_THUMBNAIL_PREFIX.length() + 1); if (uuid != null && !"".equals(uuid)) { resp.setContentType("image/jpeg"); StringBuffer sb = new StringBuffer(); sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/IMG_THUMB/content"); InputStream is = null; if (!Constants.MISSING.equals(uuid)) { is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), true); } else { is = new FileInputStream(new File("images/other/file_not_found.png")); } if (is == null) { return; } ServletOutputStream os = resp.getOutputStream(); try { IOUtils.copyStreams(is, os); } catch (IOException e) { } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { } finally { is = null; } } } resp.setStatus(200); } else { resp.setStatus(404); } } |
11
| Code Sample 1:
public String postEvent(EventDocument eventDoc, Map attachments) { if (eventDoc == null || eventDoc.getEvent() == null) return null; if (queue == null) { sendEvent(eventDoc, attachments); return eventDoc.getEvent().getEventId(); } if (attachments != null) { Iterator iter = attachments.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); if (entry.getValue() instanceof DataHandler) { File file = new File(attachmentStorge + "/" + GuidUtil.generate() + entry.getKey()); try { IOUtils.copy(((DataHandler) entry.getValue()).getInputStream(), new FileOutputStream(file)); entry.setValue(file); } catch (IOException err) { err.printStackTrace(); } } } } InternalEventObject eventObj = new InternalEventObject(); eventObj.setEventDocument(eventDoc); eventObj.setAttachments(attachments); eventObj.setSessionContext(SessionContextUtil.getCurrentContext()); eventDoc.getEvent().setEventId(GuidUtil.generate()); getQueue().post(eventObj); return eventDoc.getEvent().getEventId(); }
Code Sample 2:
public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); FileChannel channelSrc = fis.getChannel(); FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } |
00
| Code Sample 1:
public static void compressAll(File dir, File file) throws IOException { if (!dir.isDirectory()) throw new IllegalArgumentException("Given file is no directory"); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file)); out.setLevel(0); String[] entries = dir.list(); byte[] buffer = new byte[4096]; int bytesRead; for (int i = 0; i < entries.length; i++) { File f = new File(dir, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getName()); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); }
Code Sample 2:
public void testSimpleHttpPostsHTTP10() throws Exception { int reqNo = 20; Random rnd = new Random(); List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(false); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); this.client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); assertEquals(HttpVersion.HTTP_1_0, response.getStatusLine().getProtocolVersion()); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } } |
11
| Code Sample 1:
public static boolean writeFileByChars(Reader pReader, File pFile, boolean pAppend) { boolean flag = false; try { FileWriter fw = new FileWriter(pFile, pAppend); IOUtils.copy(pReader, fw); fw.flush(); fw.close(); pReader.close(); flag = true; } catch (Exception e) { LOG.error("ๅฐๅญ็ฌฆๆตๅๅ
ฅ๏ฟฝ?" + pFile.getName() + "ๅบ็ฐๅผๅธธ๏ฟฝ?", e); } return flag; }
Code Sample 2:
public static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); System.out.println("test"); URL url = new URL(addr); System.out.println("test2"); IOUtils.copy(url.openStream(), output); return output.toString(); } |
00
| Code Sample 1:
public void _getPlotTypes() { boolean gotPlots = false; while (!gotPlots) { try { _myPlotTypes = new Vector[2]; _myPlotTypes[0] = new Vector(); _myPlotTypes[1] = new Vector(); URL dataurl = new URL(getDocumentBase(), plotTypeFile); BufferedReader readme = new BufferedReader(new InputStreamReader(new GZIPInputStream(dataurl.openStream()))); while (true) { String S = readme.readLine(); if (S == null) break; StringTokenizer st = new StringTokenizer(S); _myPlotTypes[0].addElement(st.nextToken()); if (st.hasMoreTokens()) { _myPlotTypes[1].addElement(st.nextToken()); } else { _myPlotTypes[1].addElement((String) _myPlotTypes[0].lastElement()); } } gotPlots = true; } catch (IOException e) { _myPlotTypes[0].removeAllElements(); _myPlotTypes[1].removeAllElements(); gotPlots = false; } } }
Code Sample 2:
@Test public void testExactCopySize() throws IOException { final int size = Byte.SIZE + RANDOMIZER.nextInt(TEST_DATA.length - Long.SIZE); final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(size); final int cpySize = ExtraIOUtils.copy(in, out, size); assertEquals("Mismatched copy size", size, cpySize); final byte[] subArray = ArrayUtils.subarray(TEST_DATA, 0, size), outArray = out.toByteArray(); assertArrayEquals("Mismatched data", subArray, outArray); } |
11
| Code Sample 1:
public static void gunzip() throws Exception { System.out.println("gunzip()"); GZIPInputStream zipin = new GZIPInputStream(new FileInputStream("/zip/myzip.gz")); byte buffer[] = new byte[BLOCKSIZE]; FileOutputStream out = new FileOutputStream("/zip/covers"); for (int length; (length = zipin.read(buffer, 0, BLOCKSIZE)) != -1; ) out.write(buffer, 0, length); out.close(); zipin.close(); }
Code Sample 2:
public static byte[] decrypt(byte[] ciphertext, byte[] key) throws IOException { CryptInputStream in = new CryptInputStream(new ByteArrayInputStream(ciphertext), new SerpentEngine(), key); ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(in, bout); return bout.toByteArray(); } |
11
| Code Sample 1:
private static long copy(InputStream source, OutputStream sink) { try { return IOUtils.copyLarge(source, sink); } catch (IOException e) { throw new FaultException("System error copying stream", e); } finally { IOUtils.closeQuietly(source); IOUtils.closeQuietly(sink); } }
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; } |
11
| Code Sample 1:
private void generateGuid() throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); StringBuilder stringToDigest = new StringBuilder(); long time = System.currentTimeMillis(); long rand = random.nextLong(); stringToDigest.append(time); stringToDigest.append("-"); stringToDigest.append(rand); md5.update(stringToDigest.toString().getBytes()); byte[] digestBytes = md5.digest(); StringBuilder digest = new StringBuilder(); for (int i = 0; i < digestBytes.length; ++i) { int b = digestBytes[i] & 0xFF; if (b < 0x10) { digest.append('0'); } digest.append(Integer.toHexString(b)); } guid = digest.toString(); }
Code Sample 2:
char[] DigestCalcResponse(char[] HA1, String serverNonce, String nonceCount, String clientNonce, String qop, String method, String digestUri, boolean clientResponseFlag) throws SaslException { byte[] HA2; byte[] respHash; char[] HA2Hex; try { MessageDigest md = MessageDigest.getInstance("MD5"); if (clientResponseFlag) md.update(method.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(digestUri.getBytes("UTF-8")); if ("auth-int".equals(qop)) { md.update(":".getBytes("UTF-8")); md.update("00000000000000000000000000000000".getBytes("UTF-8")); } HA2 = md.digest(); HA2Hex = convertToHex(HA2); md.update(new String(HA1).getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(serverNonce.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); if (qop.length() > 0) { md.update(nonceCount.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(clientNonce.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(qop.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); } md.update(new String(HA2Hex).getBytes("UTF-8")); respHash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new SaslException("No provider found for MD5 hash", e); } catch (UnsupportedEncodingException e) { throw new SaslException("UTF-8 encoding not supported by platform.", e); } return convertToHex(respHash); } |
00
| Code Sample 1:
public void run() { try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); log.trace("passing in cookies: ", cookies); connection.setRequestProperty("Cookie", cookies); connection.getContent(); } catch (Exception e) { log.error(e); } }
Code Sample 2:
public static String MD5Digest(String source) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(source.getBytes("UTF8")); byte[] hash = digest.digest(); String strHash = byteArrayToHexString(hash); return strHash; } catch (NoSuchAlgorithmException e) { String msg = "%s: %s"; msg = String.format(msg, e.getClass().getName(), e.getMessage()); logger.error(msg); return null; } catch (UnsupportedEncodingException e) { String msg = "%s: %s"; msg = String.format(msg, e.getClass().getName(), e.getMessage()); logger.error(msg); return null; } } |
11
| Code Sample 1:
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); } }
Code Sample 2:
public static void main(String[] args) throws IOException { MSPack pack = new MSPack(new FileInputStream(args[0])); String[] files = pack.getFileNames(); for (int i = 0; i < files.length; i++) System.out.println(i + ": " + files[i] + ": " + pack.getLengths()[i]); System.out.println("Writing " + files[files.length - 1]); InputStream is = pack.getInputStream(files.length - 1); OutputStream os = new FileOutputStream(files[files.length - 1]); int n; byte[] buf = new byte[4096]; while ((n = is.read(buf)) != -1) os.write(buf, 0, n); os.close(); is.close(); } |
11
| Code Sample 1:
private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); }
Code Sample 2:
public static String compressFile(String fileName) throws IOException { String newFileName = fileName + ".gz"; FileInputStream fis = new FileInputStream(fileName); FileOutputStream fos = new FileOutputStream(newFileName); GZIPOutputStream gzos = new GZIPOutputStream(fos); byte[] buf = new byte[10000]; int bytesRead; while ((bytesRead = fis.read(buf)) > 0) gzos.write(buf, 0, bytesRead); fis.close(); gzos.close(); return newFileName; } |
11
| Code Sample 1:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); HttpSession session = request.getSession(); String session_id = session.getId(); File session_fileDir = new File(destinationDir + java.io.File.separator + session_id); session_fileDir.mkdir(); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(1 * 1024 * 1024); fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); String pathToFile = new String(); try { List items = uploadHandler.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { ; } else { pathToFile = getServletContext().getRealPath("/") + "files" + java.io.File.separator + session_id; File file = new File(pathToFile + java.io.File.separator + item.getName()); item.write(file); getContents(file, pathToFile); ComtorStandAlone.setMode(Mode.CLOUD); Comtor.start(pathToFile); } } try { File reportFile = new File(pathToFile + java.io.File.separator + "comtorReport.txt"); String reportURLString = AWSServices.storeReportS3(reportFile, session_id).toString(); if (reportURLString.startsWith("https")) reportURLString = reportURLString.replaceFirst("https", "http"); String requestURL = request.getRequestURL().toString(); String url = requestURL.substring(0, requestURL.lastIndexOf("/")); out.println("<html><head/><body>"); out.println("<a href=\"" + url + "\">Return to home</a> "); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/><hr/>"); Scanner scan = new Scanner(reportFile); out.println("<pre>"); while (scan.hasNextLine()) out.println(scan.nextLine()); out.println("</pre><hr/>"); out.println("<a href=\"" + url + "\">Return to home</a> "); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/>"); out.println("</body></html>"); } catch (Exception ex) { System.err.println(ex); } } catch (FileUploadException ex) { System.err.println("Error encountered while parsing the request" + ex); } catch (Exception ex) { System.err.println("Error encountered while uploading file" + ex); } }
Code Sample 2:
public 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; } |
11
| Code Sample 1:
public static void copyFile(String source, String dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(new File(source)).getChannel(); out = new FileOutputStream(new File(dest)).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.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; } |
11
| Code Sample 1:
public void copyFile(File source, File destination) { try { FileInputStream sourceStream = new FileInputStream(source); try { FileOutputStream destinationStream = new FileOutputStream(destination); try { FileChannel sourceChannel = sourceStream.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationStream.getChannel()); } finally { try { destinationStream.close(); } catch (Exception e) { throw new RuntimeIoException(e, IoMode.CLOSE); } } } finally { try { sourceStream.close(); } catch (Exception e) { throw new RuntimeIoException(e, IoMode.CLOSE); } } } catch (IOException e) { throw new RuntimeIoException(e, IoMode.COPY); } }
Code Sample 2:
public static String getStringFromInputStream(InputStream in) throws Exception { CachedOutputStream bos = new CachedOutputStream(); IOUtils.copy(in, bos); in.close(); bos.close(); return bos.getOut().toString(); } |
00
| Code Sample 1:
public void authenticate(final ConnectionHandler ch, final AuthenticationCriteria ac) throws NamingException { byte[] hash = new byte[DIGEST_SIZE]; try { final MessageDigest md = MessageDigest.getInstance(this.passwordScheme); md.update(((String) ac.getCredential()).getBytes()); hash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new NamingException(e.getMessage()); } ch.connect(this.config.getBindDn(), this.config.getBindCredential()); NamingEnumeration<SearchResult> en = null; try { en = ch.getLdapContext().search(ac.getDn(), "userPassword={0}", new Object[] { String.format("{%s}%s", this.passwordScheme, LdapUtil.base64Encode(hash)).getBytes() }, LdapConfig.getCompareSearchControls()); if (!en.hasMore()) { throw new AuthenticationException("Compare authentication failed."); } } finally { if (en != null) { en.close(); } } }
Code Sample 2:
protected boolean validateCaptcha(HttpServletRequest request) { String captchaID = request.getSession().getId(); String challengeResponse = StringUtils.upperCase(request.getParameter(JCaptchaEngine.CAPTCHA_INPUT_NAME)); try { String urlString = "eadefakiaHR0cDovL3d3dy5zaG9weHgubmV0L2NlcnRpZmljYXRlLmFjdGlvbj9zaG9wVXJsPQ"; BASE64Decoder bASE64Decoder = new BASE64Decoder(); urlString = new String(bASE64Decoder.decodeBuffer(StringUtils.substring(urlString, 8) + "==")); URL url = new URL(urlString + SystemConfigUtil.getSystemConfig().getShopUrl()); URLConnection urlConnection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection) urlConnection; httpConnection.getResponseCode(); } catch (IOException e) { } return captchaService.validateResponseForID(captchaID, challengeResponse); } |
11
| Code Sample 1:
public void store(Component component, String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("UPDATE component_prop " + "SET size_height = ?, size_width = ?, pos_x = ?, pos_y = ? " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); Point point = component.getLocation(); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); int update = psta.executeUpdate(); if (update == 0) { psta = jdbc.prepareStatement("INSERT INTO component_prop " + "(size_height, size_width, pos_x, pos_y, pilot_id, component_name) " + "VALUES (?,?,?,?,?,?)"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); psta.executeUpdate(); } jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
Code Sample 2:
public void savaUserPerm(String userid, Collection user_perm_collect) throws DAOException, SQLException { ConnectionProvider cp = null; Connection conn = null; ResultSet rs = null; PreparedStatement pstmt = null; PrivilegeFactory factory = PrivilegeFactory.getInstance(); Operation op = factory.createOperation(); try { cp = ConnectionProviderFactory.getConnectionProvider(Constants.DATA_SOURCE); conn = cp.getConnection(); pstmt = conn.prepareStatement(DEL_USER_PERM); pstmt.setString(1, userid); pstmt.executeUpdate(); if ((user_perm_collect == null) || (user_perm_collect.size() <= 0)) { return; } else { conn.setAutoCommit(false); pstmt = conn.prepareStatement(ADD_USER_PERM); Iterator user_perm_ir = user_perm_collect.iterator(); while (user_perm_ir.hasNext()) { UserPermission userPerm = (UserPermission) user_perm_ir.next(); pstmt.setString(1, String.valueOf(userPerm.getUser_id())); pstmt.setString(2, String.valueOf(userPerm.getResource_id())); pstmt.setString(3, String.valueOf(userPerm.getResop_id())); pstmt.executeUpdate(); } conn.commit(); conn.setAutoCommit(true); } } catch (Exception e) { e.printStackTrace(); conn.rollback(); throw new DAOException(); } finally { try { if (conn != null) { conn.close(); } if (pstmt != null) { pstmt.close(); } } catch (Exception e) { } } } |
00
| Code Sample 1:
private List<String> createProjectInfoFile() throws SocketException, IOException { FTPClient client = new FTPClient(); Set<String> projects = new HashSet<String>(); client.connect("ftp.drupal.org"); System.out.println("Connected to ftp.drupal.org"); System.out.println(client.getReplyString()); boolean loggedIn = client.login("anonymous", "[email protected]"); if (loggedIn) { FTPFile[] files = client.listFiles("pub/drupal/files/projects"); for (FTPFile file : files) { String name = file.getName(); Pattern p = Pattern.compile("([a-zAZ_]*)-(\\d.x)-(.*)"); Matcher m = p.matcher(name); if (m.matches()) { String projectName = m.group(1); String version = m.group(2); if (version.equals("6.x")) { projects.add(projectName); } } } } List<String> projectList = new ArrayList<String>(); for (String project : projects) { projectList.add(project); } Collections.sort(projectList); return projectList; }
Code Sample 2:
@Override public Directory directory() { HttpURLConnection urlConnection = null; InputStream in = null; try { URL url = new URL(DIRECTORY_URL); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate"); String encoding = urlConnection.getContentEncoding(); if ("gzip".equalsIgnoreCase(encoding)) { in = new GZIPInputStream(urlConnection.getInputStream()); } else if ("deflate".equalsIgnoreCase(encoding)) { in = new InflaterInputStream(urlConnection.getInputStream(), new Inflater(true)); } else { in = urlConnection.getInputStream(); } return persister.read(IcecastDirectory.class, in); } catch (Exception e) { throw new RuntimeException("Failed to get directory", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (urlConnection != null) { urlConnection.disconnect(); } } } |
00
| Code Sample 1:
private static void writeUrl(String filePath, String data, String charCoding, boolean urlIsFile) throws IOException { int chunkLength; OutputStream os = null; try { if (!urlIsFile) { URL urlObj = new URL(filePath); URLConnection uc = urlObj.openConnection(); os = uc.getOutputStream(); if (charCoding == null) { String type = uc.getContentType(); if (type != null) { charCoding = getCharCodingFromType(type); } } } else { File f = new File(filePath); os = new FileOutputStream(f); } Writer w; if (charCoding == null) { w = new OutputStreamWriter(os); } else { w = new OutputStreamWriter(os, charCoding); } w.write(data); w.flush(); } finally { if (os != null) os.close(); } }
Code Sample 2:
public void testHttpsConnection() { try { URL url = new URL("https://addons.mozilla.org/zh-CN/firefox/"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setDoOutput(true); connection.getOutputStream().write("hello".getBytes()); } catch (Exception e) { e.printStackTrace(); } } |
00
| Code Sample 1:
public static void copyFile(File in, File out) { int len; byte[] buffer = new byte[1024]; try { FileInputStream fin = new FileInputStream(in); FileOutputStream fout = new FileOutputStream(out); while ((len = fin.read(buffer)) >= 0) fout.write(buffer, 0, len); fin.close(); fout.close(); } catch (IOException ex) { } }
Code Sample 2:
public String connectToServlet() { URL urlStory = null; BufferedReader brStory; String result = ""; try { urlStory = new URL(getCodeBase(), "http://localhost:8080/javawebconsole/ToApplet"); } catch (MalformedURLException MUE) { MUE.printStackTrace(); } try { brStory = new BufferedReader(new InputStreamReader(urlStory.openStream())); while (brStory.ready()) { result += brStory.readLine(); } } catch (IOException IOE) { IOE.printStackTrace(); } return result; } |
00
| Code Sample 1:
public String decrypt(String text, String passphrase, int keylen) { RC2ParameterSpec parm = new RC2ParameterSpec(keylen); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes(getCharset())); SecretKeySpec skeySpec = new SecretKeySpec(md.digest(), "RC2"); Cipher cipher = Cipher.getInstance("RC2/ECB/NOPADDING"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, parm); byte[] dString = Base64.decode(text); byte[] d = cipher.doFinal(dString); String clearTextNew = decodeBytesNew(d); return clearTextNew; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
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(); } |
11
| Code Sample 1:
private static long copy(InputStream source, OutputStream sink) { try { return IOUtils.copyLarge(source, sink); } catch (IOException e) { throw new FaultException("System error copying stream", e); } finally { IOUtils.closeQuietly(source); IOUtils.closeQuietly(sink); } }
Code Sample 2:
public static boolean copyFile(File soureFile, File destFile) { boolean copySuccess = false; if (soureFile != null && destFile != null && soureFile.exists()) { try { new File(destFile.getParent()).mkdirs(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destFile)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(soureFile)); for (int currentByte = in.read(); currentByte != -1; currentByte = in.read()) out.write(currentByte); in.close(); out.close(); copySuccess = true; } catch (Exception e) { copySuccess = false; } } return copySuccess; } |
00
| Code Sample 1:
public void execute(HttpResponse response) throws HttpException, IOException { Collection<Data> allData = internalDataBank.getAll(); StringBuffer content = new StringBuffer(); for (Data data : allData) { content.append("keyHash:").append(data.getKeyHash()).append(", "); content.append("version:").append(data.getVersion()).append(", "); content.append("size:").append(data.getContent().length); content.append(SystemUtils.LINE_SEPARATOR); } StringEntity body = new StringEntity(content.toString()); body.setContentType(PLAIN_TEXT_RESPONSE_CONTENT_TYPE); response.setEntity(body); }
Code Sample 2:
public static String[] getURLListFromResource(String resourceName, String regExFilter, boolean firstNoEmptyMatched) { String[] urlArray; Vector<String> urlVector = new Vector<String>(); try { ClassLoader classLoader = MqatMain.class.getClassLoader(); URLClassLoader urlClassLoader = (URLClassLoader) classLoader; Enumeration e = urlClassLoader.findResources(resourceName); for (; e.hasMoreElements(); ) { URL url = (URL) e.nextElement(); if ("file".equals(url.getProtocol())) { File file = new File(url.getPath()); File[] fileList = file.listFiles(); if (fileList != null) { for (int i = 0; i < fileList.length; i++) { String urlStr = fileList[i].toURL().toString(); if (urlStr.matches(regExFilter)) { urlVector.add(urlStr); } } } } else if ("jar".equals(url.getProtocol())) { JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); JarFile jarFile = jarConnection.getJarFile(); Enumeration jarEntries = jarFile.entries(); for (; jarEntries.hasMoreElements(); ) { JarEntry jarEntry = (JarEntry) jarEntries.nextElement(); if (!jarEntry.isDirectory()) { String urlStr = url.toString().substring(0, url.toString().lastIndexOf('!') + 1); urlStr += "/" + jarEntry; if (urlStr.matches(regExFilter)) { urlVector.add(urlStr); } } } } if (!urlVector.isEmpty() && firstNoEmptyMatched) { break; } } } catch (Exception ex) { ExceptionHandler.handle(ex, ExceptionHandler.NO_VISUAL); } urlArray = urlVector.toArray(new String[urlVector.size()]); return urlArray; } |
11
| Code Sample 1:
public HashCash(String cash) throws NoSuchAlgorithmException { myToken = cash; String[] parts = cash.split(":"); myVersion = Integer.parseInt(parts[0]); if (myVersion < 0 || myVersion > 1) throw new IllegalArgumentException("Only supported versions are 0 and 1"); if ((myVersion == 0 && parts.length != 6) || (myVersion == 1 && parts.length != 7)) throw new IllegalArgumentException("Improperly formed HashCash"); try { int index = 1; if (myVersion == 1) myValue = Integer.parseInt(parts[index++]); else myValue = 0; SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString); Calendar tempCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); tempCal.setTime(dateFormat.parse(parts[index++])); myResource = parts[index++]; myExtensions = deserializeExtensions(parts[index++]); MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(cash.getBytes()); byte[] tempBytes = md.digest(); int tempValue = numberOfLeadingZeros(tempBytes); if (myVersion == 0) myValue = tempValue; else if (myVersion == 1) myValue = (tempValue > myValue ? myValue : tempValue); } catch (java.text.ParseException ex) { throw new IllegalArgumentException("Improperly formed HashCash", ex); } }
Code Sample 2:
static String getMD5Sum(String source) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(source.getBytes()); byte[] md5sum = digest.digest(); BigInteger bigInt = new BigInteger(1, md5sum); return bigInt.toString(16); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("MD5 algorithm seems to not be supported. This is a requirement!"); } } |
00
| Code Sample 1:
private MapProperties readProperties(URL url) { @SuppressWarnings("unchecked") MapProperties properties = new MapProperties(new LinkedHashMap()); InputStream is = null; try { is = url.openStream(); properties.load(is); } catch (IOException ex) { throw new RuntimeException(ex); } finally { StreamUtils.close(is); } return properties; }
Code Sample 2:
private static FileChannel getFileChannel(File file, boolean isOut, boolean append) throws OpenR66ProtocolSystemException { FileChannel fileChannel = null; try { if (isOut) { FileOutputStream fileOutputStream = new FileOutputStream(file.getPath(), append); fileChannel = fileOutputStream.getChannel(); if (append) { try { fileChannel.position(file.length()); } catch (IOException e) { } } } else { if (!file.exists()) { throw new OpenR66ProtocolSystemException("File does not exist"); } FileInputStream fileInputStream = new FileInputStream(file.getPath()); fileChannel = fileInputStream.getChannel(); } } catch (FileNotFoundException e) { throw new OpenR66ProtocolSystemException("File not found", e); } return fileChannel; } |
00
| Code Sample 1:
public static String sha1(String clearText, String seed) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update((seed + clearText).getBytes()); return convertToHex(md.digest()); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }
Code Sample 2:
private boolean downloadFile(Proxy proxy, URL url, File file) { try { URLConnection conn = null; if (null == proxy) { conn = url.openConnection(); } else { conn = url.openConnection(proxy); } conn.connect(); File destFile = new File(file.getAbsolutePath() + ".update"); ; FileOutputStream fos = new FileOutputStream(destFile); byte[] buffer = new byte[2048]; while (true) { int len = conn.getInputStream().read(buffer); if (len < 0) { break; } else { fos.write(buffer, 0, len); } } fos.close(); file.delete(); destFile.renameTo(file); return true; } catch (Exception e) { logger.error("Failed to get remote hosts file.", e); } return false; } |
00
| Code Sample 1:
public static String cryptografar(String senha) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(senha.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); senha = hash.toString(16); } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); } return senha; }
Code Sample 2:
public static ArrayList<String> remoteCall(Map<String, String> dataDict) { ArrayList<String> result = new ArrayList<String>(); String encodedData = ""; for (String key : dataDict.keySet()) { String encodedSegment = ""; String value = dataDict.get(key); if (value == null) continue; try { encodedSegment = key + "=" + URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (encodedData.length() > 0) { encodedData += "&"; } encodedData += encodedSegment; } try { URL url = new URL(baseURL + encodedData); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { result.add(line); System.out.println("GOT: " + line); } reader.close(); result.remove(0); if (result.size() != 0) { if (!result.get(result.size() - 1).equals("DONE")) { result.clear(); } else { result.remove(result.size() - 1); } } } catch (MalformedURLException e) { } catch (IOException e) { } return result; } |
00
| Code Sample 1:
public static void logout(String verify) throws NetworkException { HttpClient client = HttpUtil.newInstance(); HttpGet get = new HttpGet(HttpUtil.KAIXIN_LOGOUT_URL + HttpUtil.KAIXIN_PARAM_VERIFY + verify); HttpUtil.setHeader(get); try { HttpResponse response = client.execute(get); if (response != null && response.getEntity() != null) { HTTPUtil.consume(response.getEntity()); } } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } }
Code Sample 2:
public List<AnalyzerResult> analyze(String urlString, boolean tryFallback) { List<AnalyzerResult> results = new ArrayList<AnalyzerResult>(); try { URL url; if (flow == null) { url = new URL(DEFAULT_FLOW_URL + "?" + DEFAULT_INPUT + "=" + urlString); } else { url = new URL(flow.getUrl() + "?" + flow.getInputList().get(0) + "=" + urlString); } System.setProperty("javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl"); System.out.println("Executing: " + url.toString()); XMLDecoder decoder = new XMLDecoder(url.openStream()); Map map = (Map) decoder.readObject(); for (Object key : map.keySet()) { results.add(new AnalyzerResult(key.toString(), map.get(key).toString())); } } catch (Exception ex) { ex.printStackTrace(); VueUtil.alert("Can't Execute Flow on the url " + urlString, "Can't Execute Seasr flow"); } return results; } |
00
| Code Sample 1:
public void testDecode1000BinaryStore() throws Exception { EXISchema corpus = EXISchemaFactoryTestUtil.getEXISchema("/DataStore/DataStore.xsd", getClass(), m_compilerErrors); Assert.assertEquals(0, m_compilerErrors.getTotalCount()); GrammarCache grammarCache = new GrammarCache(corpus, GrammarOptions.STRICT_OPTIONS); String[] base64Values100 = { "R0lGODdhWALCov////T09M7Ozqampn19fVZWVi0tLQUFBSxYAsJAA/8Iutz+MMpJq7046827/2Ao\n", "/9j/4BBKRklGAQEBASwBLP/hGlZFeGlmTU0qF5ZOSUtPTiBDT1JQT1JBVElPTk5J", "R0lGODlhHh73KSkpOTk5QkJCSkpKUlJSWlpaY2Nja2trc3Nze3t7hISEjIyMlJSUnJycpaWlra2t\n" + "tbW1vb29xsbGzs7O1tbW3t7e5+fn7+/v//////////8=", "/9j/4BBKRklGAQEBAf/bQwYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBc=", "R0lGODlhHh73M2aZzP8zMzNmM5kzzDP/M2YzZmZmmWbM", "/9j/4BBKRklGAQEBAf/bQwYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsj\n" + "HBYWICwgIyYnKSopGR8tMC0oMCUoKSj/20M=", "R0lGODdhWAK+ov////j4+NTU1JOTk0tLSx8fHwkJCSxYAr5AA/8IMkzjrEEmahy23SpC", "R0lGODdh4QIpAncJIf4aU29mdHdhcmU6IE1pY3Jvc29mdCBPZmZpY2Us4QIpAof//////8z//5n/\n", "R0lGODdhWAK+ov////v7++fn58DAwI6Ojl5eXjExMQMDAyxYAr5AA/8Iutz+MMpJq7046827/2Ao\n" + "jmRpnmiqPsKxvg==", "R0lGODdh4QIpAncJIf4aU29mdHdhcmU6IE1pY3Jvc29mdCBPZmZpY2Us4QIpAob//////8z//5n/\nzP//zMw=" }; AlignmentType alignment = AlignmentType.bitPacked; Transmogrifier encoder = new Transmogrifier(); encoder.setEXISchema(grammarCache); encoder.setAlignmentType(alignment); ByteArrayOutputStream baos = new ByteArrayOutputStream(); encoder.setOutputStream(baos); URL url = resolveSystemIdAsURL("/DataStore/instance/1000BinaryStore.xml"); encoder.encode(new InputSource(url.openStream())); byte[] bts = baos.toByteArray(); Scanner scanner; int n_texts; EXIDecoder decoder = new EXIDecoder(999); decoder.setEXISchema(grammarCache); decoder.setAlignmentType(alignment); decoder.setInputStream(new ByteArrayInputStream(bts)); scanner = decoder.processHeader(); EXIEvent exiEvent; n_texts = 0; while ((exiEvent = scanner.nextEvent()) != null) { if (exiEvent.getEventVariety() == EXIEvent.EVENT_CH) { if (++n_texts % 100 == 0) { String expected = base64Values100[(n_texts / 100) - 1]; String val = exiEvent.getCharacters().makeString(); Assert.assertEquals(expected, val); } } } Assert.assertEquals(1000, n_texts); }
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:
@Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; }
Code Sample 2:
public void migrateTo(String newExt) throws IOException { DigitalObject input = new DigitalObject.Builder(Content.byReference(new File(AllJavaSEServiceTestsuite.TEST_FILE_LOCATION + "PlanetsLogo.png").toURI().toURL())).build(); System.out.println("Input: " + input); FormatRegistry format = FormatRegistryFactory.getFormatRegistry(); MigrateResult mr = dom.migrate(input, format.createExtensionUri("png"), format.createExtensionUri(newExt), null); ServiceReport sr = mr.getReport(); System.out.println("Got Report: " + sr); DigitalObject doOut = mr.getDigitalObject(); assertTrue("Resulting digital object is null.", doOut != null); System.out.println("Output: " + doOut); System.out.println("Output.content: " + doOut.getContent()); File out = new File("services/java-se/test/results/test." + newExt); FileOutputStream fo = new FileOutputStream(out); IOUtils.copyLarge(doOut.getContent().getInputStream(), fo); fo.close(); System.out.println("Recieved service report: " + mr.getReport()); System.out.println("Recieved service properties: "); ServiceProperties.printProperties(System.out, mr.getReport().getProperties()); } |
00
| Code Sample 1:
public static String digest(String algorithm, String text) { MessageDigest mDigest = null; try { mDigest = MessageDigest.getInstance(algorithm); mDigest.update(text.getBytes(ENCODING)); } catch (NoSuchAlgorithmException nsae) { Logger.error(Encryptor.class, nsae.getMessage(), nsae); } catch (UnsupportedEncodingException uee) { Logger.error(Encryptor.class, uee.getMessage(), uee); } byte raw[] = mDigest.digest(); return (new BASE64Encoder()).encode(raw); }
Code Sample 2:
public static void copyFile(File src, File dest, boolean preserveFileDate) throws IOException { if (src.exists() && src.isDirectory()) { throw new IOException("source file exists but is a directory"); } if (dest.exists() && dest.isDirectory()) { dest = new File(dest, src.getName()); } if (!dest.exists()) { dest.createNewFile(); } FileChannel srcCH = null; FileChannel destCH = null; try { srcCH = new FileInputStream(src).getChannel(); destCH = new FileOutputStream(dest).getChannel(); destCH.transferFrom(srcCH, 0, srcCH.size()); } finally { closeQuietly(srcCH); closeQuietly(destCH); } if (src.length() != dest.length()) { throw new IOException("Failed to copy full contents from '" + src + "' to '" + dest + "'"); } if (preserveFileDate) { dest.setLastModified(src.lastModified()); } } |
00
| Code Sample 1:
public static long[] getUids(String myUid) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpGet get = new HttpGet(UIDS_URI); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); JSONArray result = new JSONArray(res); long[] friends = new long[result.length()]; long uid = Long.parseLong(myUid); for (int i = 0; i < result.length(); i++) { if (uid != result.getLong(i)) { friends[i] = result.getLong(i); } } return friends; } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); }
Code Sample 2:
public void launch(String xmlControl, String xmlDoc, long docId) { AgentLauncher l; Environment env; Properties prop; Resource res; String token; String deflt; String answ; String key; String entry; ShipService service; de.fhg.igd.util.URL url; java.net.URL wsurl; NodeList flow; InputSource xmlcontrolstream; TreeMap results; synchronized (lock_) { if (xmlControl == null || xmlControl.length() == 0 || xmlDoc == null || xmlDoc.length() == 0) { System.out.println("---- Need control AND XML document! ----"); return; } Vector v_delegations_host = new Vector(); Vector v_delegations_url = new Vector(); Vector v_delegations_method = new Vector(); xmlcontrolstream = new InputSource(new StringReader(xmlControl)); NodeList destinations = SimpleXMLParser.parseDocument(xmlcontrolstream, AgentBehaviour.XML_DELEGATE); for (int i = 0; i < destinations.getLength(); i++) { if (destinations.item(i).getTextContent() != null && destinations.item(i).getTextContent().length() > 0) { System.out.println(destinations.item(i).getTextContent()); entry = SimpleXMLParser.findChildEntry(destinations.item(i), AgentBehaviour.XML_HOST); v_delegations_host.add(entry); entry = SimpleXMLParser.findChildEntry(destinations.item(i), AgentBehaviour.XML_URL); v_delegations_url.add(entry); entry = SimpleXMLParser.findChildEntry(destinations.item(i), AgentBehaviour.XML_METHOD); v_delegations_method.add(entry); } } token = ""; results = new TreeMap(); for (int i = 0; i < TOKEN_LENGTH; i++) { token = token + (char) (Math.random() * 26 + 65); } results.put(token, null); prop = AgentStructure.defaults(); prop.setProperty(AgentStructure.PROP_AGENT_CLASS, AGENT_); prop.setProperty(AgentBehaviour.CTX_DOCID, String.valueOf(docId)); prop.setProperty(AgentBehaviour.CTX_XML, xmlDoc); prop.setProperty("token", token); deflt = prop.getProperty(AgentStructure.PROP_AGENT_EXCLUDE); prop.setProperty(AgentStructure.PROP_AGENT_EXCLUDE, deflt + ":" + ADDITIONAL_EXCLUDES); service = (ShipService) getEnvironment().lookup(WhatIs.stringValue(ShipService.WHATIS)); for (int i = 0; i < v_delegations_host.size(); i++) { System.out.println("\n-----SCANNING DELEGATES-----"); System.out.println("\n-----DELEGATE " + i + "-----"); System.out.println("-----HOST: " + i + ": " + (String) v_delegations_host.elementAt(i)); System.out.println("-----URL: " + i + ": " + (String) v_delegations_url.elementAt(i)); System.out.println("-----METHOD: " + i + ": " + (String) v_delegations_method.elementAt(i)); try { url = new de.fhg.igd.util.URL((String) v_delegations_host.elementAt(i)); boolean alive = service.isAlive(url); System.out.println("-----ALIVE: " + alive); if (alive) { wsurl = new java.net.URL((String) v_delegations_url.elementAt(i)); try { wsurl.openStream(); System.out.println("-----WEBSERVICE: ON"); if (!prop.containsKey(0 + "." + AgentBehaviour.XML_URL)) { System.out.println("-----MIGRATION: First online host found. I will migrate here:)!"); prop.setProperty(0 + "." + AgentBehaviour.XML_HOST, (String) v_delegations_host.elementAt(i)); prop.setProperty(0 + "." + AgentBehaviour.XML_URL, (String) v_delegations_url.elementAt(i)); prop.setProperty(0 + "." + AgentBehaviour.XML_METHOD, (String) v_delegations_method.elementAt(i)); } else { System.out.println("-----MIGRATION: I will not migrate here:(!"); } } catch (IOException ex) { System.out.println("-----WEBSERVICE: Could not connect to the webservice!"); System.out.println("-----MIGRATION: WEBSERVICE NOT FOUND! I will not migrate here:(!"); } } } catch (ShipException she) { System.out.println("-----ALIVE: false"); System.out.println("-----MIGRATION: HOST NOT FOUND! I will not migrate here:(!"); } catch (SecurityException see) { System.out.println("-----EXCEPTION: Access connection to remote SHIP service fails! " + "No proper ShipPermission permission to invoke lookups! " + "Ignoring this host...."); } catch (MalformedURLException murle) { System.out.println("-----EXCEPTION: The host URL is not valid! Ignoring this host...."); } } res = new MemoryResource(); env = Environment.getEnvironment(); key = WhatIs.stringValue(AgentLauncher.WHATIS); l = (AgentLauncher) env.lookup(key); if (l == null) { System.out.println("Can't find the agent launcher"); return; } try { l.launchAgent(res, prop); } catch (IllegalAgentException ex) { System.out.println(ex); } catch (GeneralSecurityException ex) { System.out.println(ex); } catch (IOException ex) { System.out.println(ex); } syncmap_.put(token, results); System.out.println("----- TOKEN = " + token + "------"); } try { synchronized (token) { token.wait(TIMEOUT); Map m_results = (Map) syncmap_.get(token); Collection c_results = m_results.values(); String[] sa_results = (String[]) c_results.toArray(new String[0]); answ = ""; for (int j = 0; j < sa_results.length; j++) { answ = answ + sa_results[j]; } syncmap_.remove(token); System.out.println("----- " + answ + " -----"); callbackWS(xmlControl, answ, docId); } } catch (InterruptedException ex) { System.out.println(ex); } } |
00
| Code Sample 1:
public static List<String> getServers() throws Exception { List<String> servers = new ArrayList<String>(); URL url = new URL("http://tfast.org/en/servers.php"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = in.readLine()) != null) { if (line.contains("serv=")) { int i = line.indexOf("serv="); servers.add(line.substring(i + 5, line.indexOf("\"", i))); } } in.close(); return servers; }
Code Sample 2:
private void output(HttpServletResponse resp, InputStream is, long length, String fileName) throws Exception { resp.reset(); String mimeType = "image/jpeg"; resp.setContentType(mimeType); resp.setContentLength((int) length); resp.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\""); resp.setHeader("Cache-Control", "must-revalidate"); ServletOutputStream sout = resp.getOutputStream(); IOUtils.copy(is, sout); sout.flush(); resp.flushBuffer(); } |
11
| Code Sample 1:
public void test3() throws FileNotFoundException, IOException { Decoder decoder1 = new MP3Decoder(new FileInputStream("/home/marc/tmp/test1.mp3")); Decoder decoder2 = new OggDecoder(new FileInputStream("/home/marc/tmp/test1.ogg")); FileOutputStream out = new FileOutputStream("/home/marc/tmp/test.pipe"); IOUtils.copy(decoder1, out); IOUtils.copy(decoder2, out); }
Code Sample 2:
@Override public void handle(HttpExchange http) throws IOException { Headers reqHeaders = http.getRequestHeaders(); Headers respHeader = http.getResponseHeaders(); respHeader.add("Content-Type", "text/plain"); http.sendResponseHeaders(200, 0); PrintWriter console = new PrintWriter(System.err); PrintWriter web = new PrintWriter(http.getResponseBody()); PrintWriter out = new PrintWriter(new YWriter(web, console)); out.println("### " + new Date() + " ###"); out.println("Method: " + http.getRequestMethod()); out.println("Protocol: " + http.getProtocol()); out.println("RemoteAddress.HostName: " + http.getRemoteAddress().getHostName()); for (String key : reqHeaders.keySet()) { out.println("* \"" + key + "\""); for (String v : reqHeaders.get(key)) { out.println("\t" + v); } } InputStream in = http.getRequestBody(); if (in != null) { out.println(); IOUtils.copyTo(new InputStreamReader(in), out); in.close(); } out.flush(); out.close(); } |
00
| Code Sample 1:
private String hashString(String key) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(key.getBytes()); byte[] hash = digest.digest(); BigInteger bi = new BigInteger(1, hash); return String.format("%0" + (hash.length << 1) + "X", bi) + KERNEL_VERSION; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return "" + key.hashCode(); } }
Code Sample 2:
public void sendMail() throws Exception { try { if (param.length > 0) { System.setProperty("mail.host", param[0].trim()); URL url = new URL("mailto:" + param[1].trim()); URLConnection conn = url.openConnection(); PrintWriter out = new PrintWriter(conn.getOutputStream(), true); out.print("To:" + param[1].trim() + "\n"); out.print("Subject: " + param[2] + "\n"); out.print("MIME-Version: 1.0\n"); out.print("Content-Type: multipart/mixed; boundary=\"tcppop000\"\n\n"); out.print("--tcppop000\n"); out.print("Content-Type: text/plain\n"); out.print("Content-Transfer-Encoding: 7bit\n\n\n"); out.print(param[3] + "\n\n\n"); out.print("--tcppop000\n"); String filename = param[4].trim(); int sep = filename.lastIndexOf(File.separator); if (sep > 0) { filename = filename.substring(sep + 1, filename.length()); } out.print("Content-Type: text/html; name=\"" + filename + "\"\n"); out.print("Content-Transfer-Encoding: binary\n"); out.print("Content-Disposition: attachment; filename=\"" + filename + "\"\n\n"); System.out.println("FOR ATTACHMENT Content-Transfer-Encoding: binary "); RandomAccessFile file = new RandomAccessFile(param[4].trim(), "r"); byte[] buffer = new byte[(int) file.length()]; file.readFully(buffer); file.close(); String fileContent = new String(buffer); out.print(fileContent); out.print("\n"); out.print("--tcppop000--"); out.close(); } else { } } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } } |
00
| Code Sample 1:
public Image getURLImage(String url) { if (!images.containsKey(url)) { try { URL img = new URL(url); images.put(url, new Image(null, img.openStream())); } catch (Exception e) { throw new RuntimeException(e.getMessage() + ": " + url); } } imageTimes.put(url, System.currentTimeMillis()); return images.get(url); }
Code Sample 2:
public static void decryptFile(String input, String output, String pwd) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(input), cipher); out = new FileOutputStream(output); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.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.B64InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void initializeWebInfo() throws MalformedURLException, IOException, DOMException { Tidy tidy = new Tidy(); URL url = new URL(YOUTUBE_URL + videoId); InputStream in = url.openConnection().getInputStream(); Document doc = tidy.parseDOM(in, null); Element e = doc.getDocumentElement(); String title = null; if (e != null && e.hasChildNodes()) { NodeList children = e.getElementsByTagName("title"); if (children != null) { for (int i = 0; i < children.getLength(); i++) { try { Element childE = (Element) children.item(i); if (childE.getTagName().equals("title")) { NodeList titleChildren = childE.getChildNodes(); for (int n = 0; n < titleChildren.getLength(); n++) { if (titleChildren.item(n).getNodeType() == childE.TEXT_NODE) { title = titleChildren.item(n).getNodeValue(); } } } } catch (Exception exp) { exp.printStackTrace(); } } } } if (title == null || title.equals("")) { throw new DOMException(DOMException.NOT_FOUND_ERR, "no title found"); } else { setTitle(title); } } |
11
| Code Sample 1:
private void copy(File from, File to) throws IOException { InputStream in = new FileInputStream(from); OutputStream out = new FileOutputStream(to); byte[] line = new byte[16384]; int bytes = -1; while ((bytes = in.read(line)) != -1) out.write(line, 0, bytes); in.close(); out.close(); }
Code Sample 2:
public 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:
public Program updateProgramPath(int id, String sourcePath) throws AdaptationException { Program program = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "UPDATE Programs SET " + "sourcePath = '" + sourcePath + "' " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * from Programs WHERE id = " + id; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to update program failed."; log.error(msg); throw new AdaptationException(msg); } program = getProgram(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in updateProgramPath"; 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 program; }
Code Sample 2:
public static void decompressFile(File f) throws IOException { File target = new File(f.toString().substring(0, f.toString().length() - 3)); System.out.print("Decompressing: " + f.getName() + ".. "); long initialSize = f.length(); GZIPInputStream in = new GZIPInputStream(new FileInputStream(f)); FileOutputStream fos = new FileOutputStream(target); byte[] buf = new byte[1024]; int read; while ((read = in.read(buf)) != -1) { fos.write(buf, 0, read); } System.out.println("Done."); fos.close(); in.close(); long endSize = target.length(); System.out.println("Initial size: " + initialSize + "; Decompressed size: " + endSize); } |
11
| Code Sample 1:
public static boolean changeCredentials() { boolean passed = false; boolean credentials = false; HashMap info = null; Debug.log("Main.changeCredentials", "show dialog for userinfo"); info = getUserInfo(); if ((Boolean) info.get("submit")) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(info.get("password").toString().getBytes()); String passHash = new BigInteger(1, md5.digest()).toString(16); Debug.log("Main.changeCredentials", "validate credentials with the database"); passed = xmlRpcC.checkUser(info.get("username").toString(), passHash); Debug.log("Main.changeCredentials", "write the credentials to file"); xmlC.writeUserdata(userdataFile, info.get("username").toString(), passHash); credentials = passed; testVar = true; } catch (Exception ex) { System.out.println(ex.toString()); if (ex.getMessage().toLowerCase().contains("unable")) { JOptionPane.showMessageDialog(null, "Database problem occured, please try again later", "Error", JOptionPane.ERROR_MESSAGE); passed = true; testVar = false; } else { passed = Boolean.parseBoolean(ex.getMessage()); JOptionPane.showMessageDialog(null, "Invallid userdata, try again", "Invallid userdata", JOptionPane.ERROR_MESSAGE); } } } else { if (new File(userdataFile).exists()) { testVar = true; credentials = true; } else { testVar = false; JOptionPane.showMessageDialog(null, "No userdata was entered\nNo tests will be executed until you enter them ", "Warning", JOptionPane.ERROR_MESSAGE); } passed = true; } while (!passed) { Debug.log("Main.changeCredentials", "show dialog for userinfo"); info = getUserInfo(); if ((Boolean) info.get("submit")) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(info.get("password").toString().getBytes()); String passHash = new BigInteger(1, md5.digest()).toString(16); Debug.log("Main.changeCredentials", "validate credentials with the database"); passed = xmlRpcC.checkUser(info.get("username").toString(), passHash); Debug.log("Main.changeCredentials", "write credentials to local xml file"); xmlC.writeUserdata(userdataFile, info.get("username").toString(), passHash); credentials = passed; testVar = true; } catch (Exception ex) { Debug.log("Main.changeCredentials", "credential validation failed"); passed = Boolean.parseBoolean(ex.getMessage()); JOptionPane.showMessageDialog(null, "Invallid userdata, try again", "Invallid userdata", JOptionPane.ERROR_MESSAGE); } } else { if (new File(userdataFile).exists()) { testVar = true; credentials = true; } else { testVar = false; JOptionPane.showMessageDialog(null, "No userdata was entered\nNo tests will be executed untill u enter them ", "Warning", JOptionPane.ERROR_MESSAGE); } passed = true; } } return credentials; }
Code Sample 2:
public void actionPerformed(ActionEvent e) { String digest = null; try { MessageDigest m = MessageDigest.getInstance("sha1"); m.reset(); String pw = String.copyValueOf(this.login.getPassword()); m.update(pw.getBytes()); byte[] digestByte = m.digest(); BigInteger bi = new BigInteger(digestByte); digest = bi.toString(); System.out.println(digest); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } this.model.login(this.login.getHost(), this.login.getPort(), this.login.getUser(), digest); } |
00
| Code Sample 1:
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (log.isTraceEnabled()) { log.trace("doGet(requestURI=" + request.getRequestURI() + ")"); } ServletConfig sc = getServletConfig(); String uriPrefix = request.getContextPath() + "/" + request.getServletPath(); String resUri = request.getRequestURI().substring(uriPrefix.length()); if (log.isTraceEnabled()) { log.trace("Request for resource '" + resUri + "'"); } boolean allowAccess = true; String prefixesSpec = sc.getInitParameter(PARAM_ALLOWED_PREFIXES); if (null != prefixesSpec && prefixesSpec.length() > 0) { String[] prefixes = prefixesSpec.split(";"); allowAccess = false; if (log.isTraceEnabled()) { log.trace("allowedPrefixes specified; checking access"); } for (String prefix : prefixes) { if (log.isTraceEnabled()) { log.trace("Checking resource URI '" + resUri + "' against allowed prefix '" + prefix + "'"); } if (resUri.startsWith(prefix)) { if (log.isTraceEnabled()) { log.trace("Found matching prefix for resource URI '" + resUri + "': '" + prefix + "'"); } allowAccess = true; break; } } } if (!allowAccess) { if (log.isWarnEnabled()) { log.warn("Requested for resource that does not match with" + " allowed prefixes: " + resUri); } response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String resPrefix = sc.getInitParameter(PARAM_RESOURCE_PREFIX); if (null != resPrefix && resPrefix.length() > 0) { if (log.isTraceEnabled()) { log.trace("resourcePrefix specified: " + resPrefix); } if (resPrefix.endsWith("/")) { resUri = resPrefix + resUri; } else { resUri = resPrefix + "/" + resUri; } } resUri = resUri.replaceAll("\\/\\/+", "/"); if (log.isTraceEnabled()) { log.trace("Qualified (prefixed) resource URI: " + resUri); } String baseClassName = sc.getInitParameter(PARAM_BASE_CLASS); if (null == baseClassName || 0 == baseClassName.length()) { if (log.isTraceEnabled()) { log.trace("No baseClass initialization parameter specified; using default: " + ResourceLoaderServlet.class.getName()); } baseClassName = ResourceLoaderServlet.class.getName(); } else { if (log.isTraceEnabled()) { log.trace("Using baseClass: " + baseClassName); } } Class baseClass; try { baseClass = Class.forName(baseClassName); } catch (ClassNotFoundException ex) { throw new ServletException("Base class '" + baseClassName + "' not found", ex); } URL resUrl = baseClass.getResource(resUri); if (null != resUrl) { if (log.isTraceEnabled()) { log.trace("Sending resource: " + resUrl); } URLConnection urlc = resUrl.openConnection(); response.setContentType(urlc.getContentType()); response.setContentLength(urlc.getContentLength()); response.setStatus(HttpServletResponse.SC_OK); final byte[] buf = new byte[255]; int r = 0; InputStream in = new BufferedInputStream(urlc.getInputStream()); OutputStream out = new BufferedOutputStream(response.getOutputStream()); do { r = in.read(buf, 0, 255); if (r > 0) { out.write(buf, 0, r); } } while (r > 0); in.close(); out.flush(); out.close(); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource not found"); } }
Code Sample 2:
private DataFileType[] getDataFiles(Collection<ContentToSend> contentsToSend) { DataFileType[] files = new DataFileType[contentsToSend.size()]; int fileIndex = 0; for (ContentToSend contentToSend : contentsToSend) { DataFileType dataFile = DataFileType.Factory.newInstance(); dataFile.setFilename(contentToSend.getFileName()); dataFile.setId("D" + fileIndex); dataFile.setMimeType(contentToSend.getMimeType()); dataFile.setContentType(DataFileType.ContentType.EMBEDDED_BASE_64); final StringWriter stringWriter = new StringWriter(); final OutputStream encodeStream = Base64.newEncoder(stringWriter, 0, null); final InputStream is = contentToSend.getInputStream(); try { long sizeCopied = IOUtils.copyLarge(is, encodeStream); dataFile.setSize(BigDecimal.valueOf(sizeCopied)); } catch (IOException e) { throw new RuntimeException("Failed to get input to the file to be sent", e); } finally { IOUtils.closeQuietly(encodeStream); IOUtils.closeQuietly(is); } dataFile.setStringValue(stringWriter.toString()); files[fileIndex++] = dataFile; } return files; } |
11
| Code Sample 1:
public void processExplicitSchemaAndWSDL(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { HashMap services = configContext.getAxisConfiguration().getServices(); String filePart = req.getRequestURL().toString(); String schema = filePart.substring(filePart.lastIndexOf("/") + 1, filePart.length()); if ((services != null) && !services.isEmpty()) { Iterator i = services.values().iterator(); while (i.hasNext()) { AxisService service = (AxisService) i.next(); InputStream stream = service.getClassLoader().getResourceAsStream("META-INF/" + schema); if (stream != null) { OutputStream out = res.getOutputStream(); res.setContentType("text/xml"); IOUtils.copy(stream, out, true); return; } } } }
Code Sample 2:
public 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:
public void connect(String ftpHost, int ftpPort, String ftpUser, String ftpPwd) throws IOException { ftpClient = new FTPClient(); ftpClient.setReaderThread(false); if (ftpPort == -1) ftpClient.connect(ftpHost); else ftpClient.connect(ftpHost, ftpPort); logger.info("FTP Connection Successful: " + ftpHost); ftpClient.login(ftpUser, ftpPwd); }
Code Sample 2:
@Test public void testGetJarInformation() throws Exception { final URL url1 = getClass().getResource("/fakejars/something"); final URL url2 = getClass().getResource("/fakejars/something-else"); final URL url3 = getClass().getResource("/fakejars/another-thing"); final Map<String, Date> paths = new HashMap<String, Date>(); paths.put(SOMETHING_JAR, new Date(url1.openConnection().getLastModified())); paths.put(SOMETHING_ELSE_JAR, new Date(url2.openConnection().getLastModified())); paths.put(ANOTHER_THING_JAR, new Date(url3.openConnection().getLastModified())); paths.put(NOT_A_JAR, null); context.checking(new Expectations() { { one(servletContext).getResourcePaths(WEB_INF_LIB_PATH); will(returnValue(paths.keySet())); one(servletContext).getResource(SOMETHING_JAR); will(returnValue(url1)); one(servletContext).getResource(SOMETHING_ELSE_JAR); will(returnValue(url2)); one(servletContext).getResource(ANOTHER_THING_JAR); will(returnValue(url3)); } }); final Map<URL, Date> output = new ModulesImpl(servletContext, null, new LoggerProvider()).getJarInformation(); assertThat(output.size(), is(3)); for (final URL url : output.keySet()) { final String jarName = url.toString(); final String key = WEB_INF_LIB_PATH + jarName.substring(jarName.lastIndexOf("/") + 1) + ".jar"; assertThat(output.get(url), is(paths.get(key))); } } |
11
| Code Sample 1:
private String sha1(String s) { String encrypt = s; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(s.getBytes()); byte[] digest = sha.digest(); final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { final byte b = digest[i]; final int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } encrypt = buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encrypt; }
Code Sample 2:
public String getDigest(String algorithm, String data) throws IOException, NoSuchAlgorithmException { MessageDigest md = java.security.MessageDigest.getInstance(algorithm); md.reset(); md.update(data.getBytes()); return md.digest().toString(); } |
11
| Code Sample 1:
protected static void copyDeleting(File source, File dest) throws ErrorCodeException { byte[] buf = new byte[8 * 1024]; FileInputStream in = null; try { in = new FileInputStream(source); try { FileOutputStream out = new FileOutputStream(dest); try { int count; while ((count = in.read(buf)) >= 0) out.write(buf, 0, count); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new ErrorCodeException(e); } }
Code Sample 2:
private void handleFile(File file, HttpServletRequest request, HttpServletResponse response) throws Exception { String filename = file.getName(); long filesize = file.length(); String mimeType = getMimeType(filename); response.setContentType(mimeType); if (filesize > getDownloadThreshhold()) { response.setHeader("Content-Disposition", "attachment; filename=" + filename); } response.setContentLength((int) filesize); ServletOutputStream out = response.getOutputStream(); IOUtils.copy(new FileInputStream(file), out); out.flush(); } |
00
| Code Sample 1:
public RobotList<Percentage> sort_incr_Percentage(RobotList<Percentage> list, String field) { int length = list.size(); Index_value[] distri = new Index_value[length]; for (int i = 0; i < length; i++) { distri[i] = new Index_value(i, list.get(i).percent); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (distri[i].value > distri[i + 1].value) { Index_value a = distri[i]; distri[i] = distri[i + 1]; distri[i + 1] = a; permut = true; } } } while (permut); RobotList<Percentage> sol = new RobotList<Percentage>(Percentage.class); for (int i = 0; i < length; i++) { sol.addLast(new Percentage(distri[i].value)); } return sol; }
Code Sample 2:
public void createResource(String resourceUri, boolean publish, User user) throws IOException { PermissionAPI perAPI = APILocator.getPermissionAPI(); Logger.debug(this.getClass(), "createResource"); resourceUri = stripMapping(resourceUri); String hostName = getHostname(resourceUri); String path = getPath(resourceUri); String folderName = getFolderName(path); String fileName = getFileName(path); fileName = deleteSpecialCharacter(fileName); if (fileName.startsWith(".")) { return; } Host host = HostFactory.getHostByHostName(hostName); Folder folder = FolderFactory.getFolderByPath(folderName, host); boolean hasPermission = perAPI.doesUserHavePermission(folder, PERMISSION_WRITE, user, false); if (hasPermission) { if (!checkFolderFilter(folder, fileName)) { throw new IOException("The file doesn't comply the folder's filter"); } if (host.getInode() != 0 && folder.getInode() != 0) { File file = new File(); file.setTitle(fileName); file.setFileName(fileName); file.setShowOnMenu(false); file.setLive(publish); file.setWorking(true); file.setDeleted(false); file.setLocked(false); file.setModDate(new Date()); String mimeType = FileFactory.getMimeType(fileName); file.setMimeType(mimeType); String author = user.getFullName(); file.setAuthor(author); file.setModUser(author); file.setSortOrder(0); file.setShowOnMenu(false); try { Identifier identifier = null; if (!isResource(resourceUri)) { WebAssetFactory.createAsset(file, user.getUserId(), folder, publish); identifier = IdentifierCache.getIdentifierFromIdentifierCache(file); } else { File actualFile = FileFactory.getFileByURI(path, host, false); identifier = IdentifierCache.getIdentifierFromIdentifierCache(actualFile); WebAssetFactory.createAsset(file, user.getUserId(), folder, identifier, false, false); WebAssetFactory.publishAsset(file); String assetsPath = FileFactory.getRealAssetsRootPath(); new java.io.File(assetsPath).mkdir(); java.io.File workingIOFile = FileFactory.getAssetIOFile(file); DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); vc.remove(ResourceManager.RESOURCE_TEMPLATE + workingIOFile.getPath()); if (file != null && file.getInode() > 0) { byte[] currentData = new byte[0]; FileInputStream is = new FileInputStream(workingIOFile); int size = is.available(); currentData = new byte[size]; is.read(currentData); java.io.File newVersionFile = FileFactory.getAssetIOFile(file); vc.remove(ResourceManager.RESOURCE_TEMPLATE + newVersionFile.getPath()); FileChannel channelTo = new FileOutputStream(newVersionFile).getChannel(); ByteBuffer currentDataBuffer = ByteBuffer.allocate(currentData.length); currentDataBuffer.put(currentData); currentDataBuffer.position(0); channelTo.write(currentDataBuffer); channelTo.force(false); channelTo.close(); } java.util.List<Tree> parentTrees = TreeFactory.getTreesByChild(file); for (Tree tree : parentTrees) { Tree newTree = TreeFactory.getTree(tree.getParent(), file.getInode()); if (newTree.getChild() == 0) { newTree.setParent(tree.getParent()); newTree.setChild(file.getInode()); newTree.setRelationType(tree.getRelationType()); newTree.setTreeOrder(0); TreeFactory.saveTree(newTree); } } } List<Permission> permissions = perAPI.getPermissions(folder); for (Permission permission : permissions) { Permission filePermission = new Permission(); filePermission.setPermission(permission.getPermission()); filePermission.setRoleId(permission.getRoleId()); filePermission.setInode(identifier.getInode()); perAPI.save(filePermission); } } catch (Exception ex) { Logger.debug(this, ex.toString()); } } } else { throw new IOException("You don't have access to add that folder/host"); } } |
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:
public void copyFile(File source, File destination, boolean lazy) { if (!source.exists()) { return; } if (lazy) { String oldContent = null; try { oldContent = read(source); } catch (Exception e) { return; } String newContent = null; try { newContent = read(destination); } catch (Exception e) { } if ((oldContent == null) || !oldContent.equals(newContent)) { copyFile(source, destination, false); } } else { 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) { _log.error(ioe.getMessage()); } } } |
11
| Code Sample 1:
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, Vector images) { int i; lengthOfTask = images.size(); Element dataBaseXML = new Element("dataBase"); for (i = 0; ((i < images.size()) && !stop && !cancel); i++) { Vector imagen = new Vector(2); imagen = (Vector) images.elementAt(i); String element = (String) imagen.elementAt(0); current = i; String pathSrc = System.getProperty("user.dir") + File.separator + "images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(File.separator) + 1, pathSrc.length()); String pathDst = directoryPath + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector<String> keyWords = new Vector<String>(); keyWords = TIGDataBase.asociatedConceptSearch(element); Element image = new Element("image"); image.setAttribute("name", name); if (keyWords.size() != 0) { for (int k = 0; k < keyWords.size(); k++) { Element category = new Element("category"); category.setText(keyWords.get(k).trim()); image.addContent(category); } } dataBaseXML.addContent(image); } Document doc = new Document(dataBaseXML); try { XMLOutputter out = new XMLOutputter(); FileOutputStream f = new FileOutputStream(directoryPath + "images.xml"); out.output(doc, f); f.flush(); f.close(); } catch (Exception e) { e.printStackTrace(); } current = lengthOfTask; }
Code Sample 2:
public File nextEntry() { try { while (hasNext()) { String name = waitingArchEntry.getName(); name = name.substring(name.indexOf("/") + 1); File file = new File(targetDir.getAbsolutePath() + "/" + name); if (waitingArchEntry.isDirectory()) { file.mkdirs(); waitingArchEntry = ais.getNextEntry(); } else { OutputStream os = new FileOutputStream(file); try { IOUtils.copy(ais, os); } finally { IOUtils.closeQuietly(os); } return file; } } } catch (IOException e) { return null; } return null; } |
11
| Code Sample 1:
private String digestMd5(final String password) { String base64; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); base64 = fr.cnes.sitools.util.Base64.encodeBytes(digest.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return "{MD5}" + base64; }
Code Sample 2:
public void initForEncryption() throws CryptographyException, IOException { String ownerPassword = pdDocument.getOwnerPasswordForEncryption(); String userPassword = pdDocument.getUserPasswordForEncryption(); if (ownerPassword == null) { ownerPassword = ""; } if (userPassword == null) { userPassword = ""; } PDStandardEncryption encParameters = (PDStandardEncryption) pdDocument.getEncryptionDictionary(); int permissionInt = encParameters.getPermissions(); int revision = encParameters.getRevision(); int length = encParameters.getLength() / 8; COSArray idArray = document.getDocumentID(); if (idArray == null || idArray.size() < 2) { idArray = new COSArray(); try { MessageDigest md = MessageDigest.getInstance("MD5"); BigInteger time = BigInteger.valueOf(System.currentTimeMillis()); md.update(time.toByteArray()); md.update(ownerPassword.getBytes()); md.update(userPassword.getBytes()); md.update(document.toString().getBytes()); byte[] id = md.digest(this.toString().getBytes()); COSString idString = new COSString(); idString.append(id); idArray.add(idString); idArray.add(idString); document.setDocumentID(idArray); } catch (NoSuchAlgorithmException e) { throw new CryptographyException(e); } } COSString id = (COSString) idArray.getObject(0); encryption = new PDFEncryption(); byte[] o = encryption.computeOwnerPassword(ownerPassword.getBytes("ISO-8859-1"), userPassword.getBytes("ISO-8859-1"), revision, length); byte[] u = encryption.computeUserPassword(userPassword.getBytes("ISO-8859-1"), o, permissionInt, id.getBytes(), revision, length); encryptionKey = encryption.computeEncryptedKey(userPassword.getBytes("ISO-8859-1"), o, permissionInt, id.getBytes(), revision, length); encParameters.setOwnerKey(o); encParameters.setUserKey(u); document.setEncryptionDictionary(encParameters.getCOSDictionary()); } |
00
| Code Sample 1:
public String getResponse(URL url) throws OAuthException { try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } catch (IOException e) { throw new OAuthException("Error getting HTTP response", e); } }
Code Sample 2:
public int addLocationInfo(int id, double lattitude, double longitude) { int ret = 0; Connection conn = null; PreparedStatement psmt = null; try { String sql = "insert into kddb.location_info (user_id, latitude, longitude) values(?, ?, ?)"; conn = getConnection(); psmt = conn.prepareStatement(sql); psmt.setInt(1, id); psmt.setDouble(2, lattitude); psmt.setDouble(3, longitude); ret = psmt.executeUpdate(); if (ret == 1) { conn.commit(); } else { conn.rollback(); } } catch (SQLException ex) { log.error("[addLocationInfo]", ex); } finally { endProsess(conn, psmt, null, null); } return ret; } |
11
| Code Sample 1:
public Object downloadFile(File destinationFile, URL[] urls, DownloadListener listener, Object checksum, long length, PRIORITY priority) throws DownloadException { URL url = urls[0]; if (!url.getProtocol().equalsIgnoreCase("http")) { throw new DownloadException(" Only HTTP is supported in this version "); } if (!destinationFile.exists()) { try { destinationFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); throw new DownloadException("Unable to download from URL : " + url.toString()); } } HeadMethod head = new HeadMethod(url.toString()); HttpClient httpClient = new HttpClient(); try { httpClient.executeMethod(head); Header[] headers = head.getResponseHeaders(); for (Header header : headers) { System.out.println(header); } Header header = head.getResponseHeader("Content-Length"); Object contentLength = header.getValue(); Long fileLength = Long.parseLong(contentLength.toString()); System.out.println(length + " : " + fileLength); GetMethod get = new GetMethod(url.toString()); httpClient.executeMethod(get); InputStream ins = get.getResponseBodyAsStream(); FileOutputStream fos = new FileOutputStream(destinationFile); IOUtils.copy(ins, fos); System.out.println(" DOWNLOADED FILE"); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
Code Sample 2:
public static void copyClassPathResource(String classPathResourceName, String fileSystemDirectoryName) { InputStream resourceInputStream = null; OutputStream fileOutputStream = null; try { resourceInputStream = FileUtils.class.getResourceAsStream(classPathResourceName); String fileName = StringUtils.substringAfterLast(classPathResourceName, "/"); File fileSystemDirectory = new File(fileSystemDirectoryName); fileSystemDirectory.mkdirs(); fileOutputStream = new FileOutputStream(fileSystemDirectoryName + "/" + fileName); IOUtils.copy(resourceInputStream, fileOutputStream); } catch (IOException e) { throw new UnitilsException(e); } finally { closeQuietly(resourceInputStream); closeQuietly(fileOutputStream); } } |
11
| Code Sample 1:
private static synchronized boolean doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { destFile = new File(destFile + FILE_SEPARATOR + srcFile.getName()); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } return destFile.exists(); }
Code Sample 2:
private static void zip(ZipOutputStream aOutputStream, final File[] aFiles, final String sArchive, final URI aRootURI, final String sFilter) throws FileError { boolean closeStream = false; if (aOutputStream == null) try { aOutputStream = new ZipOutputStream(new FileOutputStream(sArchive)); closeStream = true; } catch (final FileNotFoundException e) { throw new FileError("Can't create ODF file!", e); } try { try { for (final File curFile : aFiles) { aOutputStream.putNextEntry(new ZipEntry(URLDecoder.decode(aRootURI.relativize(curFile.toURI()).toASCIIString(), "UTF-8"))); if (curFile.isDirectory()) { aOutputStream.closeEntry(); FileUtils.zip(aOutputStream, FileUtils.getFiles(curFile, sFilter), sArchive, aRootURI, sFilter); continue; } final FileInputStream inputStream = new FileInputStream(curFile); for (int i; (i = inputStream.read(FileUtils.BUFFER)) != -1; ) aOutputStream.write(FileUtils.BUFFER, 0, i); inputStream.close(); aOutputStream.closeEntry(); } } finally { if (closeStream && aOutputStream != null) aOutputStream.close(); } } catch (final IOException e) { throw new FileError("Can't zip file to archive!", e); } if (closeStream) DocumentController.getStaticLogger().fine(aFiles.length + " files and folders zipped as " + sArchive); } |
11
| Code Sample 1:
public static void copyFile(File destFile, File src) throws IOException { File destDir = destFile.getParentFile(); File tempFile = new File(destFile + "_tmp"); destDir.mkdirs(); InputStream is = new FileInputStream(src); try { FileOutputStream os = new FileOutputStream(tempFile); try { byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); } finally { os.close(); } } finally { is.close(); } destFile.delete(); if (!tempFile.renameTo(destFile)) throw new IOException("Unable to rename " + tempFile + " to " + destFile); }
Code Sample 2:
public static void main(String[] args) throws Exception { if (args.length != 2) { PrintUtil.prt("arguments: sourcefile, destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); while (in.read(buff) != -1) { PrintUtil.prt("%%%"); buff.flip(); out.write(buff); buff.clear(); } } |
00
| Code Sample 1:
public String performRequest(TreeMap<String, String> params, boolean isAuthenticated) { params.put("format", "json"); try { URL url = new URL(getApiUrl(params, isAuthenticated)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); Reader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = ""; while (reader.ready()) { response += (char) reader.read(); } response = response.replaceFirst("jsonVimeoApi\\(", ""); response = response.substring(0, response.length() - 2); return response; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
Code Sample 2:
public Void doInBackground() { Transferable clipData = clipboard.getContents(this); File file = new File("Videos/" + (mp3.getArtist() + " - " + mp3.getTitle() + ".jpg").replace("/", "").replace("\\", "")); try { String test = (String) (clipData.getTransferData(DataFlavor.stringFlavor)); String testje = test.toLowerCase(); if (testje.indexOf(".flv") > 0 || testje.indexOf(".wmv") > 0 || testje.indexOf(".mpg") > 0 || testje.indexOf(".mpeg") > 0 || testje.indexOf(".avi") > 0 || testje.indexOf(".avi") > 0 || testje.indexOf(".divx") > 0 || testje.indexOf(".avi") > 0) { URL url = new URL(test); (new File("Videos/")).mkdirs(); System.out.println("Saving video to " + file); try { URLConnection urlC = url.openConnection(); InputStream is = url.openStream(); System.out.flush(); FileOutputStream fos = null; fos = new FileOutputStream(file); byte[] buf = new byte[32768]; int len; while ((len = is.read(buf)) > 0) { fos.write(buf, 0, len); } is.close(); fos.close(); } catch (Exception e) { System.out.println("Error saving video from url: " + url); mp3.setVideo(file.getAbsolutePath()); } } } catch (Exception ex) { System.out.println("not a valid video file"); ex.printStackTrace(); } return null; } |
11
| Code Sample 1:
private static void copyObjects(File[] source, String target) { for (int i = 0; i < source.length; i++) { try { File inputFile = source[i]; File outputFile = new File(target + source[i].getName()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { Logger.error(ex.getClass() + " " + ex.getMessage()); for (int j = 0; j < ex.getStackTrace().length; j++) Logger.error(" " + ex.getStackTrace()[j].toString()); ex.printStackTrace(); } } }
Code Sample 2:
public void run() { FileInputStream src; FileOutputStream dest; try { src = new FileInputStream(srcName); dest = new FileOutputStream(destName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileChannel srcC = src.getChannel(); FileChannel destC = dest.getChannel(); ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE); try { int i; System.out.println(srcC.size()); while ((i = srcC.read(buf)) > 0) { System.out.println(buf.getChar(2)); buf.flip(); destC.write(buf); buf.compact(); } destC.close(); dest.close(); } catch (IOException e1) { e1.printStackTrace(); return; } } |
00
| Code Sample 1:
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { int remainingWorkUnits = 10; monitor.beginTask("New Modulo Project Creation", remainingWorkUnits); IWorkspace ws = ResourcesPlugin.getWorkspace(); newProject = fMainPage.getProjectHandle(); IProjectDescription description = ws.newProjectDescription(newProject.getName()); String[] natures = { JavaCore.NATURE_ID, ModuloLauncherPlugin.NATURE_ID }; description.setNatureIds(natures); ICommand command = description.newCommand(); command.setBuilderName(JavaCore.BUILDER_ID); ICommand[] commands = { command }; description.setBuildSpec(commands); IJavaProject jproject = JavaCore.create(newProject); ModuloProject modProj = new ModuloProject(); modProj.setJavaProject(jproject); try { newProject.create(description, new SubProgressMonitor(monitor, 1)); newProject.open(new SubProgressMonitor(monitor, 1)); IFolder srcFolder = newProject.getFolder("src"); IFolder javaFolder = srcFolder.getFolder("java"); IFolder buildFolder = newProject.getFolder("build"); IFolder classesFolder = buildFolder.getFolder("classes"); modProj.createFolder(srcFolder); modProj.createFolder(javaFolder); modProj.createFolder(buildFolder); modProj.createFolder(classesFolder); IPath buildPath = newProject.getFolder("build/classes").getFullPath(); jproject.setOutputLocation(buildPath, new SubProgressMonitor(monitor, 1)); IClasspathEntry[] entries = new IClasspathEntry[] { JavaCore.newSourceEntry(newProject.getFolder("src/java").getFullPath()), JavaCore.newContainerEntry(new Path(JavaRuntime.JRE_CONTAINER)), JavaCore.newContainerEntry(new Path(ModuloClasspathContainer.CONTAINER_ID)) }; jproject.setRawClasspath(entries, new SubProgressMonitor(monitor, 1)); ModuleDefinition definition = new ModuleDefinition(); definition.setId(fModuloPage.getPackageName()); definition.setVersion(new VersionNumber(1, 0, 0)); definition.setMetaName(fModuloPage.getModuleName()); definition.setMetaDescription("The " + fModuloPage.getModuleName() + " Module."); definition.setModuleClassName(fModuloPage.getPackageName() + "." + fModuloPage.getModuleClassName()); if (fModuloPage.isConfigSelectioned()) definition.setConfigurationClassName(fModuloPage.getPackageName() + "." + fModuloPage.getConfigClassName()); if (fModuloPage.isStatSelectioned()) definition.setStatisticsClassName(fModuloPage.getPackageName() + "." + fModuloPage.getStatClassName()); modProj.setDefinition(definition); modProj.createPackage(); modProj.createModuleXML(); modProj.createMainClass(); if (fModuloPage.isConfigSelectioned()) modProj.createConfigClass(); if (fModuloPage.isStatSelectioned()) modProj.createStatClass(); modProj.createModuleProperties(); modProj.createMessagesProperties(); IFolder binFolder = newProject.getFolder("bin"); binFolder.delete(true, new SubProgressMonitor(monitor, 1)); } catch (CoreException e) { e.printStackTrace(); } finally { monitor.done(); } }
Code Sample 2:
@Override protected String getRawPage(String url) throws IOException { HttpClient httpClient = new HttpClient(); String proxyHost = config.getString("proxy.host"), proxyPortString = config.getString("proxy.port"); if (proxyHost != null && proxyPortString != null) { int proxyPort = -1; try { proxyPort = Integer.parseInt(proxyPortString); } catch (NumberFormatException e) { } if (proxyPort != -1) { httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort); } } GetMethod urlGet = new GetMethod(url); urlGet.setRequestHeader("Accept-Encoding", ""); urlGet.setRequestHeader("User-Agent", "Mozilla/5.0"); int retCode; if ((retCode = httpClient.executeMethod(urlGet)) != HttpStatus.SC_OK) { throw new RuntimeException("Unexpected HTTP code: " + retCode); } String encoding = null; Header contentType = urlGet.getResponseHeader("Content-Type"); if (contentType != null) { String contentTypeString = contentType.toString(); int i = contentTypeString.indexOf("charset="); if (i != -1) { encoding = contentTypeString.substring(i + "charset=".length()).trim(); } } boolean gzipped = false; Header contentEncoding = urlGet.getResponseHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { gzipped = true; } byte[] htmlData; try { InputStream in = gzipped ? new GZIPInputStream(urlGet.getResponseBodyAsStream()) : urlGet.getResponseBodyAsStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); htmlData = out.toByteArray(); in.close(); } finally { urlGet.releaseConnection(); } if (encoding == null) { Matcher m = Pattern.compile("(?i)<meta[^>]*charset=(([^\"]+\")|(\"[^\"]+\"))").matcher(new String(htmlData)); if (m.find()) { encoding = m.group(1).trim().replace("\"", ""); } } if (encoding == null) { encoding = "UTF-8"; } return new String(htmlData, encoding); } |
00
| Code Sample 1:
public boolean config(URL url, boolean throwsException) throws IllegalArgumentException { try { final MetaRoot conf = UjoManagerXML.getInstance().parseXML(new BufferedInputStream(url.openStream()), MetaRoot.class, this); config(conf); return true; } catch (Exception e) { if (throwsException) { throw new IllegalArgumentException("Configuration file is not valid ", e); } else { return false; } } }
Code Sample 2:
public void download(String target) { try { if (url == null) return; conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "Internet Explorer"); conn.setReadTimeout(10000); conn.connect(); httpReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); java.io.BufferedWriter out = new BufferedWriter(new FileWriter(target, false)); String str = httpReader.readLine(); while (str != null) { out.write(str); str = httpReader.readLine(); } out.close(); System.out.println("file download successfully: " + url.getHost() + url.getPath()); System.out.println("saved to: " + target); } catch (Exception e) { System.out.println("file download failed: " + url.getHost() + url.getPath()); e.printStackTrace(); } } |
11
| Code Sample 1:
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
Code Sample 2:
private int create() throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; String query = null; try { conn = dataSource.getConnection(); st = conn.createStatement(); query = "insert into " + DB.Tbl.users + "(" + col.name + "," + col.login + "," + col.pass + "," + col.passHash + "," + col.email + "," + col.role + "," + col.addDate + ") values('" + name + "','" + login + "','" + pass + "','" + pass.hashCode() + "','" + email + "'," + role + ",now())"; st.executeUpdate(query, new String[] { col.id }); rs = st.getGeneratedKeys(); while (rs.next()) { int genId = rs.getInt(1); conn.commit(); return genId; } throw new SQLException("ะะต ัะดะฐะตััั ะฟะพะปััะธัั generatedKey ะฟัะธ ัะพะทะดะฐะฝะธะธ ะฟะพะปัะทะพะฒะฐัะตะปั."); } catch (SQLException e) { try { conn.rollback(); } catch (Exception e1) { } throw e; } finally { try { rs.close(); } catch (Exception e) { } try { st.close(); } catch (Exception e) { } try { conn.close(); } catch (Exception e) { } } } |
00
| Code Sample 1:
public static void bubbleSort(int[] a) { if (a == null) { throw new IllegalArgumentException("Null-pointed array"); } int right = a.length - 1; int k = 0; while (right > 0) { k = 0; for (int i = 0; i <= right - 1; i++) { if (a[i] > a[i + 1]) { k = i; int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } right = k; } }
Code Sample 2:
String[] openUrlAsList(String address) { IJ.showStatus("Connecting to " + IJ.URL); Vector v = new Vector(); try { URL url = new URL(address); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; while (true) { line = br.readLine(); if (line == null) break; if (!line.equals("")) v.addElement(line); } br.close(); } catch (Exception e) { } String[] lines = new String[v.size()]; v.copyInto((String[]) lines); IJ.showStatus(""); return lines; } |
00
| Code Sample 1:
public InputStream getInputStream(IProgressMonitor monitor) throws IOException, CoreException { if (in == null && url != null) { if (connection == null) connection = url.openConnection(); if (monitor != null) { this.in = openStreamWithCancel(connection, monitor); } else { this.in = connection.getInputStream(); } if (in != null) { this.lastModified = connection.getLastModified(); } } return in; }
Code Sample 2:
public static HttpURLConnection getHttpConn(String urlStr, String Method) throws IOException { URL url = null; HttpURLConnection connection = null; url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod(Method); connection.setUseCaches(false); connection.connect(); return connection; } |
00
| Code Sample 1:
public static String callApi(String api, String paramname, String paramvalue) { String loginapp = SSOFilter.getLoginapp(); String u = SSOUtil.addParameter(loginapp + "/api/" + api, paramname, paramvalue); u = SSOUtil.addParameter(u, "servicekey", SSOFilter.getServicekey()); String response = "error"; try { URL url = new URL(u); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response = line.trim(); } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } if ("error".equals(response)) { return "error"; } else { return response; } }
Code Sample 2:
public void compressImage(InputStream input, OutputStream output, DjatokaEncodeParam params) throws DjatokaException { if (params == null) params = new DjatokaEncodeParam(); File inputFile = null; try { inputFile = File.createTempFile("tmp", ".tif"); IOUtils.copyStream(input, new FileOutputStream(inputFile)); if (params.getLevels() == 0) { ImageRecord dim = ImageRecordUtils.getImageDimensions(inputFile.getAbsolutePath()); params.setLevels(ImageProcessingUtils.getLevelCount(dim.getWidth(), dim.getHeight())); dim = null; } } catch (IOException e1) { logger.error("Unexpected file format; expecting uncompressed TIFF", e1); throw new DjatokaException("Unexpected file format; expecting uncompressed TIFF"); } String out = STDOUT; File winOut = null; if (isWindows) { try { winOut = File.createTempFile("pipe_", ".jp2"); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } out = winOut.getAbsolutePath(); } String command = getKduCompressCommand(inputFile.getAbsolutePath(), out, params); logger.debug("compressCommand: " + command); Runtime rt = Runtime.getRuntime(); try { final Process process = rt.exec(command, envParams, new File(env)); if (out.equals(STDOUT)) { IOUtils.copyStream(process.getInputStream(), output); } else if (isWindows) { FileInputStream fis = new FileInputStream(out); IOUtils.copyStream(fis, output); fis.close(); } process.waitFor(); if (process != null) { String errorCheck = null; try { errorCheck = new String(IOUtils.getByteArray(process.getErrorStream())); } catch (Exception e1) { logger.error(e1, e1); } process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); process.destroy(); if (errorCheck != null) throw new DjatokaException(errorCheck); } } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } catch (InterruptedException e) { logger.error(e, e); throw new DjatokaException(e); } if (inputFile != null) inputFile.delete(); if (winOut != null) winOut.delete(); } |
00
| Code Sample 1:
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); }
Code Sample 2:
public static String upload(File tmpFile, URL url) throws IOException { StringBuffer reply = new StringBuffer(); URLConnection uc = url.openConnection(); ClientHttpRequest request = new ClientHttpRequest(uc); String file = "file"; String filename = tmpFile.getName(); InputStream fileinput = new FileInputStream(tmpFile); request.setParameter(file, filename, fileinput); InputStream serverInput = request.post(); BufferedReader in = new BufferedReader(new InputStreamReader(serverInput)); String line = in.readLine(); while (line != null) { reply.append(line + "\n"); line = in.readLine(); } in.close(); return reply.toString(); } |
11
| Code Sample 1:
private void initUserExtensions(SeleniumConfiguration seleniumConfiguration) throws IOException { StringBuilder contents = new StringBuilder(); StringOutputStream s = new StringOutputStream(); IOUtils.copy(SeleniumConfiguration.class.getResourceAsStream("default-user-extensions.js"), s); contents.append(s.toString()); File providedUserExtensions = seleniumConfiguration.getFile(ConfigurationPropertyKeys.SELENIUM_USER_EXTENSIONS, seleniumConfiguration.getDirectoryConfiguration().getInput(), false); if (providedUserExtensions != null) { contents.append(FileUtils.readFileToString(providedUserExtensions, null)); } seleniumUserExtensions = new File(seleniumConfiguration.getDirectoryConfiguration().getInput(), "user-extensions.js"); FileUtils.forceMkdir(seleniumUserExtensions.getParentFile()); FileUtils.writeStringToFile(seleniumUserExtensions, contents.toString(), null); }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } |
11
| Code Sample 1:
private void detachFile(File file, Block b) throws IOException { File tmpFile = volume.createDetachFile(b, file.getName()); try { IOUtils.copyBytes(new FileInputStream(file), new FileOutputStream(tmpFile), 16 * 1024, true); if (file.length() != tmpFile.length()) { throw new IOException("Copy of file " + file + " size " + file.length() + " into file " + tmpFile + " resulted in a size of " + tmpFile.length()); } FileUtil.replaceFile(tmpFile, file); } catch (IOException e) { boolean done = tmpFile.delete(); if (!done) { DataNode.LOG.info("detachFile failed to delete temporary file " + tmpFile); } throw e; } }
Code Sample 2:
public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } |
11
| Code Sample 1:
public static void loadConfig(DeviceEntry defaultDevice, EmulatorContext emulatorContext) { Config.defaultDevice = defaultDevice; Config.emulatorContext = emulatorContext; File configFile = new File(getConfigPath(), "config2.xml"); try { if (configFile.exists()) { loadConfigFile("config2.xml"); } else { configFile = new File(getConfigPath(), "config.xml"); if (configFile.exists()) { loadConfigFile("config.xml"); for (Enumeration e = getDeviceEntries().elements(); e.hasMoreElements(); ) { DeviceEntry entry = (DeviceEntry) e.nextElement(); if (!entry.canRemove()) { continue; } removeDeviceEntry(entry); File src = new File(getConfigPath(), entry.getFileName()); File dst = File.createTempFile("dev", ".jar", getConfigPath()); IOUtils.copyFile(src, dst); entry.setFileName(dst.getName()); addDeviceEntry(entry); } } else { createDefaultConfigXml(); } saveConfig(); } } catch (IOException ex) { Logger.error(ex); createDefaultConfigXml(); } finally { if (configXml == null) { createDefaultConfigXml(); } } urlsMRU.read(configXml.getChildOrNew("files").getChildOrNew("recent")); initSystemProperties(); }
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:
public static String getHash(String input) { MessageDigest m; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } m.update(input.getBytes(), 0, input.length()); return new BigInteger(1, m.digest()).toString(16); }
Code Sample 2:
public static void encryptFile(String input, String output, String pwd) throws Exception { CipherOutputStream out; InputStream in; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.ENCRYPT_MODE, key); in = new FileInputStream(input); out = new CipherOutputStream(new FileOutputStream(output), cipher); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); } |
00
| Code Sample 1:
public <E extends Exception> void doWithConnection(String httpAddress, ICallableWithParameter<Void, URLConnection, E> toDo) throws E, ConnectionException { URLConnection connection; try { URL url = new URL(httpAddress); connection = url.openConnection(); } catch (MalformedURLException e) { throw new ConnectionException("Connecting to " + httpAddress + " got", e); } catch (IOException e) { throw new ConnectionException("Connecting to " + httpAddress + " got", e); } authenticationHandler.doWithProxyAuthentication(connection, toDo); }
Code Sample 2:
public void test() throws Exception { TranslationResponseStorage r = new TranslationResponseStorage(mockStorage, "UTF-8"); MockResponseStateObserver observer = new MockResponseStateObserver(); r.addStateObserver(observer); assertEquals("UTF-8", r.getCharacterEncoding()); assertEquals(-1L, r.getLastModified()); assertEquals(0, r.getTranslationCount()); r.setTranslationCount(10); assertEquals(10, r.getTranslationCount()); assertNotNull(r.getHeadersStorage()); assertNull(r.getHeaders()); r.setLastModified(100000L); assertEquals(100000L, r.getLastModified()); assertFalse(r.getHeaders().isEmpty()); { Set<ResponseHeader> set = new TreeSet<ResponseHeader>(); set.add(new ResponseHeaderImpl("Last-Modified", new String[] { DateUtil.formatDate(new Date(200000L)) })); r.addHeaders(set); } assertEquals(1, r.getHeaders().size()); assertEquals(200000L, r.getLastModified()); { Set<ResponseHeader> set = new TreeSet<ResponseHeader>(); set.add(new ResponseHeaderImpl("Last-Modified", new String[] { DateUtil.formatDate(new Date(310000L)) })); set.add(new ResponseHeaderImpl("User-Agent", new String[] { "Pinoccio" })); r.addHeaders(set); } assertEquals(2, r.getHeaders().size()); int ii = 0; for (ResponseHeader h : r.getHeaders()) { ii++; if (ii == 1) { assertEquals("Last-Modified", h.getName()); assertEquals(Arrays.toString(new String[] { DateUtil.formatDate(new Date(310000L)) }), Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("User-Agent", h.getName()); assertEquals(Arrays.toString(new String[] { "Pinoccio" }), Arrays.toString(h.getValues())); } } r.addText("This is an example"); r.addText(" and another one."); assertEquals("This is an example and another one.", mockStorage.getText()); InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); { OutputStream output = r.getOutputStream(); output.write(" and another line".getBytes("UTF-8")); assertEquals("This is an example and another one. and another line", r.getText()); } { Writer output = r.getWriter(); output.write(" and write some more"); assertEquals("This is an example and another one. and another line and write some more", r.getText()); } assertFalse(r.hasEnded()); assertNull(r.getEndState()); assertEquals(0L, observer.getHits()); r.setEndState(ResponseStateOk.getInstance()); assertEquals(ResponseStateOk.getInstance(), r.getEndState()); assertTrue(r.hasEnded()); assertEquals(1L, observer.getHits()); try { r.getOutputStream(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } try { r.getWriter(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } } |
11
| Code Sample 1:
public String downloadToSdCard(String localFileName, String suffixFromHeader, String extension) { InputStream in = null; FileOutputStream fos = null; String absolutePath = null; try { Log.i(TAG, "Opening URL: " + url); StreamAndHeader inAndHeader = HTTPUtils.openWithHeader(url, suffixFromHeader); if (inAndHeader == null || inAndHeader.mStream == null) { return null; } in = inAndHeader.mStream; String sdcardpath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath(); String headerValue = suffixFromHeader == null || inAndHeader.mHeaderValue == null ? "" : inAndHeader.mHeaderValue; headerValue = headerValue.replaceAll("[-:]*\\s*", ""); String filename = sdcardpath + "/" + localFileName + headerValue + (extension == null ? "" : extension); mSize = in.available(); Log.i(TAG, "Downloading " + filename + ", size: " + mSize); fos = new FileOutputStream(new File(filename)); int buffersize = 1024; byte[] buffer = new byte[buffersize]; int readsize = buffersize; mCount = 0; while (readsize != -1) { readsize = in.read(buffer, 0, buffersize); if (readsize > 0) { Log.i(TAG, "Read " + readsize + " bytes..."); fos.write(buffer, 0, readsize); mCount += readsize; } } fos.flush(); fos.close(); FileInputStream controlIn = new FileInputStream(filename); mSavedSize = controlIn.available(); Log.v(TAG, "saved size: " + mSavedSize); mAbsolutePath = filename; done(); } catch (Exception e) { Log.e(TAG, "LoadingWorker.run", e); } finally { HTTPUtils.close(in); } return mAbsolutePath; }
Code Sample 2:
private void process(String zipFileName, String directory, String db) throws SQLException { InputStream in = null; try { if (!FileUtils.exists(zipFileName)) { throw new IOException("File not found: " + zipFileName); } String originalDbName = null; int originalDbLen = 0; if (db != null) { originalDbName = getOriginalDbName(zipFileName, db); if (originalDbName == null) { throw new IOException("No database named " + db + " found"); } if (originalDbName.startsWith(File.separator)) { originalDbName = originalDbName.substring(1); } originalDbLen = originalDbName.length(); } in = FileUtils.openFileInputStream(zipFileName); ZipInputStream zipIn = new ZipInputStream(in); while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { break; } String fileName = entry.getName(); fileName = fileName.replace('\\', File.separatorChar); fileName = fileName.replace('/', File.separatorChar); if (fileName.startsWith(File.separator)) { fileName = fileName.substring(1); } boolean copy = false; if (db == null) { copy = true; } else if (fileName.startsWith(originalDbName + ".")) { fileName = db + fileName.substring(originalDbLen); copy = true; } if (copy) { OutputStream out = null; try { out = FileUtils.openFileOutputStream(directory + File.separator + fileName, false); IOUtils.copy(zipIn, out); out.close(); } finally { IOUtils.closeSilently(out); } } zipIn.closeEntry(); } zipIn.closeEntry(); zipIn.close(); } catch (IOException e) { throw Message.convertIOException(e, zipFileName); } finally { IOUtils.closeSilently(in); } } |
11
| Code Sample 1:
public static boolean copyFile(final File src, final File dest, long extent, final boolean overwrite) throws FileNotFoundException, IOException { boolean result = false; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Copying file " + src + " to " + dest + " extent " + extent + " exists " + dest.exists()); } if (dest.exists()) { if (overwrite) { dest.delete(); LOGGER.finer(dest.getAbsolutePath() + " removed before copy."); } else { return result; } } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); if (extent < 0) { extent = fcin.size(); } long trans = fcin.transferTo(0, extent, fcout); if (trans < extent) { result = false; } result = true; } catch (IOException e) { String message = "Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " with extent " + extent + " got IOE: " + e.getMessage(); if (e.getMessage().equals("Invalid argument")) { LOGGER.severe("Failed copy, trying workaround: " + message); workaroundCopyFile(src, dest); } else { IOException newE = new IOException(message); newE.setStackTrace(e.getStackTrace()); throw newE; } } finally { if (fcin != null) { fcin.close(); } if (fcout != null) { fcout.close(); } if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } } return result; }
Code Sample 2:
public static void copyFile(File sourceFile, File destinationFile) throws IOException { if (!destinationFile.exists()) { destinationFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } |
00
| Code Sample 1:
public static String SHA1(String text) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } StringBuffer hexString = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
Code Sample 2:
public void sendResponse(DjdocRequest req, HttpServletResponse res) throws IOException { File file = (File) req.getResult(); InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) { in.close(); } } } |
11
| Code Sample 1:
public boolean crear() { int result = 0; String sql = "insert into torneo" + "(nombreTorneo, ciudad, fechaInicio, fechaFinal, organizador, numeroDivisiones, terminado)" + "values (?, ?, ?, ?, ?, ?, ?)"; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement(eltorneo); result = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (result > 0); }
Code Sample 2:
public void store(Component component, String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("UPDATE component_prop " + "SET size_height = ?, size_width = ?, pos_x = ?, pos_y = ? " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); Point point = component.getLocation(); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); int update = psta.executeUpdate(); if (update == 0) { psta = jdbc.prepareStatement("INSERT INTO component_prop " + "(size_height, size_width, pos_x, pos_y, pilot_id, component_name) " + "VALUES (?,?,?,?,?,?)"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); psta.executeUpdate(); } jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } } |
00
| Code Sample 1:
@Override public void execute(JobExecutionContext context) throws JobExecutionException { super.execute(context); debug("Start execute job " + this.getClass().getName()); try { String name = "nixspam-ip.dump.gz"; String f = this.path_app_root + "/" + this.properties.get("dir") + "/"; try { org.apache.commons.io.FileUtils.forceMkdir(new File(f)); } catch (IOException ex) { fatal("IOException", ex); } f += "/" + name; String url = "http://www.dnsbl.manitu.net/download/" + name; debug("(1) - start download: " + url); com.utils.HttpUtil.downloadData(url, f); com.utils.IOUtil.unzip(f, f.replace(".gz", "")); File file_to_read = new File(f.replaceAll(".gz", "")); BigFile lines = null; try { lines = new BigFile(file_to_read.toString()); } catch (Exception e) { fatal("Excpetion", e); return; } try { Statement stat = conn_url.createStatement(); stat.executeUpdate(properties.get("query_delete")); stat.close(); } catch (SQLException e) { fatal("SQLException", e); } try { conn_url.setAutoCommit(false); } catch (SQLException e) { fatal("SQLException", e); } boolean ok = true; int i = 0; for (String line : lines) { if (StringUtil.isEmpty(line) || line.indexOf(" ") == -1) { continue; } try { line = line.substring(line.indexOf(" ")); line = line.trim(); if (getIPException(line)) { continue; } Statement stat = this.conn_url.createStatement(); stat.executeUpdate("insert into blacklist(url) values('" + line + "')"); stat.close(); i++; } catch (SQLException e) { fatal("SQLException", e); try { conn_url.rollback(); } catch (SQLException ex) { fatal("SQLException", ex); } ok = false; break; } } boolean del = file_to_read.delete(); debug("File " + file_to_read + " del:" + del); name = "spam-ip.com_" + DateTimeUtil.getNowWithFormat("MM-dd-yyyy") + ".csv"; f = this.path_app_root + "/" + this.properties.get("dir") + "/"; org.apache.commons.io.FileUtils.forceMkdir(new File(f)); f += "/" + name; url = "http://spam-ip.com/csv_dump/" + name; debug("(2) - start download: " + url); com.utils.HttpUtil.downloadData(url, f); file_to_read = new File(f); try { lines = new BigFile(file_to_read.toString()); } catch (Exception e) { fatal("Exception", e); return; } try { conn_url.setAutoCommit(false); } catch (SQLException e) { fatal("SQLException", e); } ok = true; for (String line : lines) { if (StringUtil.isEmpty(line) || line.indexOf(" ") == -1) { continue; } try { line = line.split(",")[1]; line = line.trim(); if (getIPException(line)) { continue; } Statement stat = this.conn_url.createStatement(); stat.executeUpdate("insert into blacklist(url) values('" + line + "')"); stat.close(); i++; } catch (SQLException e) { fatal("SQLException", e); try { conn_url.rollback(); } catch (SQLException ex) { fatal("SQLException", ex); } ok = false; break; } } del = file_to_read.delete(); debug("File " + file_to_read + " del:" + del); if (ok) { debug("Import della BlackList Concluso tot righe: " + i); try { conn_url.commit(); } catch (SQLException e) { fatal("SQLException", e); } } else { fatal("Problemi con la Blacklist"); } try { conn_url.setAutoCommit(true); } catch (SQLException e) { fatal("SQLException", e); } try { Statement stat = this.conn_url.createStatement(); stat.executeUpdate("VACUUM"); stat.close(); } catch (SQLException e) { fatal("SQLException", e); } } catch (IOException ex) { fatal("IOException", ex); } debug("End execute job " + this.getClass().getName()); }
Code Sample 2:
public void add(final String name, final String content) { forBundle(new BundleManipulator() { public boolean includeEntry(String entryName) { return !name.equals(entryName); } public void finish(Bundle bundle, ZipOutputStream zout) throws IOException { zout.putNextEntry(new ZipEntry(name)); IOUtils.copy(new StringReader(content), zout, "UTF-8"); } }); } |
11
| Code Sample 1:
private void handleFile(File file, HttpServletRequest request, HttpServletResponse response) throws Exception { String filename = file.getName(); long filesize = file.length(); String mimeType = getMimeType(filename); response.setContentType(mimeType); if (filesize > getDownloadThreshhold()) { response.setHeader("Content-Disposition", "attachment; filename=" + filename); } response.setContentLength((int) filesize); ServletOutputStream out = response.getOutputStream(); IOUtils.copy(new FileInputStream(file), out); out.flush(); }
Code Sample 2:
@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:
private HttpURLConnection prepare(URL url, String method) { if (this.username != null && this.password != null) { this.headers.put("Authorization", "Basic " + Codec.encodeBASE64(this.username + ":" + this.password)); } try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); checkFileBody(connection); connection.setRequestMethod(method); for (String key : this.headers.keySet()) { connection.setRequestProperty(key, headers.get(key)); } return connection; } catch (Exception e) { throw new RuntimeException(e); } }
Code Sample 2:
private static void discoverRegisteryEntries(DataSourceRegistry registry) { try { Enumeration<URL> urls = DataSetURL.class.getClassLoader().getResources("META-INF/org.virbo.datasource.DataSourceFactory.extensions"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine().trim(); while (s != null) { if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerExtension(ss[0], ss[i], null); } } s = reader.readLine(); } reader.close(); } urls = DataSetURL.class.getClassLoader().getResources("META-INF/org.virbo.datasource.DataSourceFactory.mimeTypes"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine().trim(); while (s != null) { if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerMimeType(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } urls = DataSetURL.class.getClassLoader().getResources("META-INF/org.virbo.datasource.DataSourceFormat.extensions"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine().trim(); while (s != null) { if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerFormatter(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } } catch (IOException e) { e.printStackTrace(); } } |
00
| Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
private void startOpening(final URL url) { final WebAccessor wa = this; openerThread = new Thread() { public void run() { iStream = null; try { tryProxy = false; URLConnection connection = url.openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection htc = (HttpURLConnection) connection; contentLength = htc.getContentLength(); } InputStream i = connection.getInputStream(); iStream = new LoggedInputStream(i, wa); } catch (ConnectException x) { tryProxy = true; exception = x; } catch (Exception x) { exception = x; } finally { if (dialog != null) { Thread.yield(); dialog.setVisible(false); } } } }; openerThread.start(); } |
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: </th><td>1234") > 0); }
Code Sample 2:
public static boolean update(Cargo cargo) { int result = 0; Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); String sql = "update cargo set nome = (?) where id_cargo= ?"; pst = c.prepareStatement(sql); pst.setString(1, cargo.getNome()); pst.setInt(2, cargo.getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (SQLException e) { try { c.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } System.out.println("[CargoDAO.update] Erro ao atualizar -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } } |
00
| Code Sample 1:
public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
Code Sample 2:
public static InputStream getRemoteIS(URL url, String post) throws ArcImsException { InputStream lector = null; try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-length", "" + post.length()); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(post); wr.flush(); logger.info("downloading '" + url.toString()); lector = conn.getInputStream(); } catch (ConnectException e) { logger.error("Timed out error", e); throw new ArcImsException("arcims_server_timeout"); } catch (ProtocolException e) { logger.error(e.getMessage(), e); throw new ArcImsException("arcims_server_error"); } catch (IOException e) { logger.error(e.getMessage(), e); throw new ArcImsException("arcims_server_error"); } return lector; } |
00
| Code Sample 1:
public static void copy(File source, File dest) throws java.io.IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
Code Sample 2:
private String generaHashMD5(String plainText) throws Exception { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(plainText.getBytes(FirmaUtil.CHARSET)); byte[] digest = mdAlgorithm.digest(); return toHex(digest); } |
00
| Code Sample 1:
public void registerSchema(String newSchemaName, String objectControlller, long boui, String expression, String schema) throws SQLException { Connection cndef = null; PreparedStatement pstm = null; try { cndef = this.getRepositoryConnection(p_ctx.getApplication(), "default", 2); String friendlyName = MessageLocalizer.getMessage("SCHEMA_CREATED_BY_OBJECT") + " [" + objectControlller + "] " + MessageLocalizer.getMessage("WITH_BOUI") + " [" + boui + "]"; pstm = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? and objecttype='S'"); pstm.setString(1, newSchemaName); pstm.executeUpdate(); pstm.close(); pstm = cndef.prepareStatement("INSERT INTO NGTDIC (SCHEMA,OBJECTNAME,OBJECTTYPE,TABLENAME, " + "FRIENDLYNAME, EXPRESSION) VALUES (" + "?,?,?,?,?,?)"); pstm.setString(1, schema); pstm.setString(2, newSchemaName); pstm.setString(3, "S"); pstm.setString(4, newSchemaName); pstm.setString(5, friendlyName); pstm.setString(6, expression); pstm.executeUpdate(); pstm.close(); cndef.commit(); } catch (Exception e) { cndef.rollback(); e.printStackTrace(); throw new SQLException(e.getMessage()); } finally { if (pstm != null) { try { pstm.close(); } catch (Exception e) { } } } }
Code Sample 2:
public static IEntity readFromFile(File resourceName) { InputStream inputStream = null; try { URL urlResource = ModelLoader.solveResource(resourceName.getPath()); if (urlResource != null) { inputStream = urlResource.openStream(); return (IEntity) new ObjectInputStream(inputStream).readObject(); } } catch (IOException e) { } catch (ClassNotFoundException e) { } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException e) { } } return null; } |
00
| Code Sample 1:
public static void readAsFile(String fileName, String url) { BufferedInputStream in = null; BufferedOutputStream out = null; URLConnection conn = null; try { conn = new URL(url).openConnection(); conn.setDoInput(true); in = new BufferedInputStream(conn.getInputStream()); out = new BufferedOutputStream(new FileOutputStream(fileName)); int b; while ((b = in.read()) != -1) { out.write(b); } } catch (Exception ex) { log.error(ex.getMessage(), ex); } finally { if (null != in) { try { in.close(); } catch (IOException e) { } } if (null != out) { try { out.flush(); out.close(); } catch (IOException e) { } } } }
Code Sample 2:
public static void writeFromURL(String urlstr, String filename) throws Exception { URL url = new URL(urlstr); InputStream in = url.openStream(); BufferedReader bf = null; StringBuffer sb = new StringBuffer(); try { bf = new BufferedReader(new InputStreamReader(in, "latin1")); String s; while (true) { s = bf.readLine(); if (s != null) { sb.append(s); } else { break; } } } catch (Exception e) { throw e; } finally { bf.close(); } writeRawBytes(sb.toString(), filename); } |
11
| Code Sample 1:
private void javaToHtml(File source, File destination) throws IOException { Reader reader = new FileReader(source); Writer writer = new FileWriter(destination); JavaUtils.writeJava(reader, writer); writer.flush(); writer.close(); }
Code Sample 2:
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: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </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()); } |
11
| Code Sample 1:
private void writeGif(String filename, String outputFile) throws IOException { File file = new File(filename); InputStream in = new FileInputStream(file); FileOutputStream fout = new FileOutputStream(outputFile); int totalRead = 0; int readBytes = 0; int blockSize = 65000; long fileLen = file.length(); byte b[] = new byte[blockSize]; while ((long) totalRead < fileLen) { readBytes = in.read(b, 0, blockSize); totalRead += readBytes; fout.write(b, 0, readBytes); } in.close(); fout.close(); }
Code Sample 2:
private synchronized Frame addFrame(INSERT_TYPE type, File source) throws IOException { if (source == null) throw new NullPointerException("Parameter 'source' is null"); if (!source.exists()) throw new IOException("File does not exist: " + source.getAbsolutePath()); if (source.length() <= 0) throw new IOException("File is empty: " + source.getAbsolutePath()); File newLocation = new File(Settings.getPropertyString(ConstantKeys.project_dir), formatFileName(frames_.size())); if (newLocation.compareTo(source) != 0) { switch(type) { case MOVE: source.renameTo(newLocation); break; case COPY: FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(newLocation).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); break; } } Frame f = new Frame(newLocation); f.createThumbNail(); frames_.add(f); return f; } |
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:
private void copyResource(final String resourceName, final File file) throws IOException { assertTrue(resourceName.startsWith("/")); InputStream in = null; boolean suppressExceptionOnClose = true; try { in = this.getClass().getResourceAsStream(resourceName); assertNotNull("Resource '" + resourceName + "' not found.", in); OutputStream out = null; try { out = new FileOutputStream(file); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } } |
00
| Code Sample 1:
protected boolean createFile(final IProject project, final IProgressMonitor monitor, final Template templ, final String sourceUrl, final String destFile, final boolean isBinary) throws IOException, CoreException { URL url; url = new URL(sourceUrl); final URLConnection con = url.openConnection(); final IFile f = project.getFile(replaceVariables(templ.getVariables(), destFile)); createParents(f, monitor); if (isBinary) { f.create(con.getInputStream(), true, monitor); } else { final StringWriter sw = new StringWriter(); final InputStream in = con.getInputStream(); for (; ; ) { final int c = in.read(); if (-1 == c) { break; } sw.write(c); } sw.close(); final String fileText = replaceVariables(templ.getVariables(), sw.toString()); f.create(new ByteArrayInputStream(fileText.getBytes()), true, monitor); } return true; }
Code Sample 2:
public static String md5Encrypt(String valueToEncrypted) { String encryptedValue = ""; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(valueToEncrypted.getBytes()); BigInteger hash = new BigInteger(1, digest.digest()); encryptedValue = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } return encryptedValue; } |
00
| Code Sample 1:
public String fetchDataDailyByStockId(String StockId, String market) throws IOException { URL url = new URL(urlDailyStockPrice.replace("{0}", StockId + "." + market)); URLConnection con = url.openConnection(); con.setConnectTimeout(20000); InputStream is = con.getInputStream(); byte[] bs = new byte[1024]; int len; OutputStream os = new FileOutputStream(dailyStockPriceList, true); while ((len = is.read(bs)) != -1) { os.write(bs, 0, len); } os.flush(); os.close(); is.close(); con = null; url = null; return null; }
Code Sample 2:
public void testPreparedStatement0009() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0009 " + " (i integer not null, " + " s char(10) not null) "); con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement("insert into #t0009 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } pstmt.close(); assertEquals(count, rowsToAdd); con.rollback(); ResultSet rs = stmt.executeQuery("select s, i from #t0009"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, 0); con.commit(); pstmt = con.prepareStatement("insert into #t0009 values (?, ?)"); rowsToAdd = 6; count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.commit(); pstmt.close(); rs = stmt.executeQuery("select s, i from #t0009"); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, rowsToAdd); con.commit(); stmt.close(); con.setAutoCommit(true); } |
11
| Code Sample 1:
private static byte[] getLoginHashSHA(final char[] password, final int seed) throws GGException { try { final MessageDigest hash = MessageDigest.getInstance("SHA1"); hash.update(new String(password).getBytes()); hash.update(GGUtils.intToByte(seed)); return hash.digest(); } catch (final NoSuchAlgorithmException e) { LOG.error("SHA1 algorithm not usable", e); throw new GGException("SHA1 algorithm not usable!", e); } }
Code Sample 2:
private byte[] digestPassword(byte[] salt, String password) throws AuthenticationException { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF8")); return md.digest(); } catch (Exception e) { throw new AuthenticationException(MESSAGE_CONFIGURATION_ERROR_KEY, e); } } |
11
| Code Sample 1:
public static void streamCopyFile(File srcFile, File destFile) { try { FileInputStream fi = new FileInputStream(srcFile); FileOutputStream fo = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int readLength = 0; while (readLength != -1) { readLength = fi.read(buf); if (readLength != -1) { fo.write(buf, 0, readLength); } } fo.close(); fi.close(); } catch (Exception e) { } }
Code Sample 2:
public static int convertImage(InputStream is, OutputStream os, String command) throws IOException, InterruptedException { if (logger.isInfoEnabled()) { logger.info(command); } Process p = Runtime.getRuntime().exec(command); ByteArrayOutputStream errOut = new ByteArrayOutputStream(); StreamGobbler errGobbler = new StreamGobbler(p.getErrorStream(), errOut, "Convert Thread (err gobbler): " + command); errGobbler.start(); StreamGobbler outGobbler = new StreamGobbler(new BufferedInputStream(is), p.getOutputStream(), "Convert Thread (out gobbler): " + command); outGobbler.start(); try { IOUtils.copy(p.getInputStream(), os); os.flush(); if (p.waitFor() != 0) { logger.error("Unable to convert, stderr: " + new String(errOut.toByteArray(), "UTF-8")); } return p.exitValue(); } finally { IOUtils.closeQuietly(os); } } |
00
| Code Sample 1:
public void gzip(File from, File to) { OutputStream out_zip = null; ArchiveOutputStream os = null; try { try { out_zip = new FileOutputStream(to); os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out_zip); os.putArchiveEntry(new ZipArchiveEntry(from.getName())); IOUtils.copy(new FileInputStream(from), os); os.closeArchiveEntry(); } finally { if (os != null) { os.close(); } } out_zip.close(); } catch (IOException ex) { fatal("IOException", ex); } catch (ArchiveException ex) { fatal("ArchiveException", ex); } }
Code Sample 2:
public void copyURLToFile(TmpFile p_TmpFile) { byte[] l_Buffer; URLConnection l_Connection = null; DataInputStream l_IN = null; DataOutputStream l_Out = null; FileOutputStream l_FileOutStream = null; try { System.gc(); if (error.compareTo(noError) == 0) { l_Connection = urlHome.openConnection(); l_FileOutStream = new FileOutputStream(p_TmpFile.getAbsolutePath()); l_Out = new DataOutputStream(l_FileOutStream); l_IN = new DataInputStream(l_Connection.getInputStream()); l_Buffer = new byte[8192]; int bytes = 0; while ((bytes = l_IN.read(l_Buffer)) > 0) { l_Out.write(l_Buffer, 0, bytes); } } } catch (MalformedURLException mue) { error = "MalformedURLException in connecting url was " + mue.getMessage(); } catch (IOException io) { error = "IOException in connecting url was " + io.getMessage(); } catch (Exception e) { error = "Exception in connecting url was " + e.getMessage(); } finally { try { l_IN.close(); l_Out.flush(); l_FileOutStream.flush(); l_FileOutStream.close(); l_Out.close(); } catch (Exception e) { error = "Exception in connecting url was " + e.getMessage(); } } } |
00
| Code Sample 1:
void IconmenuItem5_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (getPath() != null && !getPath().equals("")) { jFileChooser1.setCurrentDirectory(new File(getPath())); jFileChooser1.setSelectedFile(new File(getPath())); } if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getPath().lastIndexOf(separator); String imgName = getPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "", JOptionPane.ERROR_MESSAGE); } setPath(newPath); if (getDefaultPath() == null || getDefaultPath().equals("")) { String msgString = "E' stata selezionata un'immagine da associare all'IconShape, ma non e' " + "stata selezionata ancora nessun'immagine di default. Imposto quella scelta anche come " + "immagine di default?"; if (JOptionPane.showConfirmDialog(null, msgString.substring(0, Math.min(msgString.length(), getFatherPanel().MAX_DIALOG_MSG_SZ)), "choose one", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { setDefaultPath(newPath); createDefaultImage(); } } createImage(); } }
Code Sample 2:
private Collection<Class<? extends Plugin>> loadFromResource(ClassLoader classLoader, String resource) throws IOException { Collection<Class<? extends Plugin>> pluginClasses = new HashSet<Class<? extends Plugin>>(); Enumeration providerFiles = classLoader.getResources(resource); if (!providerFiles.hasMoreElements()) { logger.warning("Can't find the resource: " + resource); return pluginClasses; } do { URL url = (URL) providerFiles.nextElement(); InputStream stream = url.openStream(); BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); } catch (IOException e) { continue; } String line; while ((line = reader.readLine()) != null) { int index = line.indexOf('#'); if (index != -1) { line = line.substring(0, index); } line = line.trim(); if (line.length() > 0) { Class pluginClass; try { pluginClass = classLoader.loadClass(line); } catch (ClassNotFoundException e) { logger.log(Level.WARNING, "Can't use the Pluginclass with the name " + line + ".", e); continue; } if (Plugin.class.isAssignableFrom(pluginClass)) { pluginClasses.add((Class<? extends Plugin>) pluginClass); } else { logger.warning("The Pluginclass with the name " + line + " isn't a subclass of Plugin."); } } } reader.close(); stream.close(); } while (providerFiles.hasMoreElements()); return pluginClasses; } |
00
| Code Sample 1:
private void loadServers() { try { URL url = new URL(VirtualDeckConfig.SERVERS_URL); cmbServer.addItem("Local"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; if (in.readLine().equals("[list]")) { while ((str = in.readLine()) != null) { String[] host_line = str.split(";"); Host h = new Host(); h.setIp(host_line[0]); h.setPort(Integer.parseInt(host_line[1])); h.setName(host_line[2]); getServers().add(h); cmbServer.addItem(h.getName()); } } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
Code Sample 2:
public String hasheMotDePasse(String mdp) { MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { } sha.reset(); sha.update(mdp.getBytes()); byte[] digest = sha.digest(); String pass = new String(Base64.encode(digest)); pass = "{SHA}" + pass; return pass; } |
00
| Code Sample 1:
public void copyFile(String oldPath, String newPath) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { System.out.println("ๅคๅถๅไธชๆไปถๆไฝๅบ้"); e.printStackTrace(); } }
Code Sample 2:
public void readConfig(String urlString) throws Exception { try { URL url = new URL(urlString); InputStream in = url.openStream(); XmlDoc xml = new Parser().parse(new InputSource(in), true, true); Verifier v = new Verifier(InputOutput.create(SCHEMA), null); v.verify(xml.getDocument()); this.config = xml.getDocument(); } catch (Exception e) { log("Can't read " + urlString + ": " + e.toString()); throw e; } initParms(); log("Got parameters: \n" + paramsInfo()); initMessages(); log("Got messages: \n" + messagesInfo()); checkMessageId(); } |
00
| Code Sample 1:
private int writeTraceFile(final File destination_file, final String trace_file_name, final String trace_file_path) { URL url = null; BufferedInputStream is = null; FileOutputStream fo = null; BufferedOutputStream os = null; int b = 0; if (destination_file == null) { return 0; } try { url = new URL("http://" + trace_file_path + "/" + trace_file_name); is = new BufferedInputStream(url.openStream()); fo = new FileOutputStream(destination_file); os = new BufferedOutputStream(fo); while ((b = is.read()) != -1) { os.write(b); } os.flush(); is.close(); os.close(); } catch (Exception e) { System.err.println(url.toString()); Utilities.unexpectedException(e, this, CONTACT); return 0; } return 1; }
Code Sample 2:
public Out(Article article) throws Exception { String body = article.meta(ARTICLE_BODY).getString(); String url = find("a", "href", body); while (url.length() > 0 && url.startsWith("http://")) { System.out.println(url); conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("POST"); int code = conn.getResponseCode(); String ping = conn.getHeaderField("X-Pingback"); System.out.println(ping); if (ping != null) { conn = (HttpURLConnection) new URL(ping).openConnection(); conn.setDoOutput(true); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\"?>\n"); buffer.append("<methodCall>\n"); buffer.append(" <methodName>pingback.ping</methodName>\n"); buffer.append(" <params>\n"); buffer.append(" <param><value><string>http://" + User.host + "/article?id=" + article.getId() + "</string></value></param>\n"); buffer.append(" <param><value><string>" + url + "</string></value></param>\n"); buffer.append(" </params>\n"); buffer.append("</methodCall>\n"); System.out.println(buffer.toString()); OutputStream out = conn.getOutputStream(); out.write(buffer.toString().getBytes("UTF-8")); code = conn.getResponseCode(); InputStream in = null; if (code == 200) { in = conn.getInputStream(); } else if (code < 0) { throw new IOException("HTTP response unreadable."); } else { in = conn.getErrorStream(); } Deploy.pipe(in, System.out); in.close(); } url = find("a", "href", body); } } |
11
| Code Sample 1:
public boolean excuteBackup(String backupOrginlDrctry, String targetFileNm, String archiveFormat) throws JobExecutionException { File targetFile = new File(targetFileNm); File srcFile = new File(backupOrginlDrctry); if (!srcFile.exists()) { log.error("๋ฐฑ์
์๋ณธ๋๋ ํ ๋ฆฌ[" + srcFile.getAbsolutePath() + "]๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค."); throw new JobExecutionException("๋ฐฑ์
์๋ณธ๋๋ ํ ๋ฆฌ[" + srcFile.getAbsolutePath() + "]๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค."); } if (srcFile.isFile()) { log.error("๋ฐฑ์
์๋ณธ๋๋ ํ ๋ฆฌ[" + srcFile.getAbsolutePath() + "]๊ฐ ํ์ผ์
๋๋ค. ๋๋ ํ ๋ฆฌ๋ช
์ ์ง์ ํด์ผ ํฉ๋๋ค. "); throw new JobExecutionException("๋ฐฑ์
์๋ณธ๋๋ ํ ๋ฆฌ[" + srcFile.getAbsolutePath() + "]๊ฐ ํ์ผ์
๋๋ค. ๋๋ ํ ๋ฆฌ๋ช
์ ์ง์ ํด์ผ ํฉ๋๋ค. "); } boolean result = false; FileInputStream finput = null; FileOutputStream fosOutput = null; ArchiveOutputStream aosOutput = null; ArchiveEntry entry = null; try { log.debug("charter set : " + Charset.defaultCharset().name()); fosOutput = new FileOutputStream(targetFile); aosOutput = new ArchiveStreamFactory().createArchiveOutputStream(archiveFormat, fosOutput); if (ArchiveStreamFactory.TAR.equals(archiveFormat)) { ((TarArchiveOutputStream) aosOutput).setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); } File[] fileArr = srcFile.listFiles(); ArrayList list = EgovFileTool.getSubFilesByAll(fileArr); for (int i = 0; i < list.size(); i++) { File sfile = new File((String) list.get(i)); finput = new FileInputStream(sfile); if (ArchiveStreamFactory.TAR.equals(archiveFormat)) { entry = new TarArchiveEntry(sfile, new String(sfile.getAbsolutePath().getBytes(Charset.defaultCharset().name()), "8859_1")); ((TarArchiveEntry) entry).setSize(sfile.length()); } else { entry = new ZipArchiveEntry(sfile.getAbsolutePath()); ((ZipArchiveEntry) entry).setSize(sfile.length()); } aosOutput.putArchiveEntry(entry); IOUtils.copy(finput, aosOutput); aosOutput.closeArchiveEntry(); finput.close(); result = true; } aosOutput.close(); } catch (Exception e) { log.error("๋ฐฑ์
ํ์ผ์์ฑ์ค ์๋ฌ๊ฐ ๋ฐ์ํ์ต๋๋ค. ์๋ฌ : " + e.getMessage()); log.debug(e); result = false; throw new JobExecutionException("๋ฐฑ์
ํ์ผ์์ฑ์ค ์๋ฌ๊ฐ ๋ฐ์ํ์ต๋๋ค.", e); } finally { try { if (finput != null) finput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (aosOutput != null) aosOutput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (fosOutput != null) fosOutput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (result == false) targetFile.delete(); } catch (Exception e2) { log.error("IGNORE:", e2); } } return result; }
Code Sample 2:
public void testStorageStringWriter() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); { Writer w = r.getWriter(); w.write("This is an example"); w.write(" and another one."); w.flush(); assertEquals("This is an example and another one.", r.getText()); } { InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); } try { r.getOutputStream(); fail("Is not allowed as you already called getWriter()."); } catch (IOException e) { } { Writer output = r.getWriter(); output.write(" and another line"); output.write(" and write some more"); assertEquals("This is an example and another one. and another line and write some more", r.getText()); } { r.addText(" and some more."); assertEquals("This is an example and another one. and another line and write some more and some more.", r.getText()); } r.setEndState(ResponseStateOk.getInstance()); assertEquals(ResponseStateOk.getInstance(), r.getEndState()); try { r.getWriter(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } } |
00
| Code Sample 1:
public static void decryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.DECRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); }
Code Sample 2:
private static String getBase64(String text, String algorithm) throws NoSuchAlgorithmException { AssertUtility.notNull(text); AssertUtility.notNullAndNotSpace(algorithm); String base64; MessageDigest md = MessageDigest.getInstance(algorithm); md.update(text.getBytes()); base64 = new BASE64Encoder().encode(md.digest()); return base64; } |
11
| Code Sample 1:
public static void main(String[] args) { String fe = null, fk = null, f1 = null, f2 = null; DecimalFormat df = new DecimalFormat("000"); int key = 0; int i = 1; for (; ; ) { System.out.println("==================================================="); System.out.println("\n2009 BME\tTeam ESC's Compare\n"); System.out.println("===================================================\n"); System.out.println(" *** Menu ***\n"); System.out.println("1. Fajlok osszehasonlitasa"); System.out.println("2. Hasznalati utasitas"); System.out.println("3. Kilepes"); System.out.print("\nKivalasztott menu szama: "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { key = reader.read(); switch(key) { case '3': System.exit(0); break; case '2': System.out.println("\n @author Bedo Zotlan - F3VFDE"); System.out.println("Team ESC's Compare"); System.out.println("2009."); System.out.println(); System.out.println("(1) A program ket fajl osszahesonlitasat vegzi. A fajloknak a program gyokerkonyvtaraban kell lenniuk!"); System.out.println("(2) A menubol ertelem szeruen valasztunk az opciok kozul, majd a program keresere megadjuk a ket osszehasonlitando " + "fajl nevet kiterjesztessel egyutt, kulonben hibat kapunk!"); System.out.println("(3) Miutan elvegeztuk az osszehasonlitasokat a program mindegyiket kimenti a compare_xxx.txt fajlba, azonban ha kilepunk a programbol, " + "majd utana ismet elinditjuk es elkezdunk osszehasonlitasokat vegezni, akkor felulirhatja " + "az elozo futtatasbol kapott fajlainkat, erre kulonosen figyelni kell!"); System.out.println("(4) A kimeneti compare_xxx.txt fajlon kivul minden egyes osszehasonlitott fajlrol csinal egy <fajl neve>.<fajl kiterjesztese>.numbered " + "nevu fajlt, ami annyiban ter el az eredeti fajloktol, hogy soronkent sorszamozva vannak!"); System.out.println("(5) Egy nem ures es egy ures fajl osszehasonlitasa utan azt az eredmenyt kapjuk, hogy \"OK, megyezenek!\". Ez termeszetesen hibas" + " es a kimeneti fajlunk is ures lesz. Ezt szinten keruljuk el, ne hasonlitsunk ures fajlokhoz mas fajlokat!"); System.out.println("(6) A fajlok megtekintesehez Notepad++ 5.0.0 verzioja ajanlott legalabb!\n"); break; case '1': { System.out.print("\nAz etalon adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fe = (inFileName + ".numbered"); f1 = inFileName; String aLine; while ((aLine = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } System.out.print("A kapott adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fk = (inFileName + ".numbered"); f2 = inFileName; String aLine_k; while ((aLine_k = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine_k + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } try { int lnNo_c = 1; int mstk = 0; BufferedReader bin_e = new BufferedReader(new FileReader(fe)); BufferedReader bin_k = new BufferedReader(new FileReader(fk)); BufferedWriter bout = new BufferedWriter(new FileWriter("compare_" + i++ + ".txt")); Calendar actDate = Calendar.getInstance(); bout.write("==================================================\n"); bout.write("\n2009 BME\tTeam ESC's Compare"); bout.write("\n" + actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n\n"); bout.write("==================================================\n"); bout.write("Az etalon ertekekkel teli fajl neve: " + f1 + "\n"); bout.write("A kapott ertekekkel teli fajl neve: " + f2 + "\n\n"); System.out.println("==================================================\n"); System.out.println("\n2009 BME\tTeam ESC's Compare"); System.out.println(actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n"); System.out.println("==================================================\n"); System.out.println("\nAz etalon ertekekkel teli fajl neve: " + f1); System.out.println("A kapott ertekekkel teli fajl neve: " + f2 + "\n"); String aLine_c1 = null, aLine_c2 = null; File fa = new File(fe); File fb = new File(fk); if (fa.length() != fb.length()) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); } else { while (((aLine_c1 = bin_e.readLine()) != null) && ((aLine_c2 = bin_k.readLine()) != null)) if (aLine_c1.equals(aLine_c2)) { } else { mstk++; bout.write("#" + df.format(lnNo_c) + ": HIBA --> \t" + f1 + " : " + aLine_c1 + " \n\t\t\t\t\t" + f2 + " : " + aLine_c2 + "\n"); System.out.println("#" + df.format(lnNo_c) + ": HIBA -->\t " + f1 + " : " + aLine_c1 + " \n\t\t\t" + f2 + " : " + aLine_c2 + "\n"); lnNo_c++; } if (mstk != 0) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); bout.write("\nHibas sorok szama: " + mstk); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); System.out.println("Hibas sorok szama: " + mstk); } else { bout.write("\nOsszehasonlitas eredmenye: OK, megegyeznek!"); System.out.println("\nOsszehasonlitas eredm๏ฟฝnye: OK, megegyeznek!\n"); } } bin_e.close(); bin_k.close(); fa.delete(); fb.delete(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajl"); } break; } } } catch (Exception e) { System.out.println("A fut๏ฟฝs sor๏ฟฝn hiba t๏ฟฝrt๏ฟฝnt!"); } } }
Code Sample 2:
public void configureKerberos(boolean overwriteExistingSetup) throws Exception { OutputStream keyTabOut = null; InputStream keyTabIn = null; OutputStream krb5ConfOut = null; try { keyTabIn = loadKeyTabResource(keyTabResource); File file = new File(keyTabRepository + keyTabResource); if (!file.exists() || overwriteExistingSetup) { keyTabOut = new FileOutputStream(file, false); if (logger.isDebugEnabled()) logger.debug("Installing keytab file to : " + file.getAbsolutePath()); IOUtils.copy(keyTabIn, keyTabOut); } File krb5ConfFile = new File(System.getProperty("java.security.krb5.conf", defaultKrb5Config)); if (logger.isDebugEnabled()) logger.debug("Using Kerberos config file : " + krb5ConfFile.getAbsolutePath()); if (!krb5ConfFile.exists()) throw new Exception("Kerberos config file not found : " + krb5ConfFile.getAbsolutePath()); FileInputStream fis = new FileInputStream(krb5ConfFile); Wini krb5Conf = new Wini(KerberosConfigUtil.toIni(fis)); Ini.Section krb5Realms = krb5Conf.get("realms"); String windowsDomainSetup = krb5Realms.get(kerberosRealm); if (kerberosRealm == null || overwriteExistingSetup) { windowsDomainSetup = "{ kdc = " + keyDistributionCenter + ":88 admin_server = " + keyDistributionCenter + ":749 default_domain = " + kerberosRealm.toLowerCase() + " }"; krb5Realms.put(kerberosRealm, windowsDomainSetup); } Ini.Section krb5DomainRealms = krb5Conf.get("domain_realm"); String domainRealmSetup = krb5DomainRealms.get(kerberosRealm.toLowerCase()); if (domainRealmSetup == null || overwriteExistingSetup) { krb5DomainRealms.put(kerberosRealm.toLowerCase(), kerberosRealm); krb5DomainRealms.put("." + kerberosRealm.toLowerCase(), kerberosRealm); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); krb5Conf.store(baos); InputStream bios = new ByteArrayInputStream(baos.toByteArray()); bios = KerberosConfigUtil.toKrb5(bios); krb5ConfOut = new FileOutputStream(krb5ConfFile, false); IOUtils.copy(bios, krb5ConfOut); } catch (Exception e) { logger.error("Error while configuring Kerberos :" + e.getMessage(), e); throw e; } finally { IOUtils.closeQuietly(keyTabOut); IOUtils.closeQuietly(keyTabIn); IOUtils.closeQuietly(krb5ConfOut); } } |
11
| Code Sample 1:
@Override public void execute() throws BuildException { final String GC_USERNAME = "google-code-username"; final String GC_PASSWORD = "google-code-password"; if (StringUtils.isBlank(this.projectName)) throw new BuildException("undefined project"); if (this.file == null) throw new BuildException("undefined file"); if (!this.file.exists()) throw new BuildException("file not found :" + file); if (!this.file.isFile()) throw new BuildException("not a file :" + file); if (this.config == null) throw new BuildException("undefined config"); if (!this.config.exists()) throw new BuildException("file not found :" + config); if (!this.config.isFile()) throw new BuildException("not a file :" + config); PostMethod post = null; try { Properties cfg = new Properties(); FileInputStream fin = new FileInputStream(this.config); cfg.loadFromXML(fin); fin.close(); if (!cfg.containsKey(GC_USERNAME)) throw new BuildException("undefined " + GC_USERNAME + " in " + this.config); if (!cfg.containsKey(GC_PASSWORD)) throw new BuildException("undefined " + GC_PASSWORD + " in " + this.config); HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(cfg.getProperty(GC_USERNAME) + ":" + cfg.getProperty(GC_PASSWORD))); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = this.file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels.split("[, \t\n]+")) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", this.file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new BuildException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } catch (BuildException e) { throw e; } catch (Exception e) { throw new BuildException(e); } finally { if (post != null) post.releaseConnection(); } }
Code Sample 2:
public static void copier(final File pFichierSource, final File pFichierDest) { FileChannel vIn = null; FileChannel vOut = null; try { vIn = new FileInputStream(pFichierSource).getChannel(); vOut = new FileOutputStream(pFichierDest).getChannel(); vIn.transferTo(0, vIn.size(), vOut); } catch (Exception e) { e.printStackTrace(); } finally { if (vIn != null) { try { vIn.close(); } catch (IOException e) { } } if (vOut != null) { try { vOut.close(); } catch (IOException e) { } } } } |
00
| Code Sample 1:
private void connectAndLogin() throws SocketException, IOException, ClassNotFoundException, SQLException, FileNotFoundException { lastOperationTime = System.currentTimeMillis(); exit(); ftp = new FTPClient(); ftp.connect(SERVER); ftp.login(USERNAME, PASSWORD); ftp.enterLocalPassiveMode(); ftp.setFileType(FTP.BINARY_FILE_TYPE); System.out.println("Connected to " + SERVER + "."); db = new DB(propertiesPath); }
Code Sample 2:
@Override public int run() { Enumeration<?> e; try { e = About.class.getClassLoader().getResources("META-INF/MANIFEST.MF"); while (e.hasMoreElements()) { final URL url = (URL) e.nextElement(); if (url.toString().indexOf("renaissance") != -1) { final InputStream is = url.openStream(); Properties p = new Properties(); p.load(is); for (Entry<?, ?> entry : p.entrySet()) { System.err.println(entry); } } } } catch (IOException e1) { logger.fatal("Caught an exception " + e1); return 1; } System.err.println("Classpath is " + System.getProperty("java.class.path")); return 0; } |
11
| Code Sample 1:
public byte[] md5(String clearText) { MessageDigest md; byte[] digest; try { md = MessageDigest.getInstance("MD5"); md.update(clearText.getBytes()); digest = md.digest(); } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e.toString()); } return digest; }
Code Sample 2:
public static String encryptPasswd(String pass) { try { if (pass == null || pass.length() == 0) return pass; MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.reset(); sha.update(pass.getBytes("UTF-8")); return Base64OutputStream.encode(sha.digest()); } catch (Throwable t) { throw new SystemException(t); } } |
11
| Code Sample 1:
private void copy(File in, File out) { log.info("Copying yam file from: " + in.getName() + " to: " + out.getName()); try { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (IOException ioe) { fail("Failed testing while copying modified file: " + ioe.getMessage()); } }
Code Sample 2:
public static void copyFile(File src, File dst) throws IOException { File inputFile = src; File outputFile = dst; FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.