label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
| Code Sample 1:
public static boolean loadTestProperties(Properties props, Class<?> callingClazz, Class<?> hierarchyRootClazz, String resourceBaseName) { if (!hierarchyRootClazz.isAssignableFrom(callingClazz)) { throw new IllegalArgumentException("Class " + callingClazz + " is not derived from " + hierarchyRootClazz); } if (null == resourceBaseName) { throw new NullPointerException("resourceBaseName is null"); } String fqcn = callingClazz.getName(); String uqcn = fqcn.substring(fqcn.lastIndexOf('.') + 1); String callingClassResource = uqcn + ".properties"; String globalCallingClassResource = "/" + callingClassResource; String baseClassResource = resourceBaseName + "-" + uqcn + ".properties"; String globalBaseClassResource = "/" + baseClassResource; String pkgResource = resourceBaseName + ".properties"; String globalResource = "/" + pkgResource; boolean loaded = false; final String[] resources = { baseClassResource, globalBaseClassResource, callingClassResource, globalCallingClassResource, pkgResource, globalResource }; List<URL> urls = new ArrayList<URL>(); Class<?> clazz = callingClazz; do { for (String res : resources) { URL url = clazz.getResource(res); if (null != url && !urls.contains(url)) { urls.add(url); } } if (hierarchyRootClazz.equals(clazz)) { clazz = null; } else { clazz = clazz.getSuperclass(); } } while (null != clazz); ListIterator<URL> it = urls.listIterator(urls.size()); while (it.hasPrevious()) { URL url = it.previous(); InputStream in = null; try { LOG.info("Loading test properties from resource: " + url); in = url.openStream(); props.load(in); loaded = true; } catch (IOException ex) { LOG.warn("Failed to load properties from resource: " + url, ex); } IOUtil.closeSilently(in); } return loaded; }
Code Sample 2:
public void testGetContentInputStream() { URL url; try { url = new URL("http://www.wurzer.org/" + "Homepage/Publikationen/Eintrage/2009/10/7_Wissen_dynamisch_organisieren_files/" + "KnowTech%202009%20-%20Wissen%20dynamisch%20organisieren.pdf"); InputStream in = url.openStream(); Content c = provider.getContent(in); assertNotNull(c); assertTrue(!c.getFulltext().isEmpty()); assertTrue(c.getModificationDate() < System.currentTimeMillis()); assertTrue(c.getAttributes().size() > 0); assertEquals("KnowTech 2009 - Wissen dynamisch organisieren", c.getAttributeByName("Title").getValue()); assertEquals("Joerg Wurzer", c.getAttributeByName("Author").getValue()); assertEquals("Pages", c.getAttributeByName("Creator").getValue()); assertNull(c.getAttributeByName("Keywords")); assertTrue(c.getFulltext().startsWith("Wissen dynamisch organisieren")); assertTrue(c.getAttributeByName("Author").isKey()); assertTrue(!c.getAttributeByName("Producer").isKey()); } catch (MalformedURLException e) { fail("Malformed url - " + e.getMessage()); } catch (IOException e) { fail("Couldn't read file - " + e.getMessage()); } } |
00
| Code Sample 1:
private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri, ClientConnectionManager connectionManager) { InputStream contentInput = null; if (connectionManager == null) { try { URL url = new URI(uri).toURL(); URLConnection conn = url.openConnection(); conn.connect(); contentInput = conn.getInputStream(); } catch (Exception e) { Log.w(TAG, "Request failed: " + uri); e.printStackTrace(); return null; } } else { final DefaultHttpClient mHttpClient = new DefaultHttpClient(connectionManager, HTTP_PARAMS); HttpUriRequest request = new HttpGet(uri); HttpResponse httpResponse = null; try { httpResponse = mHttpClient.execute(request); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { contentInput = entity.getContent(); } } catch (Exception e) { Log.w(TAG, "Request failed: " + request.getURI()); return null; } } if (contentInput != null) { return new BufferedInputStream(contentInput, 4096); } else { return null; } }
Code Sample 2:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileChannel input = new FileInputStream(srcFile).getChannel(); try { FileChannel output = new FileOutputStream(destFile).getChannel(); try { output.transferFrom(input, 0, input.size()); } 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()); } } |
11
| Code Sample 1:
public boolean verifySignature() { try { byte[] data = readFile(name + ".tmp1.bin"); if (data == null) return false; if (data[data.length - 0x104] != 'N' || data[data.length - 0x103] != 'G' || data[data.length - 0x102] != 'I' || data[data.length - 0x101] != 'S') return false; byte[] signature = new byte[0x100]; byte[] module = new byte[data.length - 0x104]; System.arraycopy(data, data.length - 0x100, signature, 0, 0x100); System.arraycopy(data, 0, module, 0, data.length - 0x104); BigIntegerEx power = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { 0x01, 0x00, 0x01, 0x00 }); BigIntegerEx mod = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { (byte) 0x6B, (byte) 0xCE, (byte) 0xF5, (byte) 0x2D, (byte) 0x2A, (byte) 0x7D, (byte) 0x7A, (byte) 0x67, (byte) 0x21, (byte) 0x21, (byte) 0x84, (byte) 0xC9, (byte) 0xBC, (byte) 0x25, (byte) 0xC7, (byte) 0xBC, (byte) 0xDF, (byte) 0x3D, (byte) 0x8F, (byte) 0xD9, (byte) 0x47, (byte) 0xBC, (byte) 0x45, (byte) 0x48, (byte) 0x8B, (byte) 0x22, (byte) 0x85, (byte) 0x3B, (byte) 0xC5, (byte) 0xC1, (byte) 0xF4, (byte) 0xF5, (byte) 0x3C, (byte) 0x0C, (byte) 0x49, (byte) 0xBB, (byte) 0x56, (byte) 0xE0, (byte) 0x3D, (byte) 0xBC, (byte) 0xA2, (byte) 0xD2, (byte) 0x35, (byte) 0xC1, (byte) 0xF0, (byte) 0x74, (byte) 0x2E, (byte) 0x15, (byte) 0x5A, (byte) 0x06, (byte) 0x8A, (byte) 0x68, (byte) 0x01, (byte) 0x9E, (byte) 0x60, (byte) 0x17, (byte) 0x70, (byte) 0x8B, (byte) 0xBD, (byte) 0xF8, (byte) 0xD5, (byte) 0xF9, (byte) 0x3A, (byte) 0xD3, (byte) 0x25, (byte) 0xB2, (byte) 0x66, (byte) 0x92, (byte) 0xBA, (byte) 0x43, (byte) 0x8A, (byte) 0x81, (byte) 0x52, (byte) 0x0F, (byte) 0x64, (byte) 0x98, (byte) 0xFF, (byte) 0x60, (byte) 0x37, (byte) 0xAF, (byte) 0xB4, (byte) 0x11, (byte) 0x8C, (byte) 0xF9, (byte) 0x2E, (byte) 0xC5, (byte) 0xEE, (byte) 0xCA, (byte) 0xB4, (byte) 0x41, (byte) 0x60, (byte) 0x3C, (byte) 0x7D, (byte) 0x02, (byte) 0xAF, (byte) 0xA1, (byte) 0x2B, (byte) 0x9B, (byte) 0x22, (byte) 0x4B, (byte) 0x3B, (byte) 0xFC, (byte) 0xD2, (byte) 0x5D, (byte) 0x73, (byte) 0xE9, (byte) 0x29, (byte) 0x34, (byte) 0x91, (byte) 0x85, (byte) 0x93, (byte) 0x4C, (byte) 0xBE, (byte) 0xBE, (byte) 0x73, (byte) 0xA9, (byte) 0xD2, (byte) 0x3B, (byte) 0x27, (byte) 0x7A, (byte) 0x47, (byte) 0x76, (byte) 0xEC, (byte) 0xB0, (byte) 0x28, (byte) 0xC9, (byte) 0xC1, (byte) 0xDA, (byte) 0xEE, (byte) 0xAA, (byte) 0xB3, (byte) 0x96, (byte) 0x9C, (byte) 0x1E, (byte) 0xF5, (byte) 0x6B, (byte) 0xF6, (byte) 0x64, (byte) 0xD8, (byte) 0x94, (byte) 0x2E, (byte) 0xF1, (byte) 0xF7, (byte) 0x14, (byte) 0x5F, (byte) 0xA0, (byte) 0xF1, (byte) 0xA3, (byte) 0xB9, (byte) 0xB1, (byte) 0xAA, (byte) 0x58, (byte) 0x97, (byte) 0xDC, (byte) 0x09, (byte) 0x17, (byte) 0x0C, (byte) 0x04, (byte) 0xD3, (byte) 0x8E, (byte) 0x02, (byte) 0x2C, (byte) 0x83, (byte) 0x8A, (byte) 0xD6, (byte) 0xAF, (byte) 0x7C, (byte) 0xFE, (byte) 0x83, (byte) 0x33, (byte) 0xC6, (byte) 0xA8, (byte) 0xC3, (byte) 0x84, (byte) 0xEF, (byte) 0x29, (byte) 0x06, (byte) 0xA9, (byte) 0xB7, (byte) 0x2D, (byte) 0x06, (byte) 0x0B, (byte) 0x0D, (byte) 0x6F, (byte) 0x70, (byte) 0x9E, (byte) 0x34, (byte) 0xA6, (byte) 0xC7, (byte) 0x31, (byte) 0xBE, (byte) 0x56, (byte) 0xDE, (byte) 0xDD, (byte) 0x02, (byte) 0x92, (byte) 0xF8, (byte) 0xA0, (byte) 0x58, (byte) 0x0B, (byte) 0xFC, (byte) 0xFA, (byte) 0xBA, (byte) 0x49, (byte) 0xB4, (byte) 0x48, (byte) 0xDB, (byte) 0xEC, (byte) 0x25, (byte) 0xF3, (byte) 0x18, (byte) 0x8F, (byte) 0x2D, (byte) 0xB3, (byte) 0xC0, (byte) 0xB8, (byte) 0xDD, (byte) 0xBC, (byte) 0xD6, (byte) 0xAA, (byte) 0xA6, (byte) 0xDB, (byte) 0x6F, (byte) 0x7D, (byte) 0x7D, (byte) 0x25, (byte) 0xA6, (byte) 0xCD, (byte) 0x39, (byte) 0x6D, (byte) 0xDA, (byte) 0x76, (byte) 0x0C, (byte) 0x79, (byte) 0xBF, (byte) 0x48, (byte) 0x25, (byte) 0xFC, (byte) 0x2D, (byte) 0xC5, (byte) 0xFA, (byte) 0x53, (byte) 0x9B, (byte) 0x4D, (byte) 0x60, (byte) 0xF4, (byte) 0xEF, (byte) 0xC7, (byte) 0xEA, (byte) 0xAC, (byte) 0xA1, (byte) 0x7B, (byte) 0x03, (byte) 0xF4, (byte) 0xAF, (byte) 0xC7 }); byte[] result = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, signature).modPow(power, mod).toByteArray(); byte[] digest; byte[] properResult = new byte[0x100]; for (int i = 0; i < properResult.length; i++) properResult[i] = (byte) 0xBB; MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(module); md.update("MAIEV.MOD".getBytes()); digest = md.digest(); System.arraycopy(digest, 0, properResult, 0, digest.length); for (int i = 0; i < result.length; i++) if (result[i] != properResult[i]) return false; return true; } catch (Exception e) { System.out.println("Failed to verify signature: " + e.toString()); } return false; }
Code Sample 2:
public static String encryptString(String str) { StringBuffer sb = new StringBuffer(); int i; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes()); byte[] md5Bytes = md5.digest(); for (i = 0; i < md5Bytes.length; i++) { sb.append(md5Bytes[i]); } } catch (Exception e) { } return sb.toString(); } |
00
| Code Sample 1:
public boolean performFinish() { try { IJavaProject javaProject = JavaCore.create(getProject()); final IProjectDescription projectDescription = ResourcesPlugin.getWorkspace().newProjectDescription(projectPage.getProjectName()); projectDescription.setLocation(null); getProject().create(projectDescription, null); List<IClasspathEntry> classpathEntries = new ArrayList<IClasspathEntry>(); projectDescription.setNatureIds(getNatures()); List<String> builderIDs = new ArrayList<String>(); addBuilders(builderIDs); ICommand[] buildCMDS = new ICommand[builderIDs.size()]; int i = 0; for (String builderID : builderIDs) { ICommand build = projectDescription.newCommand(); build.setBuilderName(builderID); buildCMDS[i++] = build; } projectDescription.setBuildSpec(buildCMDS); getProject().open(null); getProject().setDescription(projectDescription, null); addClasspaths(classpathEntries, getProject()); javaProject.setRawClasspath(classpathEntries.toArray(new IClasspathEntry[classpathEntries.size()]), null); javaProject.setOutputLocation(new Path("/" + projectPage.getProjectName() + "/bin"), null); createFiles(); return true; } catch (Exception exception) { StatusManager.getManager().handle(new Status(IStatus.ERROR, getPluginID(), "Problem creating " + getProjectTypeName() + " project. Ignoring.", exception)); try { getProject().delete(true, null); } catch (Exception e) { } return false; } }
Code Sample 2:
public ArrayList loadIndexes() { JSONObject job = new JSONObject(); ArrayList al = new ArrayList(); try { String req = job.put("OperationId", "1").toString(); InputStream is = null; String result = ""; JSONObject jArray = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://192.168.1.4:8080/newgenlibctxt/CarbonServlet"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("OperationId", "1")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } try { JSONObject jobres = new JSONObject(result); JSONArray jarr = jobres.getJSONArray("MobileIndexes"); for (int i = 0; i < jarr.length(); i++) { String indexname = jarr.getString(i); al.add(indexname); } } catch (JSONException e) { e.printStackTrace(); } } catch (Exception exp) { exp.printStackTrace(); } return al; } |
00
| Code Sample 1:
public File createWindow(String pdfUrl) { URL url; InputStream is; try { int fileLength = 0; String str; if (pdfUrl.startsWith("jar:/")) { str = "file.pdf"; is = this.getClass().getResourceAsStream(pdfUrl.substring(4)); } else { url = new URL(pdfUrl); is = url.openStream(); str = url.getPath().substring(url.getPath().lastIndexOf('/') + 1); fileLength = url.openConnection().getContentLength(); } final String filename = str; tempURLFile = File.createTempFile(filename.substring(0, filename.lastIndexOf('.')), filename.substring(filename.lastIndexOf('.')), new File(ObjectStore.temp_dir)); FileOutputStream fos = new FileOutputStream(tempURLFile); if (visible) { download.setLocation((coords.x - (download.getWidth() / 2)), (coords.y - (download.getHeight() / 2))); download.setVisible(true); } if (visible) { pb.setMinimum(0); pb.setMaximum(fileLength); String message = Messages.getMessage("PageLayoutViewMenu.DownloadWindowMessage"); message = message.replaceAll("FILENAME", filename); downloadFile.setText(message); Font f = turnOff.getFont(); turnOff.setFont(new Font(f.getName(), f.getStyle(), 8)); turnOff.setAlignmentY(JLabel.RIGHT_ALIGNMENT); turnOff.setText(Messages.getMessage("PageLayoutViewMenu.DownloadWindowTurnOff")); } byte[] buffer = new byte[4096]; int read; int current = 0; String rate = "kb"; int mod = 1000; if (fileLength > 1000000) { rate = "mb"; mod = 1000000; } if (visible) { progress = Messages.getMessage("PageLayoutViewMenu.DownloadWindowProgress"); if (fileLength < 1000000) progress = progress.replaceAll("DVALUE", (fileLength / mod) + " " + rate); else { String fraction = String.valueOf(((fileLength % mod) / 10000)); if (((fileLength % mod) / 10000) < 10) fraction = "0" + fraction; progress = progress.replaceAll("DVALUE", (fileLength / mod) + "." + fraction + " " + rate); } } while ((read = is.read(buffer)) != -1) { current = current + read; downloadCount = downloadCount + read; if (visible) { if (fileLength < 1000000) downloadMessage.setText(progress.replaceAll("DSOME", (current / mod) + " " + rate)); else { String fraction = String.valueOf(((current % mod) / 10000)); if (((current % mod) / 10000) < 10) fraction = "0" + fraction; downloadMessage.setText(progress.replaceAll("DSOME", (current / mod) + "." + fraction + " " + rate)); } pb.setValue(current); download.repaint(); } fos.write(buffer, 0, read); } fos.flush(); is.close(); fos.close(); if (visible) downloadMessage.setText("Download of " + filename + " is complete."); } catch (Exception e) { LogWriter.writeLog("[PDF] Exception " + e + " opening URL " + pdfUrl); e.printStackTrace(); } if (visible) download.setVisible(false); return tempURLFile; }
Code Sample 2:
private Element getXmlFromGeoNetwork(String urlIn, Session userSession) throws FailedActionException { Element results = null; try { URL url = new URL(urlIn); URLConnection conn = url.openConnection(); conn.setConnectTimeout(1000); String cookie = (String) userSession.getAttribute("usercookie.object"); if (cookie != null) conn.setRequestProperty("Cookie", cookie); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); try { results = Xml.loadStream(in); } finally { in.close(); } } catch (Exception e) { throw new FailedActionException(FailedActionReason.SYSTEM_ERROR); } return results; } |
11
| Code Sample 1:
public Object run() { try { MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(buf.toString().getBytes()); byte[] data = digest.digest(); serialNum = new BASE64Encoder().encode(data); return serialNum; } catch (NoSuchAlgorithmException exp) { BootSecurityManager.securityLogger.log(Level.SEVERE, exp.getMessage(), exp); return buf.toString(); } }
Code Sample 2:
public static String SHA1(String text) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes()); byte byteData[] = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } StringBuilder hexString = new StringBuilder(); 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(); } |
00
| Code Sample 1:
public void test_UseCache_HttpURLConnection_NoCached_GetOutputStream() throws Exception { ResponseCache.setDefault(new MockNonCachedResponseCache()); uc = (HttpURLConnection) url.openConnection(); uc.setChunkedStreamingMode(10); uc.setDoOutput(true); uc.getOutputStream(); assertTrue(isGetCalled); assertFalse(isPutCalled); assertFalse(isAbortCalled); uc.disconnect(); }
Code Sample 2:
public static String urlPost(Map<String, String> paraMap, String urlStr) throws IOException { String strParam = ""; for (Map.Entry<String, String> entry : paraMap.entrySet()) { strParam = strParam + (entry.getKey() + "=" + entry.getValue()) + "&"; } URL url = new URL(urlStr); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8"); out.write(strParam); out.flush(); out.close(); String sCurrentLine; String sTotalString; sCurrentLine = ""; sTotalString = ""; InputStream l_urlStream; l_urlStream = connection.getInputStream(); BufferedReader l_reader = new BufferedReader(new InputStreamReader(l_urlStream)); while ((sCurrentLine = l_reader.readLine()) != null) { sTotalString += sCurrentLine + "\r\n"; } System.out.println(sTotalString); return sTotalString; } |
00
| Code Sample 1:
protected 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 (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
Code Sample 2:
public void run() { try { String data = URLEncoder.encode("send_id", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8"); data += "&" + URLEncoder.encode("author", "UTF-8") + "=" + URLEncoder.encode(name.getText(), "UTF-8"); data += "&" + URLEncoder.encode("location", "UTF-8") + "=" + URLEncoder.encode(System.getProperty("user.language"), "UTF-8"); data += "&" + URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(email.getText(), "UTF-8"); data += "&" + URLEncoder.encode("content", "UTF-8") + "=" + URLEncoder.encode(comment.getText(), "UTF-8"); data += "&" + URLEncoder.encode("rate", "UTF-8") + "=" + URLEncoder.encode(rate.getSelectedItem().toString(), "UTF-8"); System.out.println(data); URL url = new URL("http://javablock.sourceforge.net/book/index.php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String address = rd.readLine(); JPanel panel = new JPanel(); panel.add(new JLabel("Comment added")); panel.add(new JTextArea("visit: http://javablock.sourceforge.net/")); JOptionPane.showMessageDialog(null, new JLabel("Comment sended correctly!")); wr.close(); rd.close(); hide(); } catch (IOException ex) { Logger.getLogger(guestBook.class.getName()).log(Level.SEVERE, null, ex); } } |
00
| Code Sample 1:
private String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
Code Sample 2:
public void executeRequest(OperationContext context) throws Throwable { long t1 = System.currentTimeMillis(); GetPortrayMapCapabilitiesParams params = context.getRequestOptions().getGetPortrayMapCapabilitiesOptions(); String srvCfg = context.getRequestContext().getApplicationConfiguration().getCatalogConfiguration().getParameters().getValue("openls.portrayMap"); String sUrl = srvCfg + "?f=json&pretty=true"; URL url = new URL(sUrl); URLConnection conn = url.openConnection(); String line = ""; String sResponse = ""; InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader rd = new BufferedReader(isr); while ((line = rd.readLine()) != null) { sResponse += line; } rd.close(); parseResponse(params, sResponse); long t2 = System.currentTimeMillis(); LOGGER.info("PERFORMANCE: " + (t2 - t1) + " ms spent performing service"); } |
11
| Code Sample 1:
private static byte[] createMD5(String seed) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(seed.getBytes("UTF-8")); return md5.digest(); }
Code Sample 2:
public static String calculatesMD5(String plainText) throws NoSuchAlgorithmException { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(plainText.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { plainText = Integer.toHexString(0xFF & digest[i]); if (plainText.length() < 2) { plainText = "0" + plainText; } hexString.append(plainText); } return hexString.toString(); } |
11
| Code Sample 1:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
@Override protected void writeFile() { super.writeFile(); try { String tagListFilePath = file.toURI().toASCIIString(); tagListFilePath = tagListFilePath.substring(0, tagListFilePath.lastIndexOf(FileManager.GLIPS_VIEW_EXTENSION)) + FileManager.TAG_LIST_FILE_EXTENSION; File tagListFile = new File(new URI(tagListFilePath)); StringBuffer buffer = new StringBuffer(""); for (String tagName : tags) { buffer.append(tagName + "\n"); } ByteBuffer byteBuffer = ByteBuffer.wrap(buffer.toString().getBytes("UTF-8")); FileOutputStream out = new FileOutputStream(tagListFile); FileChannel channel = out.getChannel(); channel.write(byteBuffer); channel.close(); } catch (Exception ex) { } try { String parentPath = file.getParentFile().toURI().toASCIIString(); if (!parentPath.endsWith("/")) { parentPath += "/"; } File srcFile = null, destFile = null; byte[] tab = new byte[1000]; int nb = 0; InputStream in = null; OutputStream out = null; for (String destinationName : dataBaseFiles.keySet()) { srcFile = dataBaseFiles.get(destinationName); if (srcFile != null) { destFile = new File(new URI(parentPath + destinationName)); in = new BufferedInputStream(new FileInputStream(srcFile)); out = new BufferedOutputStream(new FileOutputStream(destFile)); while (in.available() > 0) { nb = in.read(tab); if (nb > 0) { out.write(tab, 0, nb); } } in.close(); out.flush(); out.close(); } } } catch (Exception ex) { ex.printStackTrace(); } } |
00
| Code Sample 1:
public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
Code Sample 2:
static void test() throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; Savepoint sp = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); st = conn.createStatement(); String sql = "update user set money=money-10 where id=1"; st.executeUpdate(sql); sp = conn.setSavepoint(); sql = "update user set money=money-10 where id=3"; st.executeUpdate(sql); sql = "select money from user where id=2"; rs = st.executeQuery(sql); float money = 0.0f; if (rs.next()) { money = rs.getFloat("money"); } if (money > 300) throw new RuntimeException("�Ѿ��������ֵ��"); sql = "update user set money=money+10 where id=2"; st.executeUpdate(sql); conn.commit(); } catch (RuntimeException e) { if (conn != null && sp != null) { conn.rollback(sp); conn.commit(); } throw e; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { JdbcUtils.free(rs, st, conn); } } |
11
| Code Sample 1:
protected Configuration() { try { Enumeration<URL> resources = getClass().getClassLoader().getResources("activejdbc_models.properties"); while (resources.hasMoreElements()) { URL url = resources.nextElement(); LogFilter.log(logger, "Load models from: " + url.toExternalForm()); InputStream inputStream = null; try { inputStream = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { String[] parts = Util.split(line, ':'); String modelName = parts[0]; String dbName = parts[1]; if (modelsMap.get(dbName) == null) { modelsMap.put(dbName, new ArrayList<String>()); } modelsMap.get(dbName).add(modelName); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) inputStream.close(); } } } catch (IOException e) { throw new InitException(e); } if (modelsMap.isEmpty()) { LogFilter.log(logger, "ActiveJDBC Warning: Cannot locate any models, assuming project without models."); return; } try { InputStream in = getClass().getResourceAsStream("/activejdbc.properties"); if (in != null) properties.load(in); } catch (Exception e) { throw new InitException(e); } String cacheManagerClass = properties.getProperty("cache.manager"); if (cacheManagerClass != null) { try { Class cmc = Class.forName(cacheManagerClass); cacheManager = (CacheManager) cmc.newInstance(); } catch (Exception e) { throw new InitException("failed to initialize a CacheManager. Please, ensure that the property " + "'cache.manager' points to correct class which extends 'activejdbc.cache.CacheManager' class and provides a default constructor.", e); } } }
Code Sample 2:
public Vector Get() throws Exception { String query_str = BuildYahooQueryString(); if (query_str == null) return null; Vector result = new Vector(); HttpURLConnection urlc = null; try { URL url = new URL(URL_YAHOO_QUOTE + "?" + query_str + "&" + FORMAT); urlc = (HttpURLConnection) url.openConnection(); urlc.setRequestMethod("GET"); urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/html;charset=UTF-8"); if (urlc.getResponseCode() == 200) { InputStream in = urlc.getInputStream(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); String msg = null; while ((msg = reader.readLine()) != null) { ExchangeRate rate = ParseYahooData(msg); if (rate != null) result.add(rate); } } finally { if (reader != null) try { reader.close(); } catch (Exception e1) { } if (in != null) try { in.close(); } catch (Exception e1) { } } return result; } } finally { if (urlc != null) try { urlc.disconnect(); } catch (Exception e) { } } return null; } |
11
| Code Sample 1:
public MapInfo loadLocalMapData(String fileName) { MapInfo info = mapCacheLocal.get(fileName); if (info != null && info.getContent() == null) { try { BufferedReader bufferedreader; URL fetchUrl = new URL(localMapContextUrl, fileName); URLConnection urlconnection = fetchUrl.openConnection(); if (urlconnection.getContentEncoding() != null) { bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), urlconnection.getContentEncoding())); } else { bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), "utf-8")); } String line; StringBuilder mapContent = new StringBuilder(); while ((line = bufferedreader.readLine()) != null) { mapContent.append(line); mapContent.append("\n"); } info.setContent(mapContent.toString()); GameMapImplementation gameMap = GameMapImplementation.createFromMapInfo(info); } catch (IOException _ex) { System.err.println("HexTD::readFile:: Can't read from " + fileName); } } else { System.err.println("HexTD::readFile:: file not in cache: " + fileName); } return info; }
Code Sample 2:
private void importExample(boolean server) throws IOException, XMLStreamException, FactoryConfigurationError { InputStream example = null; if (server) { monitor.setNote(Messages.getString("ImportExampleDialog.Cont")); monitor.setProgress(0); String page = engine.getConfiguration().getProperty("example.url"); URL url = new URL(page); BufferedReader rr = new BufferedReader(new InputStreamReader(url.openStream())); try { sleep(3000); } catch (InterruptedException e1) { Logger.getLogger(this.getClass()).debug("Internal error.", e1); } if (monitor.isCanceled()) { return; } try { while (rr.ready()) { if (monitor.isCanceled()) { return; } String l = rr.readLine(); if (example == null) { int i = l.indexOf("id=\"example\""); if (i > 0) { l = l.substring(i + 19); l = l.substring(0, l.indexOf('"')); url = new URL(l); example = url.openStream(); } } } } catch (IOException ex) { throw ex; } finally { if (rr != null) { try { rr.close(); } catch (Exception e) { Logger.getLogger(this.getClass()).debug("Internal error.", e); } } } } else { InputStream is = ApplicationHelper.class.getClassLoader().getResourceAsStream("gtd-free-example.xml"); if (is != null) { example = is; } } if (example != null) { if (monitor.isCanceled()) { try { example.close(); } catch (IOException e) { Logger.getLogger(this.getClass()).debug("Internal error.", e); } return; } monitor.setNote(Messages.getString("ImportExampleDialog.Read")); monitor.setProgress(1); model = new GTDModel(null); GTDDataXMLTools.importFile(model, example); try { example.close(); } catch (IOException e) { Logger.getLogger(this.getClass()).debug("Internal error.", e); } if (monitor.isCanceled()) { return; } monitor.setNote(Messages.getString("ImportExampleDialog.Imp.File")); monitor.setProgress(2); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { if (monitor.isCanceled()) { return; } engine.getGTDModel().importData(model); } }); } catch (InterruptedException e1) { Logger.getLogger(this.getClass()).debug("Internal error.", e1); } catch (InvocationTargetException e1) { Logger.getLogger(this.getClass()).debug("Internal error.", e1); } } else { throw new IOException("Failed to obtain remote example file."); } } |
00
| Code Sample 1:
public DefaultMainControl(@NotNull final FileFilter scriptFileFilter, @NotNull final String scriptExtension, @NotNull final String scriptName, final int spellType, @Nullable final String spellFile, @NotNull final String scriptsDir, final ErrorView errorView, @NotNull final EditorFactory<G, A, R> editorFactory, final boolean forceReadFromFiles, @NotNull final GlobalSettings globalSettings, @NotNull final ConfigSourceFactory configSourceFactory, @NotNull final PathManager pathManager, @NotNull final GameObjectMatchers gameObjectMatchers, @NotNull final GameObjectFactory<G, A, R> gameObjectFactory, @NotNull final ArchetypeTypeSet archetypeTypeSet, @NotNull final ArchetypeSet<G, A, R> archetypeSet, @NotNull final ArchetypeChooserModel<G, A, R> archetypeChooserModel, @NotNull final AutojoinLists<G, A, R> autojoinLists, @NotNull final AbstractMapManager<G, A, R> mapManager, @NotNull final PluginModel<G, A, R> pluginModel, @NotNull final DelegatingMapValidator<G, A, R> validators, @NotNull final ScriptedEventEditor<G, A, R> scriptedEventEditor, @NotNull final AbstractResources<G, A, R> resources, @NotNull final Spells<NumberSpell> numberSpells, @NotNull final Spells<GameObjectSpell<G, A, R>> gameObjectSpells, @NotNull final PluginParameterFactory<G, A, R> pluginParameterFactory, @NotNull final ValidatorPreferences validatorPreferences, @NotNull final MapWriter<G, A, R> mapWriter) { final XmlHelper xmlHelper; try { xmlHelper = new XmlHelper(); } catch (final ParserConfigurationException ex) { log.fatal("Cannot create XML parser: " + ex.getMessage()); throw new MissingResourceException("Cannot create XML parser: " + ex.getMessage(), null, null); } final AttributeRangeChecker<G, A, R> attributeRangeChecker = new AttributeRangeChecker<G, A, R>(validatorPreferences); final EnvironmentChecker<G, A, R> environmentChecker = new EnvironmentChecker<G, A, R>(validatorPreferences); final DocumentBuilder documentBuilder = xmlHelper.getDocumentBuilder(); try { final URL url = IOUtils.getResource(globalSettings.getConfigurationDirectory(), "GameObjectMatchers.xml"); final ErrorViewCollector gameObjectMatchersErrorViewCollector = new ErrorViewCollector(errorView, url); try { documentBuilder.setErrorHandler(new ErrorViewCollectorErrorHandler(gameObjectMatchersErrorViewCollector, ErrorViewCategory.GAMEOBJECTMATCHERS_FILE_INVALID)); try { final GameObjectMatchersParser gameObjectMatchersParser = new GameObjectMatchersParser(documentBuilder, xmlHelper.getXPath()); gameObjectMatchersParser.readGameObjectMatchers(url, gameObjectMatchers, gameObjectMatchersErrorViewCollector); } finally { documentBuilder.setErrorHandler(null); } } catch (final IOException ex) { gameObjectMatchersErrorViewCollector.addWarning(ErrorViewCategory.GAMEOBJECTMATCHERS_FILE_INVALID, ex.getMessage()); } final ValidatorFactory<G, A, R> validatorFactory = new ValidatorFactory<G, A, R>(validatorPreferences, gameObjectMatchers, globalSettings, mapWriter); loadValidators(validators, validatorFactory, errorView); editorFactory.initMapValidators(validators, gameObjectMatchersErrorViewCollector, globalSettings, gameObjectMatchers, attributeRangeChecker, validatorPreferences); validators.addValidator(attributeRangeChecker); validators.addValidator(environmentChecker); } catch (final FileNotFoundException ex) { errorView.addWarning(ErrorViewCategory.GAMEOBJECTMATCHERS_FILE_INVALID, "GameObjectMatchers.xml: " + ex.getMessage()); } final GameObjectMatcher shopSquareMatcher = gameObjectMatchers.getMatcher("system_shop_square", "shop_square"); if (shopSquareMatcher != null) { final GameObjectMatcher noSpellsMatcher = gameObjectMatchers.getMatcher("system_no_spells", "no_spells"); if (noSpellsMatcher != null) { final GameObjectMatcher blockedMatcher = gameObjectMatchers.getMatcher("system_blocked", "blocked"); validators.addValidator(new ShopSquareChecker<G, A, R>(validatorPreferences, shopSquareMatcher, noSpellsMatcher, blockedMatcher)); } final GameObjectMatcher paidItemMatcher = gameObjectMatchers.getMatcher("system_paid_item"); if (paidItemMatcher != null) { validators.addValidator(new PaidItemShopSquareChecker<G, A, R>(validatorPreferences, shopSquareMatcher, paidItemMatcher)); } } Map<String, TreasureTreeNode> specialTreasureLists; try { final URL url = IOUtils.getResource(globalSettings.getConfigurationDirectory(), "TreasureLists.xml"); final ErrorViewCollector treasureListsErrorViewCollector = new ErrorViewCollector(errorView, url); try { final InputStream inputStream = url.openStream(); try { documentBuilder.setErrorHandler(new ErrorViewCollectorErrorHandler(treasureListsErrorViewCollector, ErrorViewCategory.TREASURES_FILE_INVALID)); try { final Document specialTreasureListsDocument = documentBuilder.parse(new InputSource(inputStream)); specialTreasureLists = TreasureListsParser.parseTreasureLists(specialTreasureListsDocument); } finally { documentBuilder.setErrorHandler(null); } } finally { inputStream.close(); } } catch (final IOException ex) { treasureListsErrorViewCollector.addWarning(ErrorViewCategory.TREASURES_FILE_INVALID, ex.getMessage()); specialTreasureLists = Collections.emptyMap(); } catch (final SAXException ex) { treasureListsErrorViewCollector.addWarning(ErrorViewCategory.TREASURES_FILE_INVALID, ex.getMessage()); specialTreasureLists = Collections.emptyMap(); } } catch (final FileNotFoundException ex) { errorView.addWarning(ErrorViewCategory.TREASURES_FILE_INVALID, "TreasureLists.xml: " + ex.getMessage()); specialTreasureLists = Collections.emptyMap(); } final ConfigSource configSource = forceReadFromFiles ? configSourceFactory.getFilesConfigSource() : configSourceFactory.getConfigSource(globalSettings.getConfigSourceName()); treasureTree = TreasureLoader.parseTreasures(errorView, specialTreasureLists, configSource, globalSettings); final ArchetypeAttributeFactory archetypeAttributeFactory = new DefaultArchetypeAttributeFactory(); final ArchetypeAttributeParser archetypeAttributeParser = new ArchetypeAttributeParser(archetypeAttributeFactory); final ArchetypeTypeParser archetypeTypeParser = new ArchetypeTypeParser(archetypeAttributeParser); ArchetypeTypeList eventTypeSet = null; try { final URL url = IOUtils.getResource(globalSettings.getConfigurationDirectory(), CommonConstants.TYPEDEF_FILE); final ErrorViewCollector typesErrorViewCollector = new ErrorViewCollector(errorView, url); documentBuilder.setErrorHandler(new ErrorViewCollectorErrorHandler(typesErrorViewCollector, ErrorViewCategory.GAMEOBJECTMATCHERS_FILE_INVALID)); try { final ArchetypeTypeSetParser archetypeTypeSetParser = new ArchetypeTypeSetParser(documentBuilder, archetypeTypeSet, archetypeTypeParser); archetypeTypeSetParser.loadTypesFromXML(typesErrorViewCollector, new InputSource(url.toString())); } finally { documentBuilder.setErrorHandler(null); } final ArchetypeTypeList eventTypeSetTmp = archetypeTypeSet.getList("event"); if (eventTypeSetTmp == null) { typesErrorViewCollector.addWarning(ErrorViewCategory.TYPES_ENTRY_INVALID, "list 'list_event' does not exist"); } else { eventTypeSet = eventTypeSetTmp; } } catch (final FileNotFoundException ex) { errorView.addWarning(ErrorViewCategory.TYPES_FILE_INVALID, CommonConstants.TYPEDEF_FILE + ": " + ex.getMessage()); } if (eventTypeSet == null) { eventTypeSet = new ArchetypeTypeList(); } scriptArchUtils = editorFactory.newScriptArchUtils(eventTypeSet); final ScriptedEventFactory<G, A, R> scriptedEventFactory = editorFactory.newScriptedEventFactory(scriptArchUtils, gameObjectFactory, scriptedEventEditor, archetypeSet); scriptArchEditor = new DefaultScriptArchEditor<G, A, R>(scriptedEventFactory, scriptExtension, scriptName, scriptArchUtils, scriptFileFilter, globalSettings, mapManager, pathManager); scriptedEventEditor.setScriptArchEditor(scriptArchEditor); scriptArchData = editorFactory.newScriptArchData(); scriptArchDataUtils = editorFactory.newScriptArchDataUtils(scriptArchUtils, scriptedEventFactory, scriptedEventEditor); final long timeStart = System.currentTimeMillis(); if (log.isInfoEnabled()) { log.info("Start to load archetypes..."); } configSource.read(globalSettings, resources, errorView); for (final R archetype : archetypeSet.getArchetypes()) { final CharSequence editorFolder = archetype.getEditorFolder(); if (editorFolder != null && !editorFolder.equals(GameObject.EDITOR_FOLDER_INTERN)) { final String[] tmp = StringUtils.PATTERN_SLASH.split(editorFolder, 2); if (tmp.length == 2) { final String panelName = tmp[0]; final String folderName = tmp[1]; archetypeChooserModel.addArchetype(panelName, folderName, archetype); } } } if (log.isInfoEnabled()) { log.info("Archetype loading took " + (double) (System.currentTimeMillis() - timeStart) / 1000.0 + " seconds."); } if (spellType != 0) { new ArchetypeSetSpellLoader<G, A, R>(gameObjectFactory).load(archetypeSet, spellType, gameObjectSpells); gameObjectSpells.sort(); } if (spellFile != null) { try { final URL url = IOUtils.getResource(globalSettings.getConfigurationDirectory(), spellFile); final ErrorViewCollector errorViewCollector = new ErrorViewCollector(errorView, url); documentBuilder.setErrorHandler(new ErrorViewCollectorErrorHandler(errorViewCollector, ErrorViewCategory.SPELLS_FILE_INVALID)); try { XMLSpellLoader.load(errorViewCollector, url, xmlHelper.getDocumentBuilder(), numberSpells); } finally { documentBuilder.setErrorHandler(null); } } catch (final FileNotFoundException ex) { errorView.addWarning(ErrorViewCategory.SPELLS_FILE_INVALID, spellFile + ": " + ex.getMessage()); } numberSpells.sort(); } final File scriptsFile = new File(globalSettings.getMapsDirectory(), scriptsDir); final PluginModelParser<G, A, R> pluginModelParser = new PluginModelParser<G, A, R>(pluginParameterFactory); new PluginModelLoader<G, A, R>(pluginModelParser).loadPlugins(errorView, scriptsFile, pluginModel); new AutojoinListsParser<G, A, R>(errorView, archetypeSet, autojoinLists).loadList(globalSettings.getConfigurationDirectory()); ArchetypeTypeChecks.addChecks(archetypeTypeSet, attributeRangeChecker, environmentChecker); }
Code Sample 2:
public static String getDigest(String seed, String code) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed.getBytes("UTF-8")); byte[] passwordMD5Byte = md.digest(code.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); log.error(e); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); log.error(e); return null; } } |
11
| Code Sample 1:
public static void fixEol(File fin) throws IOException { File fout = File.createTempFile(fin.getName(), ".fixEol", fin.getParentFile()); FileChannel in = new FileInputStream(fin).getChannel(); if (0 != in.size()) { FileChannel out = new FileOutputStream(fout).getChannel(); byte[] eol = AStringUtilities.systemNewLine.getBytes(); ByteBuffer bufOut = ByteBuffer.allocateDirect(1024 * eol.length); boolean previousIsCr = false; ByteBuffer buf = ByteBuffer.allocateDirect(1024); while (in.read(buf) > 0) { buf.limit(buf.position()); buf.position(0); while (buf.remaining() > 0) { byte b = buf.get(); if (b == '\r') { previousIsCr = true; bufOut.put(eol); } else { if (b == '\n') { if (!previousIsCr) bufOut.put(eol); } else bufOut.put(b); previousIsCr = false; } } bufOut.limit(bufOut.position()); bufOut.position(0); out.write(bufOut); bufOut.clear(); buf.clear(); } out.close(); } in.close(); fin.delete(); fout.renameTo(fin); }
Code Sample 2:
public ResourceMigratorBuilder createResourceMigratorBuilder(NotificationReporter reporter) { return new ResourceMigratorBuilder() { public ResourceMigrator getCompletedResourceMigrator() { return new ResourceMigrator() { public void migrate(InputMetadata meta, InputStream inputStream, OutputCreator outputCreator) throws IOException, ResourceMigrationException { OutputStream outputStream = outputCreator.createOutputStream(); IOUtils.copy(inputStream, outputStream); } }; } public void setTarget(Version version) { } public void startType(String typeName) { } public void setRegexpPathRecogniser(String re) { } public void setCustomPathRecogniser(PathRecogniser pathRecogniser) { } public void addRegexpContentRecogniser(Version version, String re) { } public void addCustomContentRecogniser(Version version, ContentRecogniser contentRecogniser) { } public XSLStreamMigratorBuilder createXSLStreamMigratorBuilder() { return null; } public void addStep(Version inputVersion, Version outputVersion, StreamMigrator streamMigrator) { } public void endType() { } }; } |
11
| Code Sample 1:
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); int i; Vector images = new Vector(); images = dataBase.allImageSearch(); lengthOfTask = images.size() * 2; String directory = directoryPath + "Images" + myDirectory.separator; File newDirectoryFolder = new File(directory); newDirectoryFolder.mkdirs(); try { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); doc = domBuilder.newDocument(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Element dbElement = doc.createElement("dataBase"); for (i = 0; ((i < images.size()) && !stop); i++) { current = i; String element = (String) images.elementAt(i); String pathSrc = "Images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(myDirectory.separator) + 1, pathSrc.length()); String pathDst = directory + 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 keyWords = new Vector(); keyWords = dataBase.asociatedConceptSearch((String) images.elementAt(i)); Element imageElement = doc.createElement("image"); Element imageNameElement = doc.createElement("name"); imageNameElement.appendChild(doc.createTextNode(name)); imageElement.appendChild(imageNameElement); for (int j = 0; j < keyWords.size(); j++) { Element keyWordElement = doc.createElement("keyWord"); keyWordElement.appendChild(doc.createTextNode((String) keyWords.elementAt(j))); imageElement.appendChild(keyWordElement); } dbElement.appendChild(imageElement); } try { doc.appendChild(dbElement); File dst = new File(directory.concat("Images")); BufferedWriter bufferWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), "UTF-8")); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(bufferWriter); transformer.transform(source, result); bufferWriter.close(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } current = lengthOfTask; }
Code Sample 2:
public static void copiaAnexos(String from, String to, AnexoTO[] anexoTO) { FileChannel in = null, out = null; for (int i = 0; i < anexoTO.length; i++) { try { in = new FileInputStream(new File((uploadDiretorio.concat(from)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); out = new FileOutputStream(new File((uploadDiretorio.concat(to)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } |
11
| Code Sample 1:
public static String md5It(String data) { MessageDigest digest; String output = ""; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); byte[] hash = digest.digest(); for (byte b : hash) { output = output + String.format("%02X", b); } } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Authenticator.class.getName()).log(Level.SEVERE, null, ex); } return output; }
Code Sample 2:
public static byte[] SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return sha1hash; } |
11
| Code Sample 1:
public boolean authenticate() { if (empresaFeta == null) empresaFeta = new AltaEmpresaBean(); log.info("authenticating {0}", credentials.getUsername()); boolean bo; try { String passwordEncriptat = credentials.getPassword(); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(passwordEncriptat.getBytes(), 0, passwordEncriptat.length()); passwordEncriptat = new BigInteger(1, m.digest()).toString(16); Query q = entityManager.createQuery("select usuari from Usuaris usuari where usuari.login=? and usuari.password=?"); q.setParameter(1, credentials.getUsername()); q.setParameter(2, passwordEncriptat); Usuaris usuari = (Usuaris) q.getSingleResult(); bo = (usuari != null); if (bo) { if (usuari.isEsAdministrador()) { identity.addRole("admin"); } else { carregaDadesEmpresa(); log.info("nom de l'empresa: " + empresaFeta.getInstance().getNom()); } } } catch (Throwable t) { log.error(t); bo = false; } log.info("L'usuari {0} s'ha identificat bé? : {1} ", credentials.getUsername(), bo ? "si" : "no"); return bo; }
Code Sample 2:
private void LoadLoginInfo() { m_PwdList.removeAllElements(); String szTemp = null; int iIndex = 0; int iSize = m_UsrList.size(); for (int i = 0; i < iSize; i++) m_PwdList.add(""); try { if ((m_UsrList.size() > 0) && m_bSavePwd) { char[] MD5PWD = new char[80]; java.util.Arrays.fill(MD5PWD, (char) 0); java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-1"); String szPath = System.getProperty("user.home"); szPath += System.getProperty("file.separator") + "MochaJournal" + System.getProperty("file.separator") + "user.dat"; java.io.File file = new java.io.File(szPath); if (file.exists()) { java.io.FileInputStream br = new java.io.FileInputStream(file); byte[] szEncryptPwd = null; int iLine = 0; while (br.available() > 0) { md.reset(); md.update(((String) m_UsrList.get(iLine)).getBytes()); byte[] DESUSR = md.digest(); byte alpha = 0; for (int i2 = 0; i2 < DESUSR.length; i2++) alpha += DESUSR[i2]; iSize = br.read(); if (iSize > 0) { szEncryptPwd = new byte[iSize]; br.read(szEncryptPwd); char[] cPwd = new char[iSize]; for (int i = 0; i < iSize; i++) { int iChar = (int) szEncryptPwd[i] - (int) alpha; if (iChar < 0) iChar += 256; cPwd[i] = (char) iChar; } m_PwdList.setElementAt(new String(cPwd), iLine); } iLine++; } } } } catch (java.security.NoSuchAlgorithmException e) { System.err.println(e); } catch (java.io.IOException e3) { System.err.println(e3); } } |
11
| Code Sample 1:
public static String getDigest(String seed, String code) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed.getBytes("UTF-8")); byte[] passwordMD5Byte = md.digest(code.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); log.error(e); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); log.error(e); return null; } }
Code Sample 2:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try { URL url = new URL(upgradeURL); InputStream in = url.openStream(); BufferedInputStream buffIn = new BufferedInputStream(in); FileOutputStream out = new FileOutputStream(""); String bytes = ""; int data = buffIn.read(); int downloadedByteCount = 1; while (data != -1) { out.write(data); bytes.concat(Character.toString((char) data)); buffIn.read(); downloadedByteCount++; updateProgressBar(downloadedByteCount); } out.close(); buffIn.close(); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(bytes.getBytes()); String hash = m.digest().toString(); if (hash.length() == 31) { hash = "0" + hash; } if (!hash.equalsIgnoreCase(md5Hash)) { } } catch (MalformedURLException e) { } catch (IOException io) { } catch (NoSuchAlgorithmException a) { } } |
11
| Code Sample 1:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </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()); }
Code Sample 2:
public static void encrypt(File plain, File symKey, File ciphered, String algorithm) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { Key key = null; try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(symKey)); key = (Key) in.readObject(); } catch (IOException ioe) { KeyGenerator generator = KeyGenerator.getInstance(algorithm); key = generator.generateKey(); ObjectOutputStream out = new ObjectOutputStream(new java.io.FileOutputStream(symKey)); out.writeObject(key); out.close(); } Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getEncoded(), algorithm)); FileInputStream in = new FileInputStream(plain); CipherOutputStream out = new CipherOutputStream(new FileOutputStream(ciphered), cipher); byte[] buffer = new byte[4096]; for (int read = in.read(buffer); read > -1; read = in.read(buffer)) { out.write(buffer, 0, read); } out.close(); } |
00
| Code Sample 1:
public static void parseRDFXML(String url, StatementHandler handler) throws IOException { ARP parser = new ARP(); parser.getHandlers().setStatementHandler(handler); URLConnection conn = new URL(url).openConnection(); String encoding = conn.getContentEncoding(); InputStream in = null; try { in = conn.getInputStream(); if (encoding == null) parser.load(in, url); else parser.load(new InputStreamReader(in, encoding), url); in.close(); } catch (org.xml.sax.SAXException e) { throw new OntopiaRuntimeException(e); } finally { if (in != null) in.close(); } }
Code Sample 2:
@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; } |
00
| 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"); 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:
void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); } |
00
| Code Sample 1:
private void btnOkActionPerformed(java.awt.event.ActionEvent evt) { if (validateData()) { LoginUser me = AdministrationPanelView.getMe(); Connection dbConnection = null; try { DriverManager.registerDriver(new com.mysql.jdbc.Driver()); dbConnection = DriverManager.getConnection(me.getSqlReportsURL(), me.getSqlReportsUser(), me.getSqlReportsPassword()); dbConnection.setAutoCommit(false); dbConnection.setSavepoint(); String sql = "INSERT INTO campaigns (type, name, dateCreated, createdBy) VALUES (?, ?, ?, ?)"; PreparedStatement statement = dbConnection.prepareStatement(sql); statement.setByte(1, (optTypeAgents.isSelected()) ? CampaignStatics.CAMP_TYPE_AGENT : CampaignStatics.CAMP_TYPE_IVR); statement.setString(2, txtCampaignName.getText()); statement.setTimestamp(3, new Timestamp(Calendar.getInstance().getTime().getTime())); statement.setLong(4, me.getId()); statement.executeUpdate(); ResultSet rs = statement.getGeneratedKeys(); rs.next(); long campaignId = rs.getLong(1); sql = "INSERT INTO usercampaigns (userid, campaignid, role) VALUES (?, ?, ?)"; statement = dbConnection.prepareStatement(sql); statement.setLong(1, me.getId()); statement.setLong(2, campaignId); statement.setString(3, "admin"); statement.executeUpdate(); dbConnection.commit(); dbConnection.close(); CampaignAdmin ca = new CampaignAdmin(); ca.setCampaign(txtCampaignName.getText()); ca.setVisible(true); dispose(); } catch (SQLException ex) { try { dbConnection.rollback(); } catch (SQLException ex1) { Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex1); } JOptionPane.showMessageDialog(this.getRootPane(), ex.getLocalizedMessage(), "Error", JOptionPane.ERROR_MESSAGE); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex); } } }
Code Sample 2:
@Test public void testTrainingQuickprop() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_QUICKPROP); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); } |
11
| Code Sample 1:
public static void copyFile(final File source, final File target) throws FileNotFoundException, IOException { FileChannel in = new FileInputStream(source).getChannel(), out = new FileOutputStream(target).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } out.close(); in.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 static void main(String[] args) throws IOException { File inputFile = new File("D:/farrago.txt"); File outputFile = new File("D:/outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
Code Sample 2:
private static void downloadFile(String downloadFileName) throws Exception { URL getFileUrl = new URL("http://www.tegsoft.com/Tobe/getFile" + "?tegsoftFileName=" + downloadFileName); URLConnection getFileUrlConnection = getFileUrl.openConnection(); InputStream is = getFileUrlConnection.getInputStream(); String tobeHome = UiUtil.getParameter("RealPath.Context"); OutputStream out = new FileOutputStream(tobeHome + "/setup/" + downloadFileName); IOUtils.copy(is, out); is.close(); out.close(); } |
00
| Code Sample 1:
private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir, BackUpInfoFileGroup fileGroup, LinkedList<String> restoreList) { LinkedList<BackUpInfoFile> fileList = fileGroup.getFileList(); if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } for (int i = 0; i < fileList.size(); i++) { if (fileList.get(i).getId().equals(entry.getName())) { for (int j = 0; j < restoreList.size(); j++) { if ((fileList.get(i).getName() + "." + fileList.get(i).getType()).equals(restoreList.get(j))) { counter += 1; File outputFile = new File(outputDir, fileList.get(i).getName() + "." + fileList.get(i).getType()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream; BufferedOutputStream outputStream; try { inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (IOException ex) { throw new BackupException(ex.getMessage()); } } } } } }
Code Sample 2:
private static String getServiceResponse(final String requestName, final Template template, final Map variables) { OutputStreamWriter outputWriter = null; try { final StringWriter writer = new StringWriter(); final VelocityContext context = new VelocityContext(variables); template.merge(context, writer); final String request = writer.toString(); final URLConnection urlConnection = new URL(SERVICE_URL).openConnection(); urlConnection.setUseCaches(false); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2b4) Gecko/20091124 Firefox/3.6b4"); urlConnection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); urlConnection.setRequestProperty("Accept-Language", "en-us,en;q=0.5"); urlConnection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate"); urlConnection.setRequestProperty("Keep-Alive", "115"); urlConnection.setRequestProperty("Connection", "keep-alive"); urlConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); urlConnection.setRequestProperty("Content-Length", "" + request.length()); urlConnection.setRequestProperty("SOAPAction", requestName); outputWriter = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"); outputWriter.write(request); outputWriter.flush(); final InputStream result = urlConnection.getInputStream(); return IOUtils.toString(result); } catch (Exception ex) { throw new RuntimeException(ex); } finally { if (outputWriter != null) { try { outputWriter.close(); } catch (IOException logOrIgnore) { } } } } |
00
| Code Sample 1:
protected boolean store(Context context) throws DataStoreException, ServletException { Connection db = context.getConnection(); Statement st = null; String q = null; Integer subscriber = context.getValueAsInteger("subscriber"); int amount = 0; if (subscriber == null) { throw new DataAuthException("Don't know who moderator is"); } Object response = context.get("Response"); if (response == null) { throw new DataStoreException("Don't know what to moderate"); } else { Context scratch = (Context) context.clone(); TableDescriptor.getDescriptor("response", "response", scratch).fetch(scratch); Integer author = scratch.getValueAsInteger("author"); if (subscriber.equals(author)) { throw new SelfModerationException("You may not moderate your own responses"); } } context.put("moderator", subscriber); context.put("moderated", response); if (db != null) { try { st = db.createStatement(); q = "select mods from subscriber where subscriber = " + subscriber.toString(); ResultSet r = st.executeQuery(q); if (r.next()) { if (r.getInt("mods") < 1) { throw new DataAuthException("You have no moderation points left"); } } else { throw new DataAuthException("Don't know who moderator is"); } Object reason = context.get("reason"); q = "select score from modreason where modreason = " + reason; r = st.executeQuery(q); if (r.next()) { amount = r.getInt("score"); context.put("amount", new Integer(amount)); } else { throw new DataStoreException("Don't recognise reason (" + reason + ") to moderate"); } context.put(keyField, null); if (super.store(context, db)) { db.setAutoCommit(false); q = "update RESPONSE set Moderation = " + "( select sum( Amount) from MODERATION " + "where Moderated = " + response + ") " + "where Response = " + response; st.executeUpdate(q); q = "update subscriber set mods = mods - 1 " + "where subscriber = " + subscriber; st.executeUpdate(q); q = "select author from response " + "where response = " + response; r = st.executeQuery(q); if (r.next()) { int author = r.getInt("author"); if (author != 0) { int points = -1; if (amount > 0) { points = 1; } StringBuffer qb = new StringBuffer("update subscriber "); qb.append("set score = score + ").append(amount); qb.append(", mods = mods + ").append(points); qb.append(" where subscriber = ").append(author); st.executeUpdate(qb.toString()); } } db.commit(); } } catch (Exception e) { try { db.rollback(); } catch (Exception whoops) { throw new DataStoreException("Shouldn't happen: " + "failed to back out " + "failed insert: " + whoops.getMessage()); } throw new DataStoreException("Failed to store moderation: " + e.getMessage()); } finally { if (st != null) { try { st.close(); } catch (Exception noclose) { } context.releaseConnection(db); } } } return true; }
Code Sample 2:
private void getRandomGUID(boolean secure) throws NoSuchAlgorithmException { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); throw e; } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } |
00
| Code Sample 1:
public synchronized void run() { logger.info("SEARCH STARTED"); JSONObject json = null; logger.info("Opening urlConnection"); URLConnection connection = null; try { connection = url.openConnection(); connection.addRequestProperty("Referer", HTTP_REFERER); } catch (IOException e) { logger.warn("PROBLEM CONTACTING GOOGLE"); e.printStackTrace(); } String line; StringBuilder builder = new StringBuilder(); BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } } catch (IOException e) { logger.warn("PROBLEM RETREIVING DATA FROM GOOGLE"); e.printStackTrace(); } logger.info("Google RET: " + builder.toString()); try { json = new JSONObject(builder.toString()); json.append("query", q); } catch (JSONException e) { logger.warn("PROBLEM RETREIVING DATA FROM GOOGLE"); e.printStackTrace(); } sc.onSearchFinished(json); }
Code Sample 2:
protected void innerProcess(CrawlURI curi) throws InterruptedException { if (!curi.isHttpTransaction()) { return; } if (!TextUtils.matches("^text.*$", curi.getContentType())) { return; } long maxsize = DEFAULT_MAX_SIZE_BYTES.longValue(); try { maxsize = ((Long) getAttribute(curi, ATTR_MAX_SIZE_BYTES)).longValue(); } catch (AttributeNotFoundException e) { logger.severe("Missing max-size-bytes attribute when processing " + curi.toString()); } if (maxsize < curi.getContentSize() && maxsize > -1) { return; } String regexpr = ""; try { regexpr = (String) getAttribute(curi, ATTR_STRIP_REG_EXPR); } catch (AttributeNotFoundException e2) { logger.severe("Missing strip-reg-exp when processing " + curi.toString()); return; } ReplayCharSequence cs = null; try { cs = curi.getHttpRecorder().getReplayCharSequence(); } catch (Exception e) { curi.addLocalizedError(this.getName(), e, "Failed get of replay char sequence " + curi.toString() + " " + e.getMessage()); logger.warning("Failed get of replay char sequence " + curi.toString() + " " + e.getMessage() + " " + Thread.currentThread().getName()); return; } MessageDigest digest = null; try { try { digest = MessageDigest.getInstance(SHA1); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); return; } digest.reset(); String s = null; if (regexpr.length() == 0) { s = cs.toString(); } else { Matcher m = TextUtils.getMatcher(regexpr, cs); s = m.replaceAll(" "); TextUtils.recycleMatcher(m); } digest.update(s.getBytes()); byte[] newDigestValue = digest.digest(); if (logger.isLoggable(Level.FINEST)) { logger.finest("Recalculated content digest for " + curi.toString() + " old: " + Base32.encode((byte[]) curi.getContentDigest()) + ", new: " + Base32.encode(newDigestValue)); } curi.setContentDigest(SHA1, newDigestValue); } finally { if (cs != null) { try { cs.close(); } catch (IOException ioe) { logger.warning(TextUtils.exceptionToString("Failed close of ReplayCharSequence.", ioe)); } } } } |
00
| Code Sample 1:
@SuppressWarnings("static-access") public FastCollection<String> load(Link link) { URL url = null; FastCollection<String> links = new FastList<String>(); FTPClient ftp = null; try { String address = link.getURI(); address = JGetFileUtils.removeTrailingString(address, "/"); url = new URL(address); host = url.getHost(); String folder = url.getPath(); logger.info("Traversing: " + address); ftp = new FTPClient(host); if (!ftp.connected()) { ftp.connect(); } ftp.login("anonymous", "[email protected]"); logger.info("Connected to " + host + "."); logger.debug("changing dir to " + folder); ftp.chdir(folder); String[] files = ftp.dir(); for (String file : files) { links.add(address + "/" + file); } } catch (Exception e) { logger.error(e.getMessage()); logger.debug(e.getStackTrace()); } finally { try { ftp.quit(); } catch (Exception e) { logger.error("Failed to logout or disconnect from the ftp server: ftp://" + host); } } return links; }
Code Sample 2:
public void excluirTopico(Integer idDisciplina) throws Exception { String sql = "DELETE from topico WHERE id_disciplina = ?"; PreparedStatement stmt = null; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, idDisciplina); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } } |
00
| Code Sample 1:
public boolean createUser(String username, String password, String name) throws Exception { boolean user_created = false; try { statement = connect.prepareStatement("SELECT COUNT(*) from toepen.users WHERE username = ? LIMIT 1"); statement.setString(1, username); resultSet = statement.executeQuery(); resultSet.next(); if (resultSet.getInt(1) == 0) { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); long ctime = System.currentTimeMillis() / 1000; statement = connect.prepareStatement("INSERT INTO toepen.users " + "(username, password, name, ctime) " + "VALUES (?, ?, ?, ?)"); statement.setString(1, username); statement.setString(2, password_hash); statement.setString(3, name); statement.setLong(4, ctime); if (statement.executeUpdate() > 0) { user_created = true; } } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_created; } }
Code Sample 2:
private List getPluginClassList(List pluginFileList) { ArrayList l = new ArrayList(); for (Iterator i = pluginFileList.iterator(); i.hasNext(); ) { URL url = (URL) i.next(); log.debug("Trying file " + url.toString()); try { BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line; while ((line = r.readLine()) != null) { line = line.trim(); if (line.length() == 0 || line.charAt(0) == '#') continue; l.add(line); } } catch (Exception e) { log.warn("Could not load " + url, e); } } return l; } |
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"); 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:
public ProgramProfilingMessageSymbol deleteProfilingMessageSymbol(int id) throws AdaptationException { ProgramProfilingMessageSymbol profilingMessageSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramProfilingMessageSymbols " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete program profiling message " + "symbol failed."; log.error(msg); throw new AdaptationException(msg); } profilingMessageSymbol = getProfilingMessageSymbol(resultSet); query = "DELETE FROM ProgramProfilingMessageSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProfilingMessageSymbol"; 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 profilingMessageSymbol; } |
11
| Code Sample 1:
public void test2() throws Exception { SpreadsheetDocument document = new SpreadsheetDocument(); Sheet sheet = new Sheet("Planilha 1"); sheet.setLandscape(true); Row row = new Row(); row.setHeight(20); sheet.getMerges().add(new IntegerCellMerge(0, 0, 0, 5)); sheet.getImages().add(new Image(new FileInputStream("D:/image001.jpg"), 0, 0, ImageType.JPEG, 80, 60)); for (int i = 0; i < 10; i++) { Cell cell = new Cell(); cell.setValue("Celula " + i); cell.setBackgroundColor(new Color(192, 192, 192)); cell.setUnderline(true); cell.setBold(true); cell.setItalic(true); cell.setFont("Times New Roman"); cell.setFontSize(10); cell.setFontColor(new Color(255, 0, 0)); Border border = new Border(); border.setWidth(1); border.setColor(new Color(0, 0, 0)); cell.setLeftBorder(border); cell.setTopBorder(border); cell.setRightBorder(border); cell.setBottomBorder(border); row.getCells().add(cell); sheet.getColumnsWith().put(new Integer(i), new Integer(25)); } sheet.getRows().add(row); document.getSheets().add(sheet); FileOutputStream fos = new FileOutputStream("D:/teste2.xls"); SpreadsheetDocumentWriter writer = HSSFSpreadsheetDocumentWriter.getInstance(); writer.write(document, fos); fos.close(); }
Code Sample 2:
public static void copyFile(String fromPath, String toPath) { try { File inputFile = new File(fromPath); String dirImg = (new File(toPath)).getParent(); File tmp = new File(dirImg); if (!tmp.exists()) { tmp.mkdir(); } File outputFile = new File(toPath); 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()); } } |
11
| Code Sample 1:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
public static void zipDirectory(String dir, String zipfile) throws IOException, IllegalArgumentException { File d = new File(dir); if (!d.isDirectory()) throw new IllegalArgumentException("Not a directory: " + dir); String[] entries = d.list(); byte[] buffer = new byte[4096]; int bytesRead; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile)); for (int i = 0; i < entries.length; i++) { File f = new File(d, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getPath()); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); } |
11
| Code Sample 1:
public int update(BusinessObject o) throws DAOException { int update = 0; Project project = (Project) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("UPDATE_PROJECT")); pst.setString(1, project.getName()); pst.setString(2, project.getDescription()); pst.setInt(3, project.getIdAccount()); pst.setInt(4, project.getIdContact()); pst.setBoolean(5, project.isArchived()); pst.setInt(6, project.getId()); update = pst.executeUpdate(); if (update <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (update > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return update; }
Code Sample 2:
public void deleteUser(User portalUserBean, AuthSession authSession) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (portalUserBean.getUserId() == null) throw new IllegalArgumentException("id of portal user is null"); String sql = "update WM_LIST_USER " + "set is_deleted=1 " + "where ID_USER=? and is_deleted = 0 and ID_FIRM in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedCompanyId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_FIRM from v$_read_list_firm z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); int num = 1; ps.setLong(num++, portalUserBean.getUserId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(num++, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) { dbDyn.rollback(); } } catch (Exception e001) { } String es = "Error delete of portal user"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } |
00
| Code Sample 1:
public void init() { this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS); try { if (memeId < 0) { } else { conurl = new URL(ServerURL + "?meme_id=" + memeId); java.io.InputStream xmlstr = conurl.openStream(); this.removeAllWorkSheets(); this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_EXPLICIT); this.setStringEncodingMode(WorkBookHandle.STRING_ENCODING_UNICODE); this.setDupeStringMode(WorkBookHandle.SHAREDUPES); ExtenXLS.parseNBind(this, xmlstr); this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS); } } catch (Exception ex) { throw new WorkBookException("Error while connecting to: " + ServerURL + ":" + ex.toString(), WorkBookException.RUNTIME_ERROR); } }
Code Sample 2:
private void copy(File fin, File fout) throws IOException { FileOutputStream out = new FileOutputStream(fout); FileInputStream in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } in.close(); out.close(); } |
11
| Code Sample 1:
public static void copy(File source, File dest) throws BuildException { dest = new File(dest, source.getName()); if (source.isFile()) { byte[] buffer = new byte[4096]; FileInputStream fin = null; FileOutputStream fout = null; try { fin = new FileInputStream(source); fout = new FileOutputStream(dest); int count = 0; while ((count = fin.read(buffer)) > 0) fout.write(buffer, 0, count); fin.close(); fout.close(); } catch (IOException ex) { throw new BuildException(ex); } finally { try { if (fin != null) fin.close(); } catch (IOException ex) { } try { if (fout != null) fout.close(); } catch (IOException ex) { } } } else { dest.mkdirs(); File[] children = source.listFiles(); for (File child : children) copy(child, dest); } }
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 static String encrypt(String x) throws Exception { MessageDigest mdEnc = MessageDigest.getInstance("SHA-1"); mdEnc.update(x.getBytes(), 0, x.length()); String md5 = new BigInteger(1, mdEnc.digest()).toString(16); return md5; }
Code Sample 2:
public static String md5(String plainText) { String ret = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } ret = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ret; } |
11
| Code Sample 1:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
@Override public void sendData(String serverUrl, String fileName, String type, InputStream is) throws IOException { ClientSession clientSession = null; try { if (logger.isDebugEnabled()) { logger.debug("Connecting to " + serverUrl); } clientSession = (ClientSession) Connector.open(serverUrl); HeaderSet hsConnectReply = clientSession.connect(clientSession.createHeaderSet()); if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) { throw new IOException("Connect Error " + hsConnectReply.getResponseCode()); } HeaderSet hsOperation = clientSession.createHeaderSet(); hsOperation.setHeader(HeaderSet.NAME, fileName); if (type != null) { hsOperation.setHeader(HeaderSet.TYPE, type); } hsOperation.setHeader(HeaderSet.LENGTH, new Long(is.available())); Operation po = clientSession.put(hsOperation); OutputStream os = po.openOutputStream(); IOUtils.copy(is, os); os.flush(); os.close(); if (logger.isDebugEnabled()) { logger.debug("put responseCode " + po.getResponseCode()); } po.close(); HeaderSet hsDisconnect = clientSession.disconnect(null); if (logger.isDebugEnabled()) { logger.debug("disconnect responseCode " + hsDisconnect.getResponseCode()); } if (hsDisconnect.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) { throw new IOException("Send Error " + hsConnectReply.getResponseCode()); } } finally { if (clientSession != null) { try { clientSession.close(); } catch (IOException ignore) { if (logger.isDebugEnabled()) { logger.debug("IOException during clientSession.close()", ignore); } } } clientSession = null; } } |
11
| Code Sample 1:
public static void copyFile(File src, File dest) { try { FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ioe) { System.err.println(ioe); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } |
00
| Code Sample 1:
private static void copyFile(String from, String to) throws IOException { FileReader in = new FileReader(from); FileWriter out = new FileWriter(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
Code Sample 2:
private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } } |
11
| Code Sample 1:
private static MyCookieData parseCookie(Cookie cookie) throws CookieException { String value = cookie.getValue(); System.out.println("original cookie: " + value); value = value.replace("%3A", ":"); value = value.replace("%40", "@"); System.out.println("cookie after replacement: " + value); String[] parts = value.split(":"); if (parts.length < 4) throw new CookieException("only " + parts.length + " parts in the cookie! " + value); String email = parts[0]; String nickname = parts[1]; boolean admin = Boolean.getBoolean(parts[2].toLowerCase()); String hsh = parts[3]; boolean valid_cookie = true; String cookie_secret = System.getProperty("COOKIE_SECRET"); if (cookie_secret == "") throw new CookieException("cookie secret is not set"); if (email.equals("")) { System.out.println("email is empty!"); nickname = ""; admin = false; } else { try { MessageDigest sha = MessageDigest.getInstance("SHA"); sha.update((email + nickname + admin + cookie_secret).getBytes()); StringBuilder builder = new StringBuilder(); for (byte b : sha.digest()) { byte tmphigh = (byte) (b >> 4); tmphigh = (byte) (tmphigh & 0xf); builder.append(hextab.charAt(tmphigh)); byte tmplow = (byte) (b & 0xf); builder.append(hextab.charAt(tmplow)); } System.out.println(); String vhsh = builder.toString(); if (!vhsh.equals(hsh)) { System.out.println("hash not same!"); System.out.println("hash passed in: " + hsh); System.out.println("hash generated: " + vhsh); valid_cookie = false; } else System.out.println("cookie match!"); } catch (NoSuchAlgorithmException ex) { } } return new MyCookieData(email, admin, nickname, valid_cookie); }
Code Sample 2:
public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; } |
00
| Code Sample 1:
protected String encrypt(final String data, final String key) throws CryptographicFailureException { Validate.notNull(data, "Provided data cannot be null."); Validate.notNull(key, "Provided key name cannot be null."); final PublicKey pk = getPublicKey(key); if (pk == null) { throw new CryptographicFailureException("PublicKeyNotFound", String.format("Cannot find public key '%s'", key)); } try { final Cipher cipher = Cipher.getInstance(pk.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, pk); final ByteArrayInputStream bin = new ByteArrayInputStream(data.getBytes()); final CipherInputStream cin = new CipherInputStream(bin, cipher); final ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(cin, bout); return new String(Base64.encodeBase64(bout.toByteArray())); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(String.format("Cannot find instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (NoSuchPaddingException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (InvalidKeyException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (IOException e) { throw new IllegalStateException("Cannot build in-memory cipher copy", e); } }
Code Sample 2:
public static void readUrlWriteFileTest(String url, String fileName) throws Exception { System.out.println("Initiated reading source queue URL: " + url); InputStream instream = new URL(url).openStream(); Serializer serializer = new Serializer(); Response response = (Response) serializer.parse(instream); Queue queue = response.getQueue(); instream.close(); System.out.println("Completed reading source queue URL (jobs=" + queue.size() + ")"); System.out.println("Initiated writing target queue File: " + fileName); OutputStream outstream = new FileOutputStream(fileName); serializer.write(response, outstream); outstream.close(); System.out.println("Completed writing target queue file."); } |
11
| Code Sample 1:
private boolean copyFile(File file) throws Exception { destination = new File(ServiceLocator.getSqliteDir(), file.getName()); logger.debug("Writing to: " + destination); if (destination.exists()) { Frame.showMessage(ServiceLocator.getText("Error.file.exists") + file.getName(), null); logger.debug("File already exists: " + file); return false; } destination.createNewFile(); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(file); out = new FileOutputStream(destination); int read = 0; byte[] buffer = new byte[2048]; while ((read = in.read(buffer)) > 0) { out.write(buffer, 0, read); } } finally { if (in != null) in.close(); if (out != null) out.close(); } return true; }
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:
private ArrayList<XSPFTrackInfo> getPlaylist() { try { Log.d(TAG, "Getting playlist started"); String urlString = "http://" + mBaseURL + "/xspf.php?sk=" + mSession + "&discovery=0&desktop=1.4.1.57486"; if (mAlternateConn) { urlString += "&api_key=9d1bbaef3b443eb97973d44181d04e4b"; Log.d(TAG, "Using alternate connection method"); } URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); DocumentBuilderFactory dbFac = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbFac.newDocumentBuilder(); Document doc = db.parse(is); Element root = doc.getDocumentElement(); NodeList titleNs = root.getElementsByTagName("title"); String stationName = "<unknown station>"; if (titleNs.getLength() > 0) { Element titleElement = (Element) titleNs.item(0); String res = ""; for (int i = 0; i < titleElement.getChildNodes().getLength(); i++) { Node item = titleElement.getChildNodes().item(i); if (item.getNodeType() == Node.TEXT_NODE) res += item.getNodeValue(); } stationName = URLDecoder.decode(res, "UTF-8"); } NodeList tracks = doc.getElementsByTagName("track"); ArrayList<XSPFTrackInfo> result = new ArrayList<XSPFTrackInfo>(); for (int i = 0; i < tracks.getLength(); i++) try { result.add(new XSPFTrackInfo(stationName, (Element) tracks.item(i))); } catch (Utils.ParseException e) { Log.e(TAG, "in getPlaylist", e); return null; } Log.d(TAG, "Getting playlist successful"); return result; } catch (Exception e) { Log.e(TAG, "in getPlaylist", e); return null; } }
Code Sample 2:
public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } } |
00
| Code Sample 1:
private static byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(frase.getBytes()); return md.digest(); } catch (Exception e) { return null; } }
Code Sample 2:
public void access() { Authenticator.setDefault(new MyAuthenticator()); try { URL url = new URL("http://localhost/ws/test"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } } |
00
| Code Sample 1:
private InputStream fetch(String urlString) throws MalformedURLException, IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet request = new HttpGet(urlString); HttpResponse response = httpClient.execute(request); return response.getEntity().getContent(); }
Code Sample 2:
protected void update(String sql, Object[] args) { Connection conn = null; PreparedStatement pstmt = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); pstmt = conn.prepareStatement(sql); this.setParameters(pstmt, args); pstmt.executeUpdate(); conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { try { if (conn != null) { conn.rollback(); conn.setAutoCommit(true); } } catch (SQLException ex) { ex.printStackTrace(); } throw new JdbcDaoException(e.getMessage(), e); } finally { JdbcUtils.free(pstmt, conn); } } |
00
| Code Sample 1:
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); } }
Code Sample 2:
public static void main(String argv[]) { try { if (argv.length != 1 && argv.length != 3) { usage(); System.exit(1); } URL url = new URL(argv[0]); URLConnection conn; conn = url.openConnection(); if (conn.getHeaderField("WWW-Authenticate") != null) { auth(conn, argv[1], argv[2]); } else { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) System.out.println(line); } } catch (Exception ex) { ex.printStackTrace(); } } |
11
| Code Sample 1:
public static void copy(final File source, final File dest) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); dest.setLastModified(source.lastModified()); } finally { close(in); close(out); } }
Code Sample 2:
public static boolean copyFile(final String src, final String dest) { if (fileExists(src)) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); return true; } catch (IOException e) { Logger.getAnonymousLogger().severe(e.getLocalizedMessage()); } } return false; } |
00
| Code Sample 1:
public void retrieveChallenges(int num) throws MalformedURLException, IOException, FBErrorException, FBConnectionException { if (num < 1 || num > 100) { error = true; FBErrorException fbee = new FBErrorException(); fbee.setErrorCode(-100); fbee.setErrorText("Invalid GetChallenges range"); throw fbee; } URL url = new URL(getHost() + getPath()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("X-FB-User", getUser()); conn.setRequestProperty("X-FB-Mode", "GetChallenges"); conn.setRequestProperty("X-FB-GetChallenges.Qty", new Integer(num).toString()); conn.connect(); Element fbresponse; try { fbresponse = readXML(conn); } catch (FBConnectionException fbce) { error = true; throw fbce; } catch (FBErrorException fbee) { error = true; throw fbee; } catch (Exception e) { error = true; FBConnectionException fbce = new FBConnectionException("XML parsing failed"); fbce.attachSubException(e); throw fbce; } NodeList nl = fbresponse.getElementsByTagName("GetChallengesResponse"); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof Element && hasError((Element) nl.item(i))) { error = true; FBErrorException e = new FBErrorException(); e.setErrorCode(errorcode); e.setErrorText(errortext); throw e; } } NodeList challenge = fbresponse.getElementsByTagName("Challenge"); for (int i = 0; i < challenge.getLength(); i++) { NodeList children = challenge.item(i).getChildNodes(); for (int j = 0; j < children.getLength(); j++) { if (children.item(j) instanceof Text) { challenges.offer(children.item(j).getNodeValue()); } } } }
Code Sample 2:
public static String digestString(String data, String algorithm) { String result = null; if (data != null) { try { MessageDigest _md = MessageDigest.getInstance(algorithm); _md.update(data.getBytes()); byte[] _digest = _md.digest(); String _ds; _ds = toHexString(_digest, 0, _digest.length); result = _ds; } catch (NoSuchAlgorithmException e) { result = null; } } return result; } |
00
| Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; } |
11
| Code Sample 1:
public void criarTopicoQuestao(Questao q, Integer idTopico) throws SQLException { PreparedStatement stmt = null; String sql = "INSERT INTO questao_topico (id_questao, id_disciplina, id_topico) VALUES (?,?,?)"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.setInt(2, q.getDisciplina().getIdDisciplina()); stmt.setInt(3, idTopico); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } }
Code Sample 2:
public boolean crear() { int result = 0; String sql = "insert into ronda" + "(divisionxTorneo_idDivisionxTorneo, fechaRonda, nRonda, estado ) " + "values (?, ?, ?, ?)"; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement(unaRonda); 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); } |
00
| Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public String encodePassword(String rawPass, Object salt) { MessageDigest sha; try { sha = MessageDigest.getInstance("SHA"); } catch (java.security.NoSuchAlgorithmException e) { throw new LdapDataAccessException("No SHA implementation available!"); } sha.update(rawPass.getBytes()); if (salt != null) { Assert.isInstanceOf(byte[].class, salt, "Salt value must be a byte array"); sha.update((byte[]) salt); } byte[] hash = combineHashAndSalt(sha.digest(), (byte[]) salt); return (salt == null ? SHA_PREFIX : SSHA_PREFIX) + new String(Base64.encodeBase64(hash)); } |
11
| Code Sample 1:
public int delete(BusinessObject o) throws DAOException { int delete = 0; Item item = (Item) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_ITEM")); pst.setInt(1, item.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; }
Code Sample 2:
public int update(BusinessObject o) throws DAOException { int update = 0; Item item = (Item) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("UPDATE_ITEM")); pst.setString(1, item.getDescription()); pst.setDouble(2, item.getUnit_price()); pst.setInt(3, item.getQuantity()); pst.setDouble(4, item.getVat()); pst.setInt(5, item.getIdProject()); if (item.getIdBill() == 0) pst.setNull(6, java.sql.Types.INTEGER); else pst.setInt(6, item.getIdBill()); pst.setInt(7, item.getIdCurrency()); pst.setInt(8, item.getId()); System.out.println("item => " + item.getDescription() + " " + item.getUnit_price() + " " + item.getQuantity() + " " + item.getVat() + " " + item.getIdProject() + " " + item.getIdBill() + " " + item.getIdCurrency() + " " + item.getId()); update = pst.executeUpdate(); if (update <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (update > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return update; } |
00
| Code Sample 1:
public void downSync(Vector v) throws SQLException { try { con = allocateConnection(tableName); PreparedStatement update = con.prepareStatement("update cal_Event set owner=?,subject=?,text=?,place=?," + "contactperson=?,startdate=?,enddate=?,starttime=?,endtime=?,allday=?," + "syncstatus=?,dirtybits=? where OId=? and syncstatus=?"); PreparedStatement insert = con.prepareStatement("insert into cal_Event (owner,subject,text,place," + "contactperson,startdate,enddate,starttime,endtime,allday,syncstatus," + "dirtybits) values(?,?,?,?,?,?,?,?,?,?,?,?)"); PreparedStatement insert1 = con.prepareStatement(DBUtil.getQueryCurrentOID(con, "cal_Event", "newoid")); PreparedStatement delete1 = con.prepareStatement("delete from cal_Event_Remind where event=?"); PreparedStatement delete2 = con.prepareStatement("delete from cal_Event where OId=? " + "and (syncstatus=? or syncstatus=?)"); for (int i = 0; i < v.size(); i++) { try { DO = (EventDO) v.elementAt(i); if (DO.getSyncstatus() == INSERT) { insert.setBigDecimal(1, DO.getOwner()); insert.setString(2, DO.getSubject()); insert.setString(3, DO.getText()); insert.setString(4, DO.getPlace()); insert.setString(5, DO.getContactperson()); insert.setDate(6, DO.getStartdate()); insert.setDate(7, DO.getEnddate()); insert.setTime(8, DO.getStarttime()); insert.setTime(9, DO.getEndtime()); insert.setBoolean(10, DO.getAllday()); insert.setInt(11, RESET); insert.setInt(12, RESET); con.executeUpdate(insert, null); con.reset(); rs = con.executeQuery(insert1, null); if (rs.next()) DO.setOId(rs.getBigDecimal("newoid")); con.reset(); } else if (DO.getSyncstatus() == UPDATE) { update.setBigDecimal(1, DO.getOwner()); update.setString(2, DO.getSubject()); update.setString(3, DO.getText()); update.setString(4, DO.getPlace()); update.setString(5, DO.getContactperson()); update.setDate(6, DO.getStartdate()); update.setDate(7, DO.getEnddate()); update.setTime(8, DO.getStarttime()); update.setTime(9, DO.getEndtime()); update.setBoolean(10, DO.getAllday()); update.setInt(11, RESET); update.setInt(12, RESET); update.setBigDecimal(13, DO.getOId()); update.setInt(14, RESET); con.executeUpdate(update, null); con.reset(); } else if (DO.getSyncstatus() == DELETE) { try { con.setAutoCommit(false); delete1.setBigDecimal(1, DO.getOId()); con.executeUpdate(delete1, null); delete2.setBigDecimal(1, DO.getOId()); delete2.setInt(2, RESET); delete2.setInt(3, DELETE); if (con.executeUpdate(delete2, null) < 1) { con.rollback(); } else { con.commit(); } } catch (Exception e) { con.rollback(); throw e; } finally { con.reset(); } } } catch (Exception e) { if (DO != null) logError("Sync-EventDO.owner = " + DO.getOwner().toString() + " oid = " + (DO.getOId() != null ? DO.getOId().toString() : "NULL"), e); } } if (rs != null) { rs.close(); } } catch (SQLException e) { if (DEBUG) logError("", e); throw e; } finally { release(); } }
Code Sample 2:
public static String[] readStats() throws Exception { URL url = null; BufferedReader reader = null; StringBuilder stringBuilder; try { url = new URL("http://localhost:" + port + webctx + "/shared/js/libOO/health_check.sjs"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(10 * 1000); connection.connect(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); stringBuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } return stringBuilder.toString().split(","); } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } } |
11
| Code Sample 1:
public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException { if (format != null && "gif".equals(format.toLowerCase())) { resize(originalFile, resizedFile, width, 1); return; } FileInputStream fis = new FileInputStream(originalFile); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int readLength = -1; int bufferSize = 1024; byte bytes[] = new byte[bufferSize]; while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) { byteStream.write(bytes, 0, readLength); } byte[] in = byteStream.toByteArray(); fis.close(); byteStream.close(); Image inputImage = Toolkit.getDefaultToolkit().createImage(in); waitForImage(inputImage); int imageWidth = inputImage.getWidth(null); if (imageWidth < 1) throw new IllegalArgumentException("image width " + imageWidth + " is out of range"); int imageHeight = inputImage.getHeight(null); if (imageHeight < 1) throw new IllegalArgumentException("image height " + imageHeight + " is out of range"); int height = -1; double scaleW = (double) imageWidth / (double) width; double scaleY = (double) imageHeight / (double) height; if (scaleW >= 0 && scaleY >= 0) { if (scaleW > scaleY) { height = -1; } else { width = -1; } } Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT); checkImage(outputImage); encode(new FileOutputStream(resizedFile), outputImage, format); }
Code Sample 2:
public static void createBackup() { String workspacePath = Workspace.INSTANCE.getWorkspace(); if (workspacePath.length() == 0) return; workspacePath += "/"; String backupPath = workspacePath + "Backup"; File directory = new File(backupPath); if (!directory.exists()) directory.mkdirs(); String dateString = DataUtils.DateAndTimeOfNowAsLocalString(); dateString = dateString.replace(" ", "_"); dateString = dateString.replace(":", ""); backupPath += "/Backup_" + dateString + ".zip"; ArrayList<String> backupedFiles = new ArrayList<String>(); backupedFiles.add("Database/Database.properties"); backupedFiles.add("Database/Database.script"); FileInputStream in; byte[] data = new byte[1024]; int read = 0; try { ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(backupPath)); zip.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < backupedFiles.size(); i++) { String backupedFile = backupedFiles.get(i); try { File inFile = new File(workspacePath + backupedFile); if (inFile.exists()) { in = new FileInputStream(workspacePath + backupedFile); if (in != null) { ZipEntry entry = new ZipEntry(backupedFile); zip.putNextEntry(entry); while ((read = in.read(data, 0, 1024)) != -1) zip.write(data, 0, read); zip.closeEntry(); in.close(); } } } catch (Exception e) { Logger.logError(e, "Error during file backup:" + backupedFile); } } zip.close(); } catch (IOException ex) { Logger.logError(ex, "Error during backup"); } } |
00
| Code Sample 1:
public static void copyFiles(String strPath, String dstPath) throws IOException { File src = new File(strPath); File dest = new File(dstPath); if (src.isDirectory()) { dest.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { String dest1 = dest.getAbsolutePath() + File.separatorChar + list[i]; String src1 = src.getAbsolutePath() + File.separatorChar + list[i]; copyFiles(src1, dest1); } } else { FileInputStream fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } }
Code Sample 2:
private synchronized void persist() { Connection conn = null; try { PoolManager pm = PoolManager.getInstance(); conn = pm.getConnection(JukeXTrackStore.DB_NAME); conn.setAutoCommit(false); Statement state = conn.createStatement(); state.executeUpdate("DELETE FROM PlaylistEntry WHERE playlistid=" + this.id); if (this.size() > 0) { StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO PlaylistEntry ( playlistid , trackid , position ) VALUES "); int location = 0; Iterator i = ll.iterator(); while (i.hasNext()) { long currTrackID = ((DatabaseObject) i.next()).getId(); sql.append('(').append(this.id).append(',').append(currTrackID).append(',').append(location++).append(')'); if (i.hasNext()) sql.append(','); } state.executeUpdate(sql.toString()); } conn.commit(); conn.setAutoCommit(true); state.close(); } catch (SQLException se) { try { conn.rollback(); } catch (SQLException ignore) { } log.error("Encountered an error persisting a playlist", se); } finally { try { conn.close(); } catch (SQLException ignore) { } } } |
00
| Code Sample 1:
private List _getWeathersFromYahoo(String city) { System.out.println("== get weather information of " + city + " from yahoo =="); try { URL url = new URL(URL + cities.get(city).toString()); InputStream input = url.openStream(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); SAXParser parser = factory.newSAXParser(); YahooHandler yh = new YahooHandler(); yh.setCity(city); parser.parse(input, yh); return yh.getWeathers(); } catch (MalformedURLException e) { throw new WeatherException("MalformedURLException"); } catch (IOException e) { throw new WeatherException("无法读取数据。"); } catch (ParserConfigurationException e) { throw new WeatherException("ParserConfigurationException"); } catch (SAXException e) { throw new WeatherException("数据格式错误,无法解析。"); } }
Code Sample 2:
public void loadSourceCode() { if (getResourceName() != null) { String filename = getResourceName() + ".java"; sourceCode = new String("<html><body bgcolor=\"#ffffff\"><pre>"); InputStream is; InputStreamReader isr; CodeViewer cv = new CodeViewer(); URL url; try { url = getClass().getResource(filename); is = url.openStream(); isr = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isr); String line = reader.readLine(); while (line != null) { sourceCode += cv.syntaxHighlight(line) + " \n "; line = reader.readLine(); } sourceCode += new String("</pre></body></html>"); } catch (Exception ex) { sourceCode = "Could not load file: " + filename; } } } |
11
| Code Sample 1:
public static void putNextJarEntry(JarOutputStream modelStream, String name, File file) throws IOException { JarEntry entry = new JarEntry(name); entry.setSize(file.length()); modelStream.putNextEntry(entry); InputStream fileStream = new BufferedInputStream(new FileInputStream(file)); IOUtils.copy(fileStream, modelStream); fileStream.close(); }
Code Sample 2:
private static void copyFile(String srFile, String dtFile) { try { File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1); OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } catch (FileNotFoundException ex) { System.out.println("Error copying " + srFile + " to " + dtFile); System.out.println(ex.getMessage() + " in the specified directory."); } catch (IOException e) { System.out.println(e.getMessage()); } } |
00
| Code Sample 1:
private static void copySmallFile(File sourceFile, File targetFile) throws BusinessException { LOG.debug("Copying SMALL file '" + sourceFile.getAbsolutePath() + "' to '" + targetFile.getAbsolutePath() + "'."); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(sourceFile).getChannel(); outChannel = new FileOutputStream(targetFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new BusinessException("Could not copy file from '" + sourceFile.getAbsolutePath() + "' to '" + targetFile.getAbsolutePath() + "'!", e); } finally { try { if (inChannel != null) inChannel.close(); } catch (IOException e) { LOG.error("Could not close input stream!", e); } try { if (outChannel != null) outChannel.close(); } catch (IOException e) { LOG.error("Could not close output stream!", e); } } }
Code Sample 2:
private synchronized void configure() { final Map res = new HashMap(); try { final Enumeration resources = getConfigResources(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); while (resources.hasMoreElements()) { final URL url = (URL) resources.nextElement(); DefaultHandler saxHandler = new DefaultHandler() { private Group group; private StringBuffer tagContent = new StringBuffer(); public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("group".equals(qName)) { group = new Group(attributes.getValue("name")); String minimizeJs = attributes.getValue("minimize"); String minimizeCss = attributes.getValue("minimizeCss"); group.setMinimize(!"false".equals(minimizeJs)); group.setMinimizeCss("true".equals(minimizeCss)); } else if ("js".equals(qName) || "css".equals(qName) || "group-ref".equals(qName)) tagContent.setLength(0); } public void characters(char ch[], int start, int length) throws SAXException { tagContent.append(ch, start, length); } public void endElement(String uri, String localName, String qName) throws SAXException { if ("group".equals(qName)) res.put(group.getName(), group); else if ("js".equals(qName)) group.getJsNames().add(tagContent.toString()); else if ("css".equals(qName)) group.getCssNames().add(tagContent.toString()); else if ("group-ref".equals(qName)) { String name = tagContent.toString(); Group subGroup = (Group) res.get(name); if (subGroup == null) throw new RuntimeException("Error parsing " + url.toString() + " <group-ref>" + name + "</group-ref> unknown"); group.getSubgroups().add(subGroup); } } }; try { saxParser.parse(url.openStream(), saxHandler); } catch (Throwable e) { log.warn(e.toString(), e); log.warn("Exception " + e.toString() + " ignored, let's move on.."); } } configurationFilesMaxModificationTime = findMaxConfigModificationTime(); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } this.groups = res; } |
11
| Code Sample 1:
public static String toMd5(String s) { String res = ""; try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); res = toHexString(messageDigest); } catch (NoSuchAlgorithmException e) { } return res; }
Code Sample 2:
private static String md5(String pwd) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(pwd.getBytes(), 0, pwd.length()); return new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new Error(); } } |
11
| Code Sample 1:
public CmsSetupTestResult execute(CmsSetupBean setupBean) { CmsSetupTestResult testResult = new CmsSetupTestResult(this); String basePath = setupBean.getWebAppRfsPath(); if (!basePath.endsWith(File.separator)) { basePath += File.separator; } File file1; Random rnd = new Random(); do { file1 = new File(basePath + "test" + rnd.nextInt(1000)); } while (file1.exists()); boolean success = false; try { file1.createNewFile(); FileWriter fw = new FileWriter(file1); fw.write("aA1"); fw.close(); success = true; FileReader fr = new FileReader(file1); success = success && (fr.read() == 'a'); success = success && (fr.read() == 'A'); success = success && (fr.read() == '1'); success = success && (fr.read() == -1); fr.close(); success = file1.delete(); success = !file1.exists(); } catch (Exception e) { success = false; } if (!success) { testResult.setRed(); testResult.setInfo("OpenCms cannot be installed without read and write privileges for path " + basePath + "! Please check you are running your servlet container with the right user and privileges."); testResult.setHelp("Not enough permissions to create/read/write a file"); testResult.setResult(RESULT_FAILED); } else { testResult.setGreen(); testResult.setResult(RESULT_PASSED); } return testResult; }
Code Sample 2:
public static void copyAssetFile(Context ctx, String srcFileName, String targetFilePath) { AssetManager assetManager = ctx.getAssets(); try { InputStream is = assetManager.open(srcFileName); File out = new File(targetFilePath); if (!out.exists()) { out.getParentFile().mkdirs(); out.createNewFile(); } OutputStream os = new FileOutputStream(out); IOUtils.copy(is, os); is.close(); os.close(); } catch (IOException e) { AIOUtils.log("error when copyAssetFile", e); } } |
00
| Code Sample 1:
public static void copyFile(File src, File dest) throws IOException, IllegalArgumentException { if (src.isDirectory()) throw new IllegalArgumentException("Source file is a directory"); if (dest.isDirectory()) throw new IllegalArgumentException("Destination file is a directory"); int bufferSize = 4 * 1024; InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest); byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) out.write(buffer, 0, bytesRead); out.close(); in.close(); }
Code Sample 2:
private void downloadFile(String name, URL url, File file) throws IOException { InputStream in = null; FileOutputStream out = null; try { URLConnection conn = url.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); int expectedSize = conn.getContentLength(); progressPanel.downloadStarting(name, expectedSize == -1); int downloaded = 0; byte[] buf = new byte[1024]; int length; in = conn.getInputStream(); out = new FileOutputStream(file); while ((in != null) && ((length = in.read(buf)) != -1)) { downloaded += length; out.write(buf, 0, length); if (expectedSize != -1) progressPanel.downloadProgress((downloaded * 100) / expectedSize); } out.flush(); } finally { progressPanel.downloadFinished(); if (out != null) out.close(); if (in != null) in.close(); } } |
11
| Code Sample 1:
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!"); } }
Code Sample 2:
private String md5(String txt) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(txt.getBytes(), 0, txt.length()); return new BigInteger(1, m.digest()).toString(16); } catch (Exception e) { return "BAD MD5"; } } |
00
| Code Sample 1:
public static String hash(String arg) throws NoSuchAlgorithmException { String input = arg; String output; MessageDigest md = MessageDigest.getInstance("SHA"); md.update(input.getBytes()); output = Hex.encodeHexString(md.digest()); return output; }
Code Sample 2:
public void executaAlteracoes() { Album album = Album.getAlbum(); Photo[] fotos = album.getFotos(); Photo f; int ultimoFotoID = -1; int albumID = album.getAlbumID(); sucesso = true; PainelWebFotos.setCursorWait(true); albumID = recordAlbumData(album, albumID); sucesso = recordFotoData(fotos, ultimoFotoID, albumID); String caminhoAlbum = Util.getFolder("albunsRoot").getPath() + File.separator + albumID; File diretorioAlbum = new File(caminhoAlbum); if (!diretorioAlbum.isDirectory()) { if (!diretorioAlbum.mkdir()) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.7]/ERRO: diretorio " + caminhoAlbum + " n�o pode ser criado. abortando"); return; } } for (int i = 0; i < fotos.length; i++) { f = fotos[i]; if (f.getCaminhoArquivo().length() > 0) { try { FileChannel canalOrigem = new FileInputStream(f.getCaminhoArquivo()).getChannel(); FileChannel canalDestino = new FileOutputStream(caminhoAlbum + File.separator + f.getFotoID() + ".jpg").getChannel(); canalDestino.transferFrom(canalOrigem, 0, canalOrigem.size()); canalOrigem = null; canalDestino = null; } catch (Exception e) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.8]/ERRO: " + e); sucesso = false; } } } prepareThumbsAndFTP(fotos, albumID, caminhoAlbum); prepareExtraFiles(album, caminhoAlbum); fireChangesToGUI(fotos); dispatchAlbum(); PainelWebFotos.setCursorWait(false); } |
11
| Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files, int label, String charset) throws FilesException { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { if ((files == null) || (files.size() <= 0)) { return; } if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } Users user = getUser(hsession, repositoryName); Identity identity = getDefaultIdentity(hsession, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); for (int i = 0; i < files.size(); i++) { MultiPartEmail email = email = new MultiPartEmail(); email.setCharset(charset); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if (_to != null) { email.addTo(_to.getAddress(), _to.getPersonal()); } MailPartObj obj = (MailPartObj) files.get(i); email.setSubject("Files-System " + obj.getName()); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); email.attach(attachment); String mid = getId(); email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader("X-DBox", "FILES"); email.addHeader("X-DRecent", "false"); email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeMessage(mid, mime, user); } } catch (FilesException e) { throw e; } catch (Exception e) { throw new FilesException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new FilesException(ex); } catch (Throwable e) { throw new FilesException(e); } finally { GeneralOperations.closeHibernateSession(hsession); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } } |
00
| Code Sample 1:
private HttpURLConnection getItemURLConnection(final String method, final String id, final byte[] data, final Map<String, List<String>> headers) throws IOException { if (m_bucket == null) { throw new IllegalArgumentException("bucket is not set"); } final URL itemURL = new URL("http://" + m_host + "/" + m_bucket + "/" + id); final HttpURLConnection urlConn = (HttpURLConnection) itemURL.openConnection(); urlConn.setRequestMethod(method); urlConn.setReadTimeout(READ_TIMEOUT); if (headers != null) { for (final Map.Entry<String, List<String>> me : headers.entrySet()) { for (final String v : me.getValue()) { urlConn.setRequestProperty(me.getKey(), v); } } } addAuthorization(urlConn, method, data); return urlConn; }
Code Sample 2:
public static void loginBayFiles() throws Exception { HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); System.out.println("Trying to log in to bayfiles.com"); HttpPost httppost = new HttpPost("http://bayfiles.com/ajax_login"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("action", "login")); formparams.add(new BasicNameValuePair("username", "")); formparams.add(new BasicNameValuePair("password", "")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); System.out.println("Getting cookies........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("SESSID")) { sessioncookie = "SESSID=" + escookie.getValue(); System.out.println(sessioncookie); login = true; System.out.println("BayFiles.com Login success :)"); } } if (!login) { System.out.println("BayFiles.com Login failed :("); } } |
11
| Code Sample 1:
public void run() { LOG.debug(this); String[] parts = createCmdArray(getCommand()); Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec(parts); if (isBlocking()) { process.waitFor(); StringWriter out = new StringWriter(); IOUtils.copy(process.getInputStream(), out); String stdout = out.toString().replaceFirst("\\s+$", ""); if (StringUtils.isNotBlank(stdout)) { LOG.info("Process stdout:\n" + stdout); } StringWriter err = new StringWriter(); IOUtils.copy(process.getErrorStream(), err); String stderr = err.toString().replaceFirst("\\s+$", ""); if (StringUtils.isNotBlank(stderr)) { LOG.error("Process stderr:\n" + stderr); } } } catch (IOException ioe) { LOG.error(String.format("Could not exec [%s]", getCommand()), ioe); } catch (InterruptedException ie) { LOG.error(String.format("Interrupted [%s]", getCommand()), ie); } }
Code Sample 2:
public void salva(UploadedFile imagem, Usuario usuario) { File destino; if (usuario.getId() == null) { destino = new File(pastaImagens, usuario.hashCode() + ".jpg"); } else { destino = new File(pastaImagens, usuario.getId() + ".jpg"); } try { IOUtils.copyLarge(imagem.getFile(), new FileOutputStream(destino)); } catch (Exception e) { throw new RuntimeException("Erro ao copiar imagem", e); } redimensionar(destino.getPath(), destino.getPath(), "jpg", 110, 110); } |
00
| Code Sample 1:
public static boolean insert(final CelulaFinanceira objCelulaFinanceira) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into celula_financeira " + "(descricao, id_orgao, id_gestao, " + "id_natureza_despesa, id_programa_trabalho, " + "id_unidade_orcamentaria, id_fonte_recursos, " + "valor_provisionado, gasto_previsto, gasto_real, " + "saldo_previsto, saldo_real)" + " values (?, ?, ?, ?, ?, ?, ?, TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2))"; pst = c.prepareStatement(sql); pst.setString(1, objCelulaFinanceira.getDescricao()); pst.setLong(2, (objCelulaFinanceira.getOrgao()).getCodigo()); pst.setString(3, (objCelulaFinanceira.getGestao()).getCodigo()); pst.setString(4, (objCelulaFinanceira.getNaturezaDespesa()).getCodigo()); pst.setString(5, (objCelulaFinanceira.getProgramaTrabalho()).getCodigo()); pst.setString(6, (objCelulaFinanceira.getUnidadeOrcamentaria()).getCodigo()); pst.setString(7, (objCelulaFinanceira.getFonteRecursos()).getCodigo()); pst.setDouble(8, objCelulaFinanceira.getValorProvisionado()); pst.setDouble(9, objCelulaFinanceira.getGastoPrevisto()); pst.setDouble(10, objCelulaFinanceira.getGastoReal()); pst.setDouble(11, objCelulaFinanceira.getSaldoPrevisto()); pst.setDouble(12, objCelulaFinanceira.getSaldoReal()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { System.out.println("[CelulaFinanceiraDAO.insert] Erro ao inserir -> " + e1.getMessage()); } System.out.println("[CelulaFinanceiraDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
Code Sample 2:
public int getHttpStatus(ProxyInfo proxyInfo, String sUrl, String cookie, String host) { HttpURLConnection connection = null; try { if (proxyInfo == null) { URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(); } else { InetSocketAddress addr = new InetSocketAddress(proxyInfo.getPxIp(), proxyInfo.getPxPort()); Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(proxy); } if (!isStringNull(host)) setHttpInfo(connection, cookie, host, ""); connection.setConnectTimeout(90 * 1000); connection.setReadTimeout(90 * 1000); connection.connect(); connection.getInputStream(); return connection.getResponseCode(); } catch (IOException e) { log.info(proxyInfo + " getHTTPConent Error "); return 0; } catch (Exception e) { log.info(proxyInfo + " getHTTPConent Error "); return 0; } } |
00
| Code Sample 1:
public static void main(String[] args) { try { FileReader reader = new FileReader(args[0]); FileWriter writer = new FileWriter(args[1]); html2xhtml(reader, writer); writer.close(); reader.close(); } catch (Exception e) { freemind.main.Resources.getInstance().logException(e); } }
Code Sample 2:
protected <T extends AbstractResponse> T readResponse(HttpUriRequest httpUriRequest, Class<T> clazz) throws IOException, TranslatorException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Executing request " + httpUriRequest.getURI()); } HttpResponse httpResponse = httpClient.execute(httpUriRequest); String response = EntityUtils.toString(httpResponse.getEntity()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Reading '" + response + "' into " + clazz.getName()); } T abstractResponse = TranslatorObjectMapper.instance().readValue(response, clazz); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Response object " + abstractResponse); } if (abstractResponse.getError() != null) { throw new TranslatorException(abstractResponse.getError()); } return abstractResponse; } |
00
| Code Sample 1:
public void applyTo(File source, File target) throws IOException { boolean failed = true; FileInputStream fin = new FileInputStream(source); try { FileChannel in = fin.getChannel(); FileOutputStream fos = new FileOutputStream(target); try { FileChannel out = fos.getChannel(); long pos = 0L; for (Replacement replacement : replacements) { in.transferTo(pos, replacement.pos - pos, out); if (replacement.val != null) out.write(ByteBuffer.wrap(replacement.val)); pos = replacement.pos + replacement.len; } in.transferTo(pos, source.length() - pos, out); failed = false; } finally { fos.close(); if (failed == true) target.delete(); } } finally { fin.close(); } }
Code Sample 2:
@Override public CheckAvailabilityResult execute(final CheckAvailabilityAction action, final ExecutionContext context) throws ActionException { if (LOGGER.isDebugEnabled()) { String serverName = null; if (action.getServerId() == CheckAvailability.FEDORA_ID) { serverName = "fedora"; } else if (action.getServerId() == CheckAvailability.KRAMERIUS_ID) { serverName = "kramerius"; } LOGGER.debug("Processing action: CheckAvailability: " + serverName); } ServerUtils.checkExpiredSession(httpSessionProvider); boolean status = true; String url = null; String usr = ""; String pass = ""; if (action.getServerId() == CheckAvailability.FEDORA_ID) { url = configuration.getFedoraHost(); usr = configuration.getFedoraLogin(); pass = configuration.getFedoraPassword(); } else if (action.getServerId() == CheckAvailability.KRAMERIUS_ID) { url = configuration.getKrameriusHost() + SOME_STATIC_KRAMERIUS_PAGE; } else { throw new ActionException("Unknown server id"); } try { URLConnection con = RESTHelper.openConnection(url, usr, pass, false); if (con instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) con; int resp = httpConnection.getResponseCode(); if (resp < 200 || resp >= 308) { status = false; LOGGER.info("Server " + url + " answered with HTTP code " + httpConnection.getResponseCode()); } } else { status = false; } } catch (MalformedURLException e) { status = false; e.printStackTrace(); } catch (IOException e) { status = false; e.printStackTrace(); } return new CheckAvailabilityResult(status, url); } |
00
| Code Sample 1:
public static void main(String[] args) { if (args.length < 1) { System.out.println("Parameters: method arg1 arg2 arg3 etc"); System.out.println(""); System.out.println("Methods:"); System.out.println(" reloadpolicies"); System.out.println(" migratedatastreamcontrolgroup"); System.exit(0); } String method = args[0].toLowerCase(); if (method.equals("reloadpolicies")) { if (args.length == 4) { try { reloadPolicies(args[1], args[2], args[3]); System.out.println("SUCCESS: Policies have been reloaded"); System.exit(0); } catch (Throwable th) { th.printStackTrace(); System.err.println("ERROR: Reloading policies failed; see above"); System.exit(1); } } else { System.err.println("ERROR: Three arguments required: " + "http|https username password"); System.exit(1); } } else if (method.equals("migratedatastreamcontrolgroup")) { if (args.length > 10) { System.err.println("ERROR: too many arguments provided"); System.exit(1); } if (args.length < 7) { System.err.println("ERROR: insufficient arguments provided. Arguments are: "); System.err.println(" protocol [http|https]"); System.err.println(" user"); System.err.println(" password"); System.err.println(" pid - either"); System.err.println(" a single pid, eg demo:object"); System.err.println(" list of pids separated by commas, eg demo:object1,demo:object2"); System.err.println(" name of file containing pids, eg file:///path/to/file"); System.err.println(" dsid - either"); System.err.println(" a single datastream id, eg DC"); System.err.println(" list of ids separated by commas, eg DC,RELS-EXT"); System.err.println(" controlGroup - target control group (note only M is implemented)"); System.err.println(" addXMLHeader - add an XML header to the datastream [true|false, default false]"); System.err.println(" reformat - reformat the XML [true|false, default false]"); System.err.println(" setMIMETypeCharset - add charset=UTF-8 to the MIMEType [true|false, default false]"); System.exit(1); } try { boolean addXMLHeader = getArgBoolean(args, 7, false); boolean reformat = getArgBoolean(args, 8, false); boolean setMIMETypeCharset = getArgBoolean(args, 9, false); ; InputStream is = modifyDatastreamControlGroup(args[1], args[2], args[3], args[4], args[5], args[6], addXMLHeader, reformat, setMIMETypeCharset); IOUtils.copy(is, System.out); is.close(); System.out.println("SUCCESS: Datastreams modified"); System.exit(0); } catch (Throwable th) { th.printStackTrace(); System.err.println("ERROR: migrating datastream control group failed; see above"); System.exit(1); } } else { System.err.println("ERROR: unrecognised method " + method); System.exit(1); } }
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:
public static void addClasses(final Checker checker, final ArrayList<Class<?>> list, final String packageName, final int levels, final URL url) { final File directory = new File(url.getFile()); if (directory.exists()) addClasses(checker, list, packageName, levels, directory); else try { final JarURLConnection conn = (JarURLConnection) url.openConnection(); addClasses(checker, list, levels, conn, packageName.replace('.', '/')); } catch (final IOException ioex) { System.err.println(ioex); } }
Code Sample 2:
public void run() { if (software == null) return; Jvm.hashtable(HKEY).put(software, this); try { software.setException(null); software.setDownloaded(false); software.setDownloadStartTime(System.currentTimeMillis()); try { software.downloadStarted(); } catch (Exception dsx) { } if (software.getDownloadDir() == null) { software.setException(new Exception("The DownloadDir is null.")); software.setDownloadStartTime(0); software.setDownloaded(false); throw software.getException(); } URL url = new URL(software.getURL()); URLConnection con = url.openConnection(); software.setDownloadLength(con.getContentLength()); inputStream = con.getInputStream(); File file = new File(software.getDownloadDir(), software.getURLFilename()); outputStream = new FileOutputStream(file); int totalBytes = 0; byte[] buffer = new byte[8192]; while (!cancelled) { int bytesRead = Jvm.copyPartialStream(inputStream, outputStream, buffer); if (bytesRead == -1) break; totalBytes += bytesRead; try { software.downloadProgress(totalBytes); } catch (Exception dx) { } } if (!cancelled) software.setDownloaded(true); } catch (Exception x) { software.setException(x); software.setDownloadStartTime(0); software.setDownloaded(false); } try { software.downloadComplete(); } catch (Exception dcx) { } Jvm.hashtable(HKEY).remove(software); closeStreams(); } |
00
| Code Sample 1:
public static void main(String args[]) { org.apache.xml.security.Init.init(); String signatureFileName = args[0]; javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); try { long start = System.currentTimeMillis(); org.apache.xml.security.Init.init(); File f = new File(signatureFileName); System.out.println("Verifying " + signatureFileName); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.parse(new java.io.FileInputStream(f)); VerifyExampleTest vf = new VerifyExampleTest(); vf.verify(doc); Constants.setSignatureSpecNSprefix("dsig"); Element sigElement = null; NodeList nodes = doc.getElementsByTagNameNS(org.apache.xml.security.utils.Constants.SignatureSpecNS, "Signature"); if (nodes.getLength() != 0) { System.out.println("Found " + nodes.getLength() + " Signature elements."); for (int i = 0; i < nodes.getLength(); i++) { sigElement = (Element) nodes.item(i); XMLSignature signature = new XMLSignature(sigElement, ""); KeyInfo ki = signature.getKeyInfo(); signature.addResourceResolver(new OfflineResolver()); if (ki != null) { if (ki.containsX509Data()) { System.out.println("Could find a X509Data element in the KeyInfo"); } KeyInfo kinfo = signature.getKeyInfo(); X509Certificate cert = null; if (kinfo.containsRetrievalMethod()) { RetrievalMethod m = kinfo.itemRetrievalMethod(0); URL url = new URL(m.getURI()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(url.openStream()); } else { cert = signature.getKeyInfo().getX509Certificate(); } if (cert != null) { System.out.println("The XML signature is " + (signature.checkSignatureValue(cert) ? "valid (good)" : "invalid !!!!! (bad)")); } else { System.out.println("Did not find a Certificate"); PublicKey pk = signature.getKeyInfo().getPublicKey(); if (pk != null) { System.out.println("The XML signatur is " + (signature.checkSignatureValue(pk) ? "valid (good)" : "invalid !!!!! (bad)")); } else { System.out.println("Did not find a public key, so I can't check the signature"); } } } else { System.out.println("Did not find a KeyInfo"); } } } long end = System.currentTimeMillis(); double elapsed = end - start; System.out.println("verified:" + elapsed); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public void put(String path, File fileToPut) throws IOException { FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(this.endpointURL, this.endpointPort); log.debug("Ftp put reply: " + ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("Ftp put server refused connection."); } if (!ftp.login("anonymous", "")) { ftp.logout(); throw new IOException("FTP: server wrong passwd"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); InputStream input = new FileInputStream(fileToPut); if (ftp.storeFile(path, input) != true) { ftp.logout(); input.close(); throw new IOException("FTP put exception"); } input.close(); ftp.logout(); } catch (Exception e) { log.error("Ftp client exception: " + e.getMessage(), e); throw new IOException(e.getMessage()); } } |
11
| Code Sample 1:
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, final HttpServletResponse response) throws Exception { final String id = request.getParameter("id"); if (id == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } try { jaxrTemplate.execute(new JAXRCallback<Object>() { public Object execute(Connection connection) throws JAXRException { RegistryObject registryObject = connection.getRegistryService().getBusinessQueryManager().getRegistryObject(id); if (registryObject instanceof ExtrinsicObject) { ExtrinsicObject extrinsicObject = (ExtrinsicObject) registryObject; DataHandler dataHandler = extrinsicObject.getRepositoryItem(); if (dataHandler != null) { response.setContentType("text/html"); try { PrintWriter out = response.getWriter(); InputStream is = dataHandler.getInputStream(); try { final XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(out); xmlStreamWriter.writeStartDocument(); xmlStreamWriter.writeStartElement("div"); xmlStreamWriter.writeStartElement("textarea"); xmlStreamWriter.writeAttribute("name", "repositoryItem"); xmlStreamWriter.writeAttribute("class", "xml"); xmlStreamWriter.writeAttribute("style", "display:none"); IOUtils.copy(new XmlInputStreamReader(is), new XmlStreamTextWriter(xmlStreamWriter)); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeStartElement("script"); xmlStreamWriter.writeAttribute("class", "javascript"); xmlStreamWriter.writeCharacters("dp.SyntaxHighlighter.HighlightAll('repositoryItem');"); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndDocument(); xmlStreamWriter.flush(); } finally { is.close(); } } catch (Throwable ex) { log.error("Error while trying to format repository item " + id, ex); } } else { } } else { } return null; } }); } catch (JAXRException ex) { throw new ServletException(ex); } return null; }
Code Sample 2:
@Test public void testTrainingDefault() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); } |
00
| Code Sample 1:
private Document getOpenLinkResponse(String queryDoc) throws IOException, UnvalidResponseException { URL url = new URL(WS_URI); URLConnection conn = url.openConnection(); logger.debug(".conn open"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "text/xml"); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(queryDoc); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); logger.debug(".resp obtained"); StringBuffer responseBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { responseBuffer.append(line); responseBuffer.append(NEWLINE); } wr.close(); rd.close(); logger.debug(".done"); try { return documentParser.parse(responseBuffer.toString()); } catch (SAXException e) { throw new UnvalidResponseException("Response is not a valid XML file", e); } }
Code Sample 2:
public static String postServiceContent(String serviceURL, String text) throws IOException { URL url = new URL(serviceURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.connect(); int code = connection.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); byte[] buffer = null; String stringBuffer = ""; buffer = new byte[4096]; int totBytes, bytes, sumBytes = 0; totBytes = connection.getContentLength(); while (true) { bytes = is.read(buffer); if (bytes <= 0) break; stringBuffer = stringBuffer + new String(buffer); } return stringBuffer; } return null; } |
00
| Code Sample 1:
protected InputStream acquireInputStream(String filename) throws IOException { Validate.notEmpty(filename); File f = new File(filename); if (f.exists()) { this.originalFilename = f.getName(); return new FileInputStream(f); } URL url = getClass().getClassLoader().getResource(filename); if (url == null) { if (!filename.startsWith("/")) { url = getClass().getClassLoader().getResource("/" + filename); if (url == null) { throw new IllegalArgumentException("File [" + filename + "] not found in classpath via " + getClass().getClassLoader().getClass()); } } } this.originalFilename = filename; return url.openStream(); }
Code Sample 2:
public List<MytemHistory> getMytemHistories(String janCode) throws GaeException { HttpClient client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); HttpConnectionParams.setSoTimeout(httpParams, 10000); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); BufferedReader reader = null; StringBuffer request = new StringBuffer(address); request.append("api/mytems/history?jan="); request.append(janCode); try { HttpGet httpGet = new HttpGet(request.toString()); HttpResponse httpResponse = client.execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == NOT_FOUND) { return null; } if (statusCode >= 400) { throw new GaeException("Status Error = " + Integer.toString(statusCode)); } reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { builder.append(line); } return createMytemHistories(builder.toString()); } catch (ClientProtocolException e) { throw new GaeException(e); } catch (SocketTimeoutException e) { throw new GaeException(e); } catch (IOException exception) { throw new GaeException(exception); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } |
00
| Code Sample 1:
public static boolean isLinkHtmlContent(String address) { boolean isHtml = false; URLConnection conn = null; try { if (!address.startsWith("http://")) { address = "http://" + address; } URL url = new URL(address); conn = url.openConnection(); if (conn.getContentType().equals("text/html") && !conn.getHeaderField(0).contains("404")) { isHtml = true; } } catch (Exception e) { logger.error("Address attempted: " + conn.getURL()); logger.error("Error Message: " + e.getMessage()); } return isHtml; }
Code Sample 2:
public static boolean copyFile(File sourceFile, File destFile) throws IOException { long flag = 0; if (!destFile.exists()) destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); flag = destination.transferFrom(source, 0, source.size()); } catch (Exception e) { Logger.getLogger(FileUtils.class.getPackage().getName()).log(Level.WARNING, "ERROR: Problem copying file", e); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } if (flag == 0) return false; else return true; } |
11
| Code Sample 1:
public boolean check(Object credentials) { try { byte[] digest = null; if (credentials instanceof Password || credentials instanceof String) { synchronized (__TYPE) { if (__md == null) __md = MessageDigest.getInstance("MD5"); __md.reset(); __md.update(credentials.toString().getBytes(StringUtil.__ISO_8859_1)); digest = __md.digest(); } if (digest == null || digest.length != _digest.length) return false; for (int i = 0; i < digest.length; i++) if (digest[i] != _digest[i]) return false; return true; } else if (credentials instanceof MD5) { MD5 md5 = (MD5) credentials; if (_digest.length != md5._digest.length) return false; for (int i = 0; i < _digest.length; i++) if (_digest[i] != md5._digest[i]) return false; return true; } else if (credentials instanceof Credential) { return ((Credential) credentials).check(this); } else { log.warn("Can't check " + credentials.getClass() + " against MD5"); return false; } } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); return false; } }
Code Sample 2:
private String generateUniqueIdMD5(String workgroupIdString, String runIdString) { String passwordUnhashed = workgroupIdString + "-" + runIdString; MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(passwordUnhashed.getBytes(), 0, passwordUnhashed.length()); String uniqueIdMD5 = new BigInteger(1, m.digest()).toString(16); return uniqueIdMD5; } |
00
| Code Sample 1:
private static String sendGetRequest(String endpoint, String requestParameters) throws Exception { String result = null; if (endpoint.startsWith("http://")) { StringBuffer data = new StringBuffer(); String urlStr = prepareUrl(endpoint, requestParameters); URL url = new URL(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); result = sb.toString(); } return result; }
Code Sample 2:
public void command() { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(dir)); int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { filename = chooser.getSelectedFile().getAbsolutePath(); String f2 = ""; for (int i = 0; i < filename.length(); ++i) { if (filename.charAt(i) != '\\') { f2 = f2 + filename.charAt(i); } else f2 = f2 + '/'; } filename = f2; if (filename.contains(dir)) { filename = filename.substring(dir.length()); } else { try { FileChannel srcFile = new FileInputStream(filename).getChannel(); FileChannel dstFile; filename = "ueditor_files/" + chooser.getSelectedFile().getName(); File newFile; if (!(newFile = new File(dir + filename)).createNewFile()) { dstFile = new FileInputStream(dir + filename).getChannel(); newFile = null; } else { dstFile = new FileOutputStream(newFile).getChannel(); } dstFile.transferFrom(srcFile, 0, srcFile.size()); srcFile.close(); dstFile.close(); System.out.println("file copyed to: " + dir + filename); } catch (Exception e) { e.printStackTrace(); label.setIcon(InputText.iconX); filename = null; for (Group g : groups) { g.updateValidity(true); } return; } } label.setIcon(InputText.iconV); for (Group g : groups) { g.updateValidity(true); } } } |
00
| Code Sample 1:
public static void copyFiles(String strPath, String dstPath) throws IOException { File src = new File(strPath); File dest = new File(dstPath); if (src.isDirectory()) { dest.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { if (list[i].lastIndexOf(SVN) != -1) { if (!SVN.equalsIgnoreCase(list[i].substring(list[i].length() - 4, list[i].length()))) { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFiles(src1, dest1); } } else { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFiles(src1, dest1); } } } else { FileInputStream fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } }
Code Sample 2:
public static String getHashedStringMD5(String value) throws java.security.NoSuchAlgorithmException { java.security.MessageDigest d = java.security.MessageDigest.getInstance("MD5"); d.reset(); d.update(value.getBytes()); byte[] buf = d.digest(); return new String(buf); } |
11
| Code Sample 1:
protected String getLibJSCode() throws IOException { if (cachedLibJSCode == null) { InputStream is = getClass().getResourceAsStream(JS_LIB_FILE); StringWriter output = new StringWriter(); IOUtils.copy(is, output); cachedLibJSCode = output.toString(); } return cachedLibJSCode; }
Code Sample 2:
public static void nioJoinFiles(FileLib.FileValidator validator, File target, File[] sources) { boolean big_files = false; for (int i = 0; i < sources.length; i++) { if (sources[i].length() > Integer.MAX_VALUE) { big_files = true; break; } } if (big_files) { joinFiles(validator, target, sources); } else { System.out.println(i18n.getString("jdk14_comment")); FileOutputStream fos = null; try { fos = new FileOutputStream(target); FileChannel fco = fos.getChannel(); FileInputStream fis = null; for (int i = 0; i < sources.length; i++) { fis = new FileInputStream(sources[i]); FileChannel fci = fis.getChannel(); java.nio.MappedByteBuffer map; try { map = fci.map(FileChannel.MapMode.READ_ONLY, 0, (int) sources[i].length()); fco.write(map); fci.close(); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); try { fis.close(); fos.close(); } catch (IOException e) { } } finally { fis.close(); } } fco.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } } } |
11
| Code Sample 1:
protected String getPageText(final String url) { StringBuilder b = new StringBuilder(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String line = null; while ((line = reader.readLine()) != null) { b.append(line).append('\n'); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { ex.printStackTrace(); } } } return b.toString(); }
Code Sample 2:
private static boolean DownloadDB() { URL url = null; BufferedWriter inWriter = null; String line; try { url = new URL(URL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); inWriter = new BufferedWriter(new FileWriter(InFileName)); while ((line = reader.readLine()) != null) { inWriter.write(line); inWriter.newLine(); } inWriter.close(); } catch (Exception e) { try { inWriter.close(); } catch (IOException ignored) { } e.printStackTrace(); return false; } return true; } |
00
| Code Sample 1:
protected void assignListeners() { groupsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent event) { refreshInfo(); } }); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JFileChooser fileDialog = new JFileChooser("."); fileDialog.setFileFilter(ReaderData.mkExtensionFileFilter(".grp", "Group Files")); int outcome = fileDialog.showSaveDialog((Frame) null); if (outcome == JFileChooser.APPROVE_OPTION) { assert (fileDialog.getCurrentDirectory() != null); assert (fileDialog.getSelectedFile() != null); String fileName = fileDialog.getCurrentDirectory().toString() + File.separator + fileDialog.getSelectedFile().getName(); try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); ReaderWriterGroup.write(out, writer); System.err.println("Wrote groups informations to output '" + fileName + "'."); out.close(); } catch (IOException e) { System.err.println("error while writing (GroupManager.saveClt):"); e.printStackTrace(); } } else if (outcome == JFileChooser.CANCEL_OPTION) { } } }); loadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { JFileChooser fileDialog = new JFileChooser("."); fileDialog.setFileFilter(ReaderData.mkExtensionFileFilter(".grp", "Group Files")); int outcome = fileDialog.showOpenDialog((Frame) null); if (outcome == JFileChooser.APPROVE_OPTION) { assert (fileDialog.getCurrentDirectory() != null); assert (fileDialog.getSelectedFile() != null); String fileName = fileDialog.getCurrentDirectory().toString() + File.separator + fileDialog.getSelectedFile().getName(); BufferedReader fileReader = null; try { fileReader = new BufferedReader(new FileReader(fileName)); ReaderWriterGroup.read(fileReader, writer); fileReader.close(); } catch (Exception e) { System.err.println("Exception while reading from file '" + fileName + "'."); System.err.println(e); } } else if (outcome == JFileChooser.CANCEL_OPTION) { } } }); ItemListener propItemListener = new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { int[] indices = groupsList.getSelectedIndices(); for (int index : indices) { Group group = getGroupFromListIndex(index); if (group != null) { if (event.getSource() instanceof JComboBox) { JComboBox eventSource = (JComboBox) event.getSource(); if (eventSource == colorComboBox) { Color color = colorComboBox.getSelectedColor(); assert (color != null); group.setColor(color); shapeComboBox.setColor(color); } else if (eventSource == shapeComboBox) { Shape shape = shapeComboBox.getSelectedShape(); assert (shape != null); group.setShape(shape); } } else if (event.getSource() instanceof JCheckBox) { JCheckBox eventSource = (JCheckBox) event.getSource(); if (eventSource == showGroupCheckBox) { group.visible = showGroupCheckBox.isSelected(); } else if (eventSource == showGraphicInfoCheckBox) { group.info = showGraphicInfoCheckBox.isSelected(); } } } } graph.notifyAboutGroupsChange(null); } }; colorComboBox.addItemListener(propItemListener); shapeComboBox.addItemListener(propItemListener); showGroupCheckBox.addItemListener(propItemListener); showGraphicInfoCheckBox.addItemListener(propItemListener); showGroupfreeNodesCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { graph.getGroup(0).visible = showGroupfreeNodesCheckBox.isSelected(); graph.notifyAboutGroupsChange(null); } }); ActionListener propActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JButton botton = (JButton) event.getSource(); Group group = getGroupFromListIndex(groupsList.getSelectedIndex()); if (group != null) { for (GraphVertex graphVertex : group) { if (botton == showLabelsButton) { graphVertex.setShowName(NameVisibility.Priority.GROUPS, true); } else if (botton == hideLabelsButton) { graphVertex.setShowName(NameVisibility.Priority.GROUPS, false); } } graph.notifyAboutGroupsChange(null); } } }; showLabelsButton.addActionListener(propActionListener); hideLabelsButton.addActionListener(propActionListener); newButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { String newGroupName = JOptionPane.showInputDialog(null, "Enter a name", "Name of the new group", JOptionPane.QUESTION_MESSAGE); if (newGroupName != null) { if (graph.getGroup(newGroupName) == null) { graph.addGroup(new Group(newGroupName, graph)); } } } }); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { Group group = getGroupFromListIndex(groupsList.getSelectedIndex()); if (group != null) { DialogEditGroup dialog = new DialogEditGroup(graph, group); dialog.setModal(true); dialog.setVisible(true); } } }); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index > 0 && index < graph.getNumberOfGroups() - 1) { graph.removeGroup(index); } } }); upButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index < graph.getNumberOfGroups() - 1) { graph.moveGroupUp(index); groupsList.setSelectedIndex(index - 1); } } }); downButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index < graph.getNumberOfGroups() - 1) { graph.moveGroupDown(index); groupsList.setSelectedIndex(index + 1); } } }); }
Code Sample 2:
@Override public User createUser(User bean) throws SitoolsException { checkUser(); if (!User.isValid(bean)) { throw new SitoolsException("CREATE_USER_MALFORMED"); } Connection cx = null; try { cx = ds.getConnection(); cx.setAutoCommit(false); PreparedStatement st = cx.prepareStatement(jdbcStoreResource.CREATE_USER); int i = 1; st.setString(i++, bean.getIdentifier()); st.setString(i++, bean.getFirstName()); st.setString(i++, bean.getLastName()); st.setString(i++, bean.getSecret()); st.setString(i++, bean.getEmail()); st.executeUpdate(); st.close(); createProperties(bean, cx); if (!cx.getAutoCommit()) { cx.commit(); } } catch (SQLException e) { try { cx.rollback(); } catch (SQLException e1) { e1.printStackTrace(); throw new SitoolsException("CREATE_USER ROLLBACK" + e1.getMessage(), e1); } e.printStackTrace(); throw new SitoolsException("CREATE_USER " + e.getMessage(), e); } finally { closeConnection(cx); } return getUserById(bean.getIdentifier()); } |
11
| Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
11
| Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
private byte[] szyfrujKlucz(byte[] kluczSesyjny) { byte[] zaszyfrowanyKlucz = null; byte[] klucz = null; try { MessageDigest skrot = MessageDigest.getInstance("SHA-1"); skrot.update(haslo.getBytes()); byte[] skrotHasla = skrot.digest(); Object kluczDoKlucza = MARS_Algorithm.makeKey(skrotHasla); int resztaKlucza = this.dlugoscKlucza % ROZMIAR_BLOKU; if (resztaKlucza == 0) { klucz = kluczSesyjny; zaszyfrowanyKlucz = new byte[this.dlugoscKlucza]; } else { int liczbaBlokow = this.dlugoscKlucza / ROZMIAR_BLOKU + 1; int nowyRozmiar = liczbaBlokow * ROZMIAR_BLOKU; zaszyfrowanyKlucz = new byte[nowyRozmiar]; klucz = new byte[nowyRozmiar]; byte roznica = (byte) (ROZMIAR_BLOKU - resztaKlucza); System.arraycopy(kluczSesyjny, 0, klucz, 0, kluczSesyjny.length); for (int i = kluczSesyjny.length; i < nowyRozmiar; i++) klucz[i] = (byte) roznica; } byte[] szyfrogram = null; int liczbaBlokow = klucz.length / ROZMIAR_BLOKU; int offset = 0; for (offset = 0; offset < liczbaBlokow; offset++) { szyfrogram = MARS_Algorithm.blockEncrypt(klucz, offset * ROZMIAR_BLOKU, kluczDoKlucza); System.arraycopy(szyfrogram, 0, zaszyfrowanyKlucz, offset * ROZMIAR_BLOKU, szyfrogram.length); } } catch (InvalidKeyException ex) { Logger.getLogger(SzyfrowaniePliku.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return zaszyfrowanyKlucz; } |
11
| Code Sample 1:
@Override public void copyFile2File(final File src, final File dest, final boolean force) throws C4JException { if (dest.exists()) if (force && !dest.delete()) throw new C4JException(format("Copying ‘%s’ to ‘%s’ failed; cannot overwrite existing file.", src.getPath(), dest.getPath())); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dest).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (src.canExecute()) dest.setExecutable(true, false); } catch (final IOException e) { throw new C4JException(format("Could not copy ‘%s’ to ‘%s’.", src.getPath(), dest.getPath()), e); } finally { if (inChannel != null) try { try { inChannel.close(); } catch (final IOException e) { throw new C4JException(format("Could not close input stream for ‘%s’.", src.getPath()), e); } } finally { if (outChannel != null) try { outChannel.close(); } catch (final IOException e) { throw new C4JException(format("Could not close output stream for ‘%s’.", dest.getPath()), e); } } } }
Code Sample 2:
@Test(dependsOnMethods = { "getSize" }) public void download() throws IOException { FileObject typica = fsManager.resolveFile("s3://" + bucketName + "/jonny.zip"); File localCache = File.createTempFile("vfs.", ".s3-test"); FileOutputStream out = new FileOutputStream(localCache); IOUtils.copy(typica.getContent().getInputStream(), out); Assert.assertEquals(localCache.length(), typica.getContent().getSize()); localCache.delete(); } |
11
| Code Sample 1:
public boolean update(int idTorneo, torneo torneoModificado) { int intResult = 0; String sql = "UPDATE torneo " + "SET nombreTorneo = ?, ciudad = ?, fechaInicio = ?, fechaFinal = ?, " + " organizador = ? " + " WHERE idTorneo = " + idTorneo; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement2(torneoModificado); intResult = 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 (intResult > 0); }
Code Sample 2:
public void unlock(String oid, String key) throws PersisterException { String lock = getLock(oid); if (lock == null) { throw new PersisterException("Object does not exist: OID = " + oid); } else if (!NULL.equals(lock) && (!lock.equals(key))) { throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key); } Connection conn = null; PreparedStatement ps = null; try { conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("update " + _table_name + " set " + _key_col + " = NULL, " + _ts_col + " = ? where " + _oid_col + " = ?"); ps.setLong(1, System.currentTimeMillis()); ps.setString(2, oid); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to unlock object: OID = " + oid + ", KEY = " + key, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } } |
00
| Code Sample 1:
public APIResponse delete(String id) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/user/delete/" + id).openConnection(); connection.setRequestMethod("DELETE"); connection.setConnectTimeout(TIMEOUT); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { response.setDone(true); response.setMessage("User Deleted!"); } else { response.setDone(false); response.setMessage("Delete User Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; }
Code Sample 2:
private PieceSet[] getPieceSets() { Resource[] resources = boardManager.getResources("pieces"); PieceSet[] pieceSets = new PieceSet[resources.length]; for (int i = 0; i < resources.length; i++) pieceSets[i] = (PieceSet) resources[i]; for (int i = 0; i < resources.length; i++) { for (int j = 0; j < resources.length - (i + 1); j++) { String name1 = pieceSets[j].getName(); String name2 = pieceSets[j + 1].getName(); if (name1.compareTo(name2) > 0) { PieceSet tmp = pieceSets[j]; pieceSets[j] = pieceSets[j + 1]; pieceSets[j + 1] = tmp; } } } return pieceSets; } |
11
| Code Sample 1:
private void processOrder() { double neg = 0d; if (intMode == MODE_CHECKOUT) { if (round2Places(mBuf.getBufferTotal()) >= round2Places(order.getOrderTotal())) { double cash, credit, allowedCredit = 0d; allowedCredit = getStudentCredit(); if (settings.get(DBSettings.MAIN_ALLOWNEGBALANCES).compareTo("1") == 0) { try { neg = Double.parseDouble(settings.get(DBSettings.MAIN_MAXNEGBALANCE)); } catch (NumberFormatException ex) { System.err.println("NumberFormatException::Potential problem with setting MAIN_MAXNEGBALANCE"); System.err.println(" * Note: If you enable negative balances, please don't leave this"); System.err.println(" blank. At least set it to 0. For right now we are setting "); System.err.println(" the max negative balance to $0.00"); System.err.println(""); System.err.println("Exception Message:" + ex.getMessage()); } if (neg < 0) neg *= -1; allowedCredit += neg; } if (round2Places(mBuf.getCredit()) <= round2Places(allowedCredit)) { if (round2Places(mBuf.getCredit()) > round2Places(getStudentCredit()) && !student.isStudentSet()) { gui.setStatus("Can't allow negative balance on an anonymous student!", true); } else { if (round2Places(mBuf.getCredit()) > round2Places(order.getOrderTotal())) { credit = round2Places(order.getOrderTotal()); } else { credit = round2Places(mBuf.getCredit()); } if ((mBuf.getCash() + credit) >= order.getOrderTotal()) { cash = round2Places(order.getOrderTotal() - credit); double change = round2Places(mBuf.getCash() - cash); if (round2Places(cash + credit) == round2Places(order.getOrderTotal())) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = dbMan.getPOSConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String host = getHostName(); String stuId = student.getStudentNumber(); String building = settings.get(DBSettings.MAIN_BUILDING); String cashier = dbMan.getPOSUser(); String strSql = "insert into " + strPOSPrefix + "trans_master ( tm_studentid, tm_total, tm_cashtotal, tm_credittotal, tm_building, tm_register, tm_cashier, tm_datetime, tm_change ) values( '" + stuId + "', '" + round2Places(order.getOrderTotal()) + "', '" + round2Places(cash) + "', '" + round2Places(credit) + "', '" + building + "', '" + host + "', '" + cashier + "', NOW(), '" + round2Places(change) + "')"; int intSqlReturnVal = -1; int masterID = -1; try { intSqlReturnVal = stmt.executeUpdate(strSql, Statement.RETURN_GENERATED_KEYS); ResultSet keys = stmt.getGeneratedKeys(); keys.next(); masterID = keys.getInt(1); keys.close(); stmt.close(); } catch (Exception exRetKeys) { System.err.println(exRetKeys.getMessage() + " (but pscafepos is attempting a work around)"); intSqlReturnVal = stmt.executeUpdate(strSql); masterID = dbMan.getLastInsertIDWorkAround(stmt, strPOSPrefix + "trans_master_tm_id_seq"); if (masterID == -1) System.err.println("It looks like the work around failed, please submit a bug report!"); else System.err.println("work around was successful!"); } if (intSqlReturnVal == 1) { if (masterID >= 0) { OrderItem[] itms = order.getOrderItems(); if (itms != null && itms.length > 0) { for (int i = 0; i < itms.length; i++) { if (itms[i] != null) { stmt = conn.createStatement(); int itemid = itms[i].getDBID(); double itemprice = round2Places(itms[i].getEffectivePrice()); int f, r, a; String strItemName, strItemBuilding, strItemCat; f = 0; r = 0; a = 0; if (itms[i].isSoldAsFree()) { f = 1; } if (itms[i].isSoldAsReduced()) { r = 1; } if (itms[i].isTypeA()) { a = 1; } strItemName = itms[i].getName(); strItemBuilding = (String) itms[i].getBuilding(); strItemCat = itms[i].getCategory(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "trans_item ( ti_itemid, ti_tmid, ti_pricesold, ti_registerid, ti_cashier, ti_studentid, ti_isfree, ti_isreduced, ti_datetime, ti_istypea, ti_itemname, ti_itembuilding, ti_itemcat ) values('" + itemid + "', '" + masterID + "', '" + round2Places(itemprice) + "', '" + host + "', '" + cashier + "', '" + stuId + "', '" + f + "', '" + r + "', NOW(), '" + a + "', '" + strItemName + "', '" + strItemBuilding + "', '" + strItemCat + "')") != 1) { gui.setCriticalMessage("Item insert failed"); conn.rollback(); } stmt.close(); stmt = conn.createStatement(); String sqlInv = "SELECT inv_id from " + strPOSPrefix + "inventory where inv_menuid = " + itemid + ""; if (stmt.execute(sqlInv)) { ResultSet rsInv = stmt.getResultSet(); int delId = -1; if (rsInv.next()) { delId = rsInv.getInt("inv_id"); } if (delId != -1) { stmt.executeUpdate("delete from " + strPOSPrefix + "inventory where inv_id = " + delId); } stmt.close(); } } else { gui.setCriticalMessage("Null Item"); conn.rollback(); } } boolean blOk = true; if (round2Places(credit) > 0d) { if (round2Places(allowedCredit) >= round2Places(credit)) { if (hasStudentCredit()) { stmt = conn.createStatement(); if (stmt.executeUpdate("update " + strPOSPrefix + "studentcredit set credit_amount = credit_amount - " + round2Places(credit) + " where credit_active = '1' and credit_studentid = '" + stuId + "'") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("update " + strPOSPrefix + "studentcredit set credit_lastused = NOW() where credit_active = '1' and credit_studentid = '" + stuId + "'") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "studentcredit_log ( scl_studentid, scl_action, scl_transid, scl_datetime ) values( '" + stuId + "', '" + round2Places((-1) * credit) + "', '" + masterID + "', NOW() )") == 1) { stmt.close(); blOk = true; } else { gui.setCriticalMessage("Unable to update student credit log."); blOk = false; } } else { gui.setCriticalMessage("Unable to update student credit account."); blOk = false; } } else { gui.setCriticalMessage("Unable to update student credit account."); blOk = false; } } else { stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "studentcredit (credit_amount,credit_active,credit_studentid,credit_lastused) values('" + round2Places((-1) * credit) + "','1','" + stuId + "', NOW())") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "studentcredit_log ( scl_studentid, scl_action, scl_transid, scl_datetime ) values( '" + stuId + "', '" + round2Places((-1) * credit) + "', '" + masterID + "', NOW() )") == 1) { stmt.close(); blOk = true; } else { gui.setCriticalMessage("Unable to update student credit log."); blOk = false; } } else { gui.setCriticalMessage("Unable to create new student credit account."); blOk = false; } } } else { gui.setCriticalMessage("Student doesn't have enought credit."); blOk = false; } } if (blOk) { if (blDepositCredit && change > 0d) { try { if (doStudentCreditUpdate(change, stuId)) { change = 0d; } else blOk = false; } catch (Exception cExp) { blOk = false; } } } if (blOk) { boolean blHBOK = true; if (itms != null && itms.length > 0) { for (int i = 0; i < itms.length; i++) { stmt = conn.createStatement(); if (stmt.execute("select count(*) from " + strPOSPrefix + "hotbar where hb_itemid = '" + itms[i].getDBID() + "' and hb_building = '" + building + "' and hb_register = '" + host + "' and hb_cashier = '" + cashier + "'")) { rs = stmt.getResultSet(); rs.next(); int num = rs.getInt(1); stmt.close(); if (num == 1) { stmt = conn.createStatement(); if (stmt.executeUpdate("update " + strPOSPrefix + "hotbar set hb_count = hb_count + 1 where hb_itemid = '" + itms[i].getDBID() + "' and hb_building = '" + building + "' and hb_register = '" + host + "' and hb_cashier = '" + cashier + "'") != 1) blHBOK = false; } else { stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "hotbar ( hb_itemid, hb_building, hb_register, hb_cashier, hb_count ) values( '" + itms[i].getDBID() + "', '" + building + "', '" + host + "', '" + cashier + "', '1' )") != 1) blHBOK = false; } stmt.close(); } } } else blHBOK = false; if (blHBOK) { conn.commit(); gui.setStatus("Order Complete."); gui.disableUI(); summary = new PSOrderSummary(gui); if (cashDrawer != null) cashDrawer.openDrawer(); else summary.setPOSEventListener(this); summary.display(money.format(order.getOrderTotal()), money.format(mBuf.getCash()), money.format(credit), money.format(change), money.format(getStudentCredit())); } else { conn.rollback(); gui.setStatus("Failure during Hotbar update. Transaction has been rolled back.", true); } } else { conn.rollback(); } } else { gui.setCriticalMessage("Unable to fetch items."); conn.rollback(); } } else { gui.setCriticalMessage("Unable to retrieve autoid"); conn.rollback(); } } else { gui.setCriticalMessage("Error During Writting of Transaction Master Record."); conn.rollback(); } } catch (SQLException sqlEx) { System.err.println("SQLException: " + sqlEx.getMessage()); System.err.println("SQLState: " + sqlEx.getSQLState()); System.err.println("VendorError: " + sqlEx.getErrorCode()); try { conn.rollback(); } catch (SQLException sqlEx2) { System.err.println("Rollback failed: " + sqlEx2.getMessage()); } } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); System.err.println(e); try { conn.rollback(); } catch (SQLException sqlEx2) { System.err.println("Rollback failed: " + sqlEx2.getMessage()); } } finally { if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { stmt = null; } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); System.err.println(e); } } } } } } else { gui.setStatus("Credit total + Cash total is less then the order total! ", true); } } } else { if (settings.get(DBSettings.MAIN_ALLOWNEGBALANCES).compareTo("1") == 0) { gui.setStatus("Sorry, maximum negative balance is " + money.format(neg) + "!", true); } else gui.setStatus("Student does not have enough credit to process this order.", true); } } else { gui.setStatus("Buffer total is less then the order total.", true); } } }
Code Sample 2:
public void testPreparedStatement0009() throws Exception { Connection cx = getConnection(); dropTable("#t0009"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0009 " + " (i integer not null, " + " s char(10) not null) "); cx.setAutoCommit(false); PreparedStatement pStmt = cx.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(); } assertTrue(count == rowsToAdd); cx.rollback(); stmt = cx.createStatement(); ResultSet rs = stmt.executeQuery("select s, i from #t0009"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == 0); cx.commit(); 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(); } assertTrue(count == rowsToAdd); cx.commit(); rs = stmt.executeQuery("select s, i from #t0009"); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == rowsToAdd); cx.commit(); cx.setAutoCommit(true); } |
00
| Code Sample 1:
public void testGetWithKeepAlive() throws Exception { HttpGet request = new HttpGet(baseUri + "/test"); HttpResponse response = client.execute(request); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("test", TestUtil.getResponseAsString(response)); response = client.execute(request); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("test", TestUtil.getResponseAsString(response)); }
Code Sample 2:
public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("some text ".getBytes())); fc.close(); fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("some more".getBytes())); fc.close(); fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) { PrintUtil.prt((char) buff.get()); } } |
00
| Code Sample 1:
protected Icon newIcon(String iconName) { URL url = Utils.getResource(getFullPath(iconName, "/"), getClass()); if (url == null) { if (getParent() != null) return getParent().getIcon(iconName); return null; } try { MethodCall getImage = new MethodCaller("org.apache.sanselan.Sanselan", null, "getBufferedImage", new Object[] { InputStream.class }).getMethodCall(); getImage.setArgumentValue(0, url.openStream()); return new ImageIcon((BufferedImage) getImage.call()); } catch (Throwable e) { return new ImageIcon(url); } }
Code Sample 2:
public void gzipCompress(String file) { try { File inputFile = new File(file); FileInputStream fileinput = new FileInputStream(inputFile); File outputFile = new File(file.substring(0, file.length() - 1) + "z"); FileOutputStream stream = new FileOutputStream(outputFile); GZIPOutputStream gzipstream = new GZIPOutputStream(stream); BufferedInputStream bis = new BufferedInputStream(fileinput); int bytes_read = 0; byte[] buf = new byte[READ_BUFFER_SIZE]; while ((bytes_read = bis.read(buf, 0, BLOCK_SIZE)) != -1) { gzipstream.write(buf, 0, bytes_read); } bis.close(); inputFile.delete(); gzipstream.finish(); gzipstream.close(); } catch (FileNotFoundException fnfe) { System.out.println("Compressor: Cannot find file " + fnfe.getMessage()); } catch (SecurityException se) { System.out.println("Problem saving file " + se.getMessage()); } catch (IOException ioe) { System.out.println("Problem saving file " + ioe.getMessage()); } } |
00
| Code Sample 1:
@Override public void decorate(Object element, IDecoration decoration) { if (element != null && element instanceof IProject) { InputStream is = null; try { IProject project = (IProject) element; IFile file = project.getFile(Activator.PLUGIN_CONF); if (file.exists()) { URL url = bundle.getEntry("icons/leaf4e_decorator.gif"); is = FileLocator.toFileURL(url).openStream(); Image img = new Image(Display.getCurrent(), is); ImageDescriptor id = ImageDescriptor.createFromImage(img); decoration.addOverlay(id, IDecoration.TOP_LEFT); } } catch (Exception e) { Status status = new Status(IStatus.WARNING, Activator.PLUGIN_ID, "Decorating error", e); logger.log(status); } finally { if (is != null) { try { is.close(); } catch (IOException e) { Status status = new Status(IStatus.WARNING, Activator.PLUGIN_ID, "", e); logger.log(status); } } } } }
Code Sample 2:
private String _doPost(final String urlStr, final Map<String, String> params) { String paramsStr = ""; for (String key : params.keySet()) { try { paramsStr += URLEncoder.encode(key, ENCODING) + "=" + URLEncoder.encode(params.get(key), ENCODING) + "&"; } catch (UnsupportedEncodingException e) { s_logger.debug("UnsupportedEncodingException caught. Trying to encode: " + key + " and " + params.get(key)); return null; } } if (paramsStr.length() == 0) { s_logger.debug("POST will not complete, no parameters specified."); return null; } s_logger.debug("POST to server will be done with the following parameters: " + paramsStr); HttpURLConnection connection = null; String responseStr = null; try { connection = (HttpURLConnection) (new URL(urlStr)).openConnection(); connection.setRequestMethod(REQUEST_METHOD); connection.setDoOutput(true); DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); dos.write(paramsStr.getBytes()); dos.flush(); dos.close(); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); responseStr = response.toString(); } catch (ProtocolException e) { s_logger.debug("ProtocolException caught. Unable to execute POST."); } catch (MalformedURLException e) { s_logger.debug("MalformedURLException caught. Unexpected. Url is: " + urlStr); } catch (IOException e) { s_logger.debug("IOException caught. Unable to execute POST."); } return responseStr; } |
11
| Code Sample 1:
private static void downloadFile(URL url, File destFile) throws Exception { try { URLConnection urlConnection = url.openConnection(); File tmpFile = null; try { tmpFile = File.createTempFile("remoteLib_", null); InputStream in = null; FileOutputStream out = null; try { in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } } catch (Exception ex) { throw new RuntimeException("Could not download URL: " + url, ex); } }
Code Sample 2:
private void doIt() throws Throwable { GenericDAO<User> dao = DAOFactory.createDAO(User.class); try { final User user = dao.findUniqueByCriteria(Expression.eq("login", login)); if (user == null) throw new IllegalArgumentException("Specified user isn't exist"); if (srcDir.isDirectory() && srcDir.exists()) { final String[] fileList = srcDir.list(new XFilenameFilter() { public boolean accept(XFile dir, String file) { String[] fNArr = file.split("\\."); return (fNArr.length > 1 && (fNArr[fNArr.length - 1].equalsIgnoreCase("map") || fNArr[fNArr.length - 1].equalsIgnoreCase("plt") || fNArr[fNArr.length - 1].equalsIgnoreCase("wpt"))); } }); int pointsCounter = 0; int tracksCounter = 0; int mapsCounter = 0; for (final String fName : fileList) { try { TransactionManager.beginTransaction(); } catch (Throwable e) { logger.error(e); throw e; } final XFile file = new XFile(srcDir, fName); InputStream in = new XFileInputStream(file); try { ArrayList<UserMapOriginal> maps = new ArrayList<UserMapOriginal>(); ArrayList<MapTrackPointsScaleRequest> tracks = new ArrayList<MapTrackPointsScaleRequest>(); final byte[] headerBuf = new byte[1024]; if (in.read(headerBuf) <= 0) continue; final String fileHeader = new String(headerBuf); final boolean isOziWPT = (fileHeader.indexOf("OziExplorer Waypoint File") >= 0); final boolean isOziPLT = (fileHeader.indexOf("OziExplorer Track Point File") >= 0); final boolean isOziMAP = (fileHeader.indexOf("OziExplorer Map Data File") >= 0); final boolean isKML = (fileHeader.indexOf("<kml xmlns=") >= 0); if (isOziMAP || isOziPLT || isOziWPT || isKML) { in.close(); in = new XFileInputStream(file); } else continue; WPTPoint wp; if (isOziWPT) { try { wp = new WPTPointParser(in, "Cp1251").parse(); } catch (Throwable t) { wp = null; } if (wp != null) { Set<WayPointRow> rows = wp.getPoints(); for (WayPointRow row : rows) { final UserMapPoint p = BeanFactory.createUserPoint(row, user); logger.info("point:" + p.getGuid()); } pointsCounter += rows.size(); } } else if (isOziPLT) { PLTTrack plt; try { plt = new PLTTrackParser(in, "Cp1251").parse(); } catch (Throwable t) { plt = null; } if (plt != null) { final UserMapTrack t = BeanFactory.createUserTrack(plt, user); tracks.add(new MapTrackPointsScaleRequest(t)); tracksCounter++; logger.info("track:" + t.getGuid()); } } else if (isOziMAP) { MapProjection projection; MAPParser parser = new MAPParser(in, "Cp1251"); try { projection = parser.parse(); } catch (Throwable t) { projection = null; } if (projection != null && projection.getPoints() != null && projection.getPoints().size() >= 2) { GenericDAO<UserMapOriginal> mapDao = DAOFactory.createDAO(UserMapOriginal.class); final UserMapOriginal mapOriginal = new UserMapOriginal(); mapOriginal.setName(projection.getTitle()); mapOriginal.setUser(user); mapOriginal.setState(UserMapOriginal.State.UPLOAD); mapOriginal.setSubstate(UserMapOriginal.SubState.COMPLETE); MapManager.updateProjection(projection, mapOriginal); final XFile srcFile = new XFile(srcDir, projection.getPath()); if (!srcFile.exists() || !srcFile.isFile()) throw new IllegalArgumentException("file: " + srcFile.getPath() + " not found"); final XFile mapStorage = new XFile(new XFile(Configuration.getInstance().getPrivateMapStorage().toString()), mapOriginal.getGuid()); mapStorage.mkdir(); XFile dstFile = new XFile(mapStorage, mapOriginal.getGuid()); XFileOutputStream out = new XFileOutputStream(dstFile); XFileInputStream inImg = new XFileInputStream(srcFile); IOUtils.copy(inImg, out); out.flush(); out.close(); inImg.close(); mapDao.save(mapOriginal); maps.add(mapOriginal); srcFile.delete(); mapsCounter++; logger.info("map:" + mapOriginal.getGuid()); } } else logger.warn("unsupported file format: " + file.getName()); TransactionManager.commitTransaction(); for (MapTrackPointsScaleRequest track : tracks) { if (track != null) { try { PoolClientInterface pool = PoolFactory.getInstance().getClientPool(); if (pool == null) throw new IllegalStateException("pool not found"); pool.put(track, new StatesStack(new byte[] { 0x00, 0x11 }), GeneralCompleteStrategy.class); } catch (Throwable t) { logger.error(t); } } } } catch (Throwable e) { logger.error("Error importing", e); TransactionManager.rollbackTransaction(); } finally { in.close(); file.delete(); } } logger.info("waypoints: " + pointsCounter + "\ntracks: " + tracksCounter + "\nmaps: " + mapsCounter); } } catch (Throwable e) { logger.error("Error importing", e); } } |
11
| 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 static void invokeServlet(String op, String user) throws Exception { boolean isSayHi = true; try { if (!"sayHi".equals(op)) { isSayHi = false; } URL url = new URL("http://localhost:9080/helloworld/*.do"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); out.write("Operation=" + op); if (!isSayHi) { out.write("&User=" + user); } out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); boolean correctReturn = false; String response; if (isSayHi) { while ((response = in.readLine()) != null) { if (response.contains("Bonjour")) { System.out.println(" sayHi server return: Bonjour"); correctReturn = true; break; } } } else { while ((response = in.readLine()) != null) { if (response.contains("Hello CXF")) { System.out.println(" greetMe server return: Hello CXF"); correctReturn = true; break; } } } if (!correctReturn) { System.out.println("Can't got correct return from server."); } in.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } |
00
| Code Sample 1:
public OutputStream getOutputStream() throws IOException { try { URL url = getURL(); URLConnection urlc = url.openConnection(); return urlc.getOutputStream(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
Code Sample 2:
public Object mapRow(ResultSet rs, int i) throws SQLException { try { BLOB blob = (BLOB) rs.getBlob(1); OutputStream outputStream = blob.setBinaryStream(0L); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (Exception e) { throw new SQLException(e.getMessage()); } return null; } |
00
| Code Sample 1:
public void zipUp() throws PersistenceException { ZipOutputStream out = null; try { if (!backup.exists()) backup.createNewFile(); out = new ZipOutputStream(new FileOutputStream(backup)); out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String file : backupDirectory.list()) { logger.debug("Deflating: " + file); FileInputStream in = null; try { in = new FileInputStream(new File(backupDirectory, file)); out.putNextEntry(new ZipEntry(file)); IOUtils.copy(in, out); } finally { out.closeEntry(); if (null != in) in.close(); } } FileUtils.deleteDirectory(backupDirectory); } catch (Exception ex) { logger.error("Unable to ZIP the backup {" + backupDirectory.getAbsolutePath() + "}.", ex); throw new PersistenceException(ex); } finally { try { if (null != out) out.close(); } catch (IOException e) { logger.error("Unable to close ZIP output stream.", e); } } }
Code Sample 2:
@SuppressWarnings("unchecked") public static <T> List<T> getServices(String service) { String serviceUri = "META-INF/services/" + service; ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { Enumeration<URL> urls = loader.getResources(serviceUri); if (urls.hasMoreElements()) { List<T> services = new ArrayList<T>(1); Set<String> keys = new HashSet<String>(20); do { URL url = urls.nextElement(); if (_LOG.isLoggable(Level.FINEST)) { _LOG.finest("Processing: " + url); } try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); try { while (true) { String line = in.readLine(); if (line == null) break; String className = _parseLine(line); if (className != null && keys.add(className)) { T instance = (T) _getClass(loader, className); services.add(instance); } } } finally { in.close(); } } catch (Exception e) { if (_LOG.isLoggable(Level.WARNING)) { _LOG.log(Level.WARNING, "Error parsing URL: " + url, e); } } } while (urls.hasMoreElements()); if (services.size() == 1) return Collections.singletonList(services.get(0)); return Collections.unmodifiableList(services); } } catch (IOException e) { if (_LOG.isLoggable(Level.SEVERE)) { _LOG.log(Level.SEVERE, "Error loading Resource: " + serviceUri, e); } } return Collections.emptyList(); } |
00
| Code Sample 1:
public void loadJar(final String extName, final String url, final String fileName, final IProgressListener pl) throws Exception { pl.setName(fileName); pl.setProgress(0); pl.setFinished(false); pl.setStarted(true); String installDirName = extDir + File.separator + extName; Log.log("extension installation directory: " + installDirName); File installDir = new File(installDirName); if (!installDir.exists()) { if (!installDir.mkdirs()) { throw new Exception("ExtensionLoader.loadJar: Cannot create install directory: " + installDirName); } } URL downloadURL = new URL(url + fileName); File jarFile = new File(installDirName, fileName); File indexFile = null; long urlTimeStamp = downloadURL.openConnection().getLastModified(); String indexFileName = ""; int idx = fileName.lastIndexOf("."); if (idx > 0) { indexFileName = fileName.substring(0, idx); } else { indexFileName = fileName; } indexFileName = indexFileName + ".idx"; Log.log("index filename: " + indexFileName); boolean isDirty = true; if (jarFile.exists()) { Log.log("extensionfile already exists: " + fileName); indexFile = new File(installDir, indexFileName); if (indexFile.exists()) { Log.log("indexfile already exists"); long cachedTimeStamp = readTimeStamp(indexFile); isDirty = !(cachedTimeStamp == urlTimeStamp); Log.log("cached file dirty: " + isDirty + ", url timestamp: " + urlTimeStamp + " cache stamp: " + cachedTimeStamp); } else { Log.log("indexfile doesn't exist, assume cache is dirty"); } } if (isDirty) { if (jarFile.exists()) { if (indexFile != null && indexFile.exists()) { Log.log("deleting old index file"); indexFile.delete(); } indexFile = new File(installDirName, indexFileName); Log.log("deleting old cached file"); jarFile.delete(); } downloadJar(downloadURL, jarFile, pl); indexFile = new File(installDir, indexFileName); Log.log("writing timestamp to index file"); writeTimeStamp(indexFile, urlTimeStamp); } addJar(jarFile); }
Code Sample 2:
public List execute(ComClient comClient) throws Exception { ArrayList outStrings = new ArrayList(); SearchResult sr = Util.getSearchResultByIDAndNum(SearchManager.getInstance(), qID, dwNum); for (int i = 0; i < checkerUrls.length; i++) { String parametrizedURL = checkerUrls[i]; Iterator mtIter = sr.iterateMetatags(); while (mtIter.hasNext()) { Map.Entry mt = (Map.Entry) mtIter.next(); parametrizedURL = parametrizedURL.replaceAll("%%" + mt.getKey() + "%%", mt.getValue().toString()); if (mt.getKey().equals("fake") && ((Boolean) mt.getValue()).booleanValue()) { outStrings.add("it's a fake."); return outStrings; } } parametrizedURL = parametrizedURL.replaceAll("%%fileid%%", sr.getFileHash().toString()); System.out.println("parametrizedURL=" + parametrizedURL); try { URL url = new URL(parametrizedURL); URLConnection connection = url.openConnection(); connection.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String str = null; while ((str = br.readLine()) != null) { System.out.println(str); if (str.indexOf(fakeMarks[i]) != -1) { System.out.println("FAKEFAKEFAKE"); sr.addMetatag("fake", Boolean.TRUE); outStrings.add("it's a fake."); break; } } } catch (MalformedURLException murl_err) { murl_err.printStackTrace(); } catch (IOException io_err) { io_err.printStackTrace(); } catch (Exception err) { err.printStackTrace(); } } return outStrings; } |
11
| Code Sample 1:
void IconmenuItem6_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setDefaultPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getDefaultPath().lastIndexOf(separator); String imgName = getDefaultPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getDefaultPath()); File outputFile = new File(newPath); 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); } setDefaultPath(newPath); createDefaultImage(); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } |
00
| Code Sample 1:
public static boolean validPassword(String password, String passwordInDb) throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] pwdInDb = hexStringToByte(passwordInDb); byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH]; System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length); if (Arrays.equals(digest, digestInDb)) { return true; } else { return false; } }
Code Sample 2:
public MpegPresentation(URL url) throws IOException { File file = new File(url.getPath()); InputStream input = url.openStream(); DataInputStream ds = new DataInputStream(input); try { parseFile(ds); prepareTracks(); if (audioTrackBox != null && audioHintTrackBox != null) { audioTrack = new AudioTrack(audioTrackBox, audioHintTrackBox, file); } if (videoTrackBox != null && videoHintTrackBox != null) { videoTrack = new VideoTrack(videoTrackBox, videoHintTrackBox, file); } } finally { ds.close(); input.close(); } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.