func1
stringlengths 254
2.93k
| func2
stringlengths 254
2.97k
| label
int64 0
1
|
|---|---|---|
private void copy(File source, File destinationDirectory) throws IOException {
if (source.isDirectory()) {
File newDir = new File(destinationDirectory, source.getName());
newDir.mkdir();
File[] children = source.listFiles();
for (int i = 0; i < children.length; i++) {
if (children[i].getName().equals(".svn")) {
continue;
}
copy(children[i], newDir);
}
} else {
File newFile = new File(destinationDirectory, source.getName());
if (newFile.exists() && source.lastModified() == newFile.lastModified()) {
return;
}
FileOutputStream output = new FileOutputStream(newFile);
FileInputStream input = new FileInputStream(source);
byte[] buff = new byte[2048];
int read = 0;
while ((read = input.read(buff)) > 0) {
output.write(buff, 0, read);
}
output.flush();
output.close();
input.close();
}
}
|
public static void main(String[] args) {
try {
URL url = new URL(args[0]);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
out.write("fatal error");
out.close();
System.out.println("end");
} catch (Exception e) {
e.printStackTrace();
}
}
| 0
|
public boolean resourceExists(String location) {
if ((location == null) || (location.length() == 0)) {
return false;
}
try {
URL url = buildURL(location);
URLConnection cxn = url.openConnection();
InputStream is = null;
try {
byte[] byteBuffer = new byte[2048];
is = cxn.getInputStream();
while (is.read(byteBuffer, 0, 2048) >= 0) ;
return true;
} finally {
if (is != null) {
is.close();
}
}
} catch (IOException ex) {
return false;
}
}
|
public static String doCrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md;
md = MessageDigest.getInstance("SHA-1");
byte[] sha1hash = new byte[40];
md.update(text.getBytes("UTF-8"), 0, text.length());
sha1hash = md.digest();
return convertToHex(sha1hash);
}
| 0
|
public Object getContent(ContentProducerContext context, String ctxAttrName, Object ctxAttrValue) {
try {
URL url = (getURL() != null) ? new URL(getURL().toExternalForm()) : new URL(((URL) ctxAttrValue).toExternalForm());
InputStream reader = url.openStream();
int available = reader.available();
byte contents[] = new byte[available];
reader.read(contents, 0, available);
reader.close();
return new String(contents);
} catch (Exception ex) {
ex.printStackTrace();
return ex.toString();
}
}
|
private static void copyFile(String src, String target) throws IOException {
FileChannel ic = new FileInputStream(src).getChannel();
FileChannel oc = new FileOutputStream(target).getChannel();
ic.transferTo(0, ic.size(), oc);
ic.close();
oc.close();
}
| 0
|
private void CopyTo(File dest) throws IOException {
FileReader in = null;
FileWriter out = null;
int c;
try {
in = new FileReader(image);
out = new FileWriter(dest);
while ((c = in.read()) != -1) out.write(c);
} finally {
if (in != null) try {
in.close();
} catch (Exception e) {
}
if (out != null) try {
out.close();
} catch (Exception e) {
}
}
}
|
private static String encodeMd5(String key) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(key.getBytes());
byte[] bytes = md.digest();
String result = toHexString(bytes);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
| 0
|
public static void unzip(File file, ZipFile zipFile, File targetDirectory) throws BusinessException {
LOG.info("Unzipping zip file '" + file.getAbsolutePath() + "' to directory '" + targetDirectory.getAbsolutePath() + "'.");
assert (file.exists() && file.isFile());
if (targetDirectory.exists() == false) {
LOG.debug("Creating target directory.");
if (targetDirectory.mkdirs() == false) {
throw new BusinessException("Could not create target directory at '" + targetDirectory.getAbsolutePath() + "'!");
}
}
ZipInputStream zipin = null;
try {
zipin = new ZipInputStream(new FileInputStream(file));
ZipEntry entry = null;
while ((entry = zipin.getNextEntry()) != null) {
LOG.debug("Unzipping entry '" + entry.getName() + "'.");
if (entry.isDirectory()) {
LOG.debug("Skipping directory.");
continue;
}
final File targetFile = new File(targetDirectory, entry.getName());
final File parentTargetFile = targetFile.getParentFile();
if (parentTargetFile.exists() == false) {
LOG.debug("Creating directory '" + parentTargetFile.getAbsolutePath() + "'.");
if (parentTargetFile.mkdirs() == false) {
throw new BusinessException("Could not create target directory at '" + parentTargetFile.getAbsolutePath() + "'!");
}
}
InputStream input = null;
FileOutputStream output = null;
try {
input = zipFile.getInputStream(entry);
if (targetFile.createNewFile() == false) {
throw new BusinessException("Could not create target file '" + targetFile.getAbsolutePath() + "'!");
}
output = new FileOutputStream(targetFile);
int readBytes = 0;
byte[] buffer = new byte[BUFFER_SIZE];
while ((readBytes = input.read(buffer, 0, buffer.length)) > 0) {
output.write(buffer, 0, readBytes);
}
} finally {
FileUtil.closeCloseable(input);
FileUtil.closeCloseable(output);
}
}
} catch (IOException e) {
throw new BusinessException("Could not unzip file '" + file.getAbsolutePath() + "'!", e);
} finally {
FileUtil.closeCloseable(zipin);
}
}
|
public static void Sample1(String myField, String condition1, String condition2) throws SQLException {
Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost/test", "user", "password");
connection.setAutoCommit(false);
PreparedStatement ps = connection.prepareStatement("UPDATE myTable SET myField = ? WHERE myOtherField1 = ? AND myOtherField2 = ?");
ps.setString(1, myField);
ps.setString(2, condition1);
ps.setString(3, condition2);
// If more than 10 entries change, panic and rollback
int numChanged = ps.executeUpdate();
if(numChanged > 10) {
connection.rollback();
} else {
connection.commit();
}
ps.close();
connection.close();
}
| 0
|
public void writeData(String name, int items, int mzmin, int mzmax, long tstart, long tdelta, int[] peaks) {
PrintWriter file = getWriter(name + ".txt");
file.print("Filename\t");
file.print("Date\t");
file.print("Acquisition #\t");
file.print("�m Diameter\t");
for (int i = mzmin; i <= mzmax; i++) file.print(i + "\t");
file.println();
int nothing = 0;
String fileLoc = "C:/abcd/" + name + ".txt\t";
Date tempDate;
for (int i = 0; i < items; i++) {
tempDate = new Date(tstart);
tstart += tdelta;
file.print(fileLoc);
file.print(dateFormat.format(tempDate) + "\t");
file.print(i + 1 + "\t");
double t = (double) (i) / 10;
file.print(t + "\t");
boolean peaked = false;
for (int k = mzmin; k <= mzmax; k++) {
for (int j = 0; j < peaks.length && !peaked; j++) {
if (k == peaks[j]) {
file.print(peakVals[j % peakVals.length] + "\t");
peaked = true;
}
}
if (!peaked) {
if (k == mzmax) file.print(nothing); else file.print(nothing + "\t");
}
peaked = false;
}
file.println();
}
try {
Scanner test = new Scanner(f);
while (test.hasNext()) {
System.out.println(test.nextLine());
}
System.out.println("test");
} catch (Exception e) {
}
file.close();
}
|
public String encrypt(String password) throws Exception {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(password.getBytes());
BigInteger hash = new BigInteger(1, md5.digest());
String hashword = hash.toString(16);
return hashword;
}
| 0
|
public static MessageService getMessageService(String fileId) {
MessageService ms = null;
if (serviceCache == null) init();
if (serviceCache.containsKey(fileId)) return serviceCache.get(fileId);
Properties p = new Properties();
try {
URL url = I18nPlugin.getFileURL(fileId);
p.load(url.openStream());
ms = new MessageService(p);
} catch (Exception e) {
ms = new MessageService();
}
serviceCache.put(fileId, ms);
return ms;
}
|
private void startScript(wabclient.Attributes prop) throws SAXException {
dialog.beginScript();
String url = prop.getValue("src");
if (url.length() > 0) {
try {
BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
String buffer;
while (true) {
buffer = r.readLine();
if (buffer == null) break;
dialog.script += buffer + "\n";
}
r.close();
dialog.endScript();
} catch (IOException ioe) {
System.err.println("[IOError] " + ioe.getMessage());
System.exit(0);
}
}
}
| 0
|
public static void copyFile(File source, File destination) throws IOException {
FileChannel in = null;
FileChannel out = null;
try {
in = new FileInputStream(source).getChannel();
out = new FileOutputStream(destination).getChannel();
in.transferTo(0, in.size(), out);
} finally {
if (in != null) in.close();
if (out != null) out.close();
}
}
|
public static void main(String[] args) {
FTPClient client = new FTPClient();
String sFTP = "ftp.miservidor.com";
String sUser = "usuario";
String sPassword = "password";
try {
System.out.println("Conectandose a " + sFTP);
client.connect(sFTP);
boolean login = client.login(sUser, sPassword);
if (login) {
System.out.println("Login correcto");
boolean logout = client.logout();
if (logout) {
System.out.println("Logout del servidor FTP");
}
} else {
System.out.println("Error en el login.");
}
System.out.println("Desconectando.");
client.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
| 0
|
public boolean clonarFichero(FileInputStream rutaFicheroOrigen, String rutaFicheroDestino) {
System.out.println("");
boolean estado = false;
try {
FileOutputStream salida = new FileOutputStream(rutaFicheroDestino);
FileChannel canalOrigen = rutaFicheroOrigen.getChannel();
FileChannel canalDestino = salida.getChannel();
canalOrigen.transferTo(0, canalOrigen.size(), canalDestino);
rutaFicheroOrigen.close();
salida.close();
estado = true;
} catch (IOException e) {
System.out.println("No se encontro el archivo");
e.printStackTrace();
estado = false;
}
return estado;
}
|
public FTPFile[] connect() {
if (ftpe == null) {
ftpe = new FTPEvent(this);
}
if (ftp == null) {
ftp = new FTPClient();
} else if (ftp.isConnected()) {
path = "";
try {
ftp.disconnect();
} catch (IOException e1) {
log.error("could not disconnect -" + e1.getMessage());
}
}
currentDir = new FTPFile[0];
log.debug("try to connect");
try {
int reply;
ftp.connect(ftpsite);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
log.error("FTP server refused connection.");
}
} catch (IOException e) {
log.error("FTPConnection error: " + e.getMessage());
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException f) {
}
}
}
try {
if (!ftp.login(user, password)) {
log.error("could not login with: " + user);
ftp.logout();
}
log.debug("Remote system is " + ftp.getSystemName());
ftp.enterLocalPassiveMode();
currentDir = ftp.listFiles();
} catch (FTPConnectionClosedException e) {
log.error("FTPConnectionClosedException: " + e.getMessage());
} catch (IOException e) {
log.error("IOException: " + e.getMessage());
}
ftpe.setType(FTPEvent.CONNECT);
fireFTPEvent(ftpe);
return currentDir;
}
| 0
|
@Override
public void sendErrorMessage(String message) throws EntriesException, StatementNotExecutedException, NotConnectedException, MessagingException {
if (query == null) {
throw new NotConnectedException();
}
ArrayList<String> recipients = query.getUserManager().getTecMail();
Mail mail = new Mail(recipients);
try {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("log/ossobooklog.zip"));
FileInputStream fis = new FileInputStream("log/ossobook.log");
ZipEntry entry = new ZipEntry("ossobook.log");
zos.putNextEntry(entry);
byte[] buffer = new byte[8192];
int read = 0;
while ((read = fis.read(buffer, 0, 1024)) != -1) {
zos.write(buffer, 0, read);
}
zos.closeEntry();
fis.close();
zos.close();
mail.sendErrorMessage(message, new File("log/ossobooklog.zip"), getUserName());
} catch (Exception ex) {
ex.printStackTrace();
}
}
|
private void Submit2URL(URL url) throws Exception {
HttpURLConnection urlc = null;
try {
urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestMethod("GET");
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setUseCaches(false);
urlc.setAllowUserInteraction(false);
if (urlc.getResponseCode() != 200) {
InputStream in = null;
Reader reader = null;
try {
in = urlc.getInputStream();
reader = new InputStreamReader(in, "UTF-8");
int read = 0;
char[] buf = new char[1024];
String error = null;
while ((read = reader.read(buf)) >= 0) {
if (error == null) error = new String(buf, 0, read); else error += new String(buf, 0, read);
}
throw new NpsException(error, ErrorHelper.SYS_UNKOWN);
} finally {
if (reader != null) try {
reader.close();
} catch (Exception e1) {
}
if (in != null) try {
in.close();
} catch (Exception e1) {
}
}
}
} finally {
if (urlc != null) try {
urlc.disconnect();
} catch (Exception e1) {
}
}
}
| 0
|
private static InputStream openNamedResource(String name) throws java.io.IOException {
InputStream in = null;
boolean result = false;
boolean httpURL = true;
URL propsURL = null;
try {
propsURL = new URL(name);
} catch (MalformedURLException ex) {
httpURL = false;
propsURL = null;
}
if (propsURL == null) {
propsURL = UserProperties.class.getResource(name);
}
if (propsURL != null) {
URLConnection urlConn = propsURL.openConnection();
if (httpURL) {
String hdrVal = urlConn.getHeaderField(0);
if (hdrVal != null) {
String code = HTTPUtilities.getResultCode(hdrVal);
if (code != null) {
if (!code.equals("200")) {
throw new java.io.IOException("status code = " + code);
}
}
}
}
in = urlConn.getInputStream();
}
return in;
}
|
public static void save(String packageName, ArrayList<byte[]> fileContents, ArrayList<String> fileNames) throws Exception {
String dirBase = Util.JAVA_DIR + File.separator + packageName;
File packageDir = new File(dirBase);
if (!packageDir.exists()) {
boolean created = packageDir.mkdir();
if (!created) {
File currentPath = new File(".");
throw new Exception("Directory " + packageName + " could not be created. Current directory: " + currentPath.getAbsolutePath());
}
}
for (int i = 0; i < fileContents.size(); i++) {
File file = new File(Util.JAVA_DIR + File.separator + fileNames.get(i));
FileOutputStream fos = new FileOutputStream(file);
fos.write(fileContents.get(i));
fos.flush();
fos.close();
}
for (int i = 0; i < fileNames.size(); i++) {
File fileSrc = new File(Util.JAVA_DIR + File.separator + fileNames.get(i));
File fileDst = new File(dirBase + File.separator + fileNames.get(i));
BufferedReader reader = new BufferedReader(new FileReader(fileSrc));
BufferedWriter writer = new BufferedWriter(new FileWriter(fileDst));
writer.append("package " + packageName + ";\n");
String line = "";
while ((line = reader.readLine()) != null) writer.append(line + "\n");
writer.flush();
writer.close();
reader.close();
}
}
| 0
|
@Override
protected String doInBackground(String... params) {
try {
final HttpParams param = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(param, 30000);
HttpConnectionParams.setSoTimeout(param, 30000);
DefaultHttpClient client = new DefaultHttpClient(param);
HttpPost post = new HttpPost("http://www.google.com/loc/json");
post.setEntity(new StringEntity(params[0]));
if (DEBUG) Log.d("Location", params[0]);
HttpResponse resp = client.execute(post);
if (resp.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = resp.getEntity();
String result = EntityUtils.toString(entity);
return result;
} else {
if (isFirstLocation) {
requestGearsLocation(1);
isFirstLocation = false;
return RESULT_FIRST_FAILE;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
|
public static String getSHADigest(String password) {
String digest = null;
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance("SHA-1");
sha.reset();
sha.update(password.getBytes());
byte[] pwhash = sha.digest();
digest = "{SHA}" + new String(Base64.encode(pwhash));
} catch (NoSuchAlgorithmException nsae) {
CofaxToolsUtil.log("Algorithme SHA-1 non supporte a la creation du hashage" + nsae + id);
}
return digest;
}
| 0
|
public static void init(Locale lng) {
try {
Locale toLoad = lng != null ? lng : DEFAULT_LOCALE;
URL url = ClassLoader.getSystemResource("locales/" + toLoad.getISO3Language() + ".properties");
if (url == null) {
url = ClassLoader.getSystemResource("locales/" + DEFAULT_LOCALE.getISO3Language() + ".properties");
}
PROPS.clear();
PROPS.load(url.openStream());
} catch (IOException ioe) {
try {
URL url = ClassLoader.getSystemResource("locales/" + DEFAULT_LOCALE.getISO3Language() + ".properties");
PROPS.clear();
PROPS.load(url.openStream());
} catch (Exception e) {
e.printStackTrace();
System.exit(99);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(99);
}
}
|
private String cookieString(String url, String ip) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
md.update((url + "&&" + ip + "&&" + salt.toString()).getBytes());
java.math.BigInteger hash = new java.math.BigInteger(1, md.digest());
return hash.toString(16);
} catch (NoSuchAlgorithmException e) {
filterConfig.getServletContext().log(this.getClass().getName() + " error " + e);
return null;
}
}
| 0
|
public String readRemoteFile() throws IOException {
String response = "";
boolean eof = false;
URL url = new URL(StaticData.remoteFile);
InputStream is = url.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String s;
s = br.readLine();
response = s;
while (!eof) {
try {
s = br.readLine();
if (s == null) {
eof = true;
br.close();
} else response += s;
} catch (EOFException eo) {
eof = true;
} catch (IOException e) {
System.out.println("IO Error : " + e.getMessage());
}
}
return response;
}
|
protected JSONObject doJSONRequest(JSONObject jsonRequest) throws JSONRPCException {
HttpPost request = new HttpPost(serviceUri);
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, getConnectionTimeout());
HttpConnectionParams.setSoTimeout(params, getSoTimeout());
HttpProtocolParams.setVersion(params, PROTOCOL_VERSION);
request.setParams(params);
request.addHeader("Authorization", "Basic " + Base64Coder.encodeString(serviceUser + ":" + servicePass));
HttpEntity entity;
try {
entity = new JSONEntity(jsonRequest);
} catch (UnsupportedEncodingException e1) {
throw new JSONRPCException("Unsupported encoding", e1);
}
request.setEntity(entity);
try {
long t = System.currentTimeMillis();
HttpResponse response = httpClient.execute(request);
t = System.currentTimeMillis() - t;
Log.d("json-rpc", "Request time :" + t);
String responseString = EntityUtils.toString(response.getEntity());
responseString = responseString.trim();
JSONObject jsonResponse = new JSONObject(responseString);
if (jsonResponse.has("error")) {
Object jsonError = jsonResponse.get("error");
if (!jsonError.equals(null)) throw new JSONRPCException(jsonResponse.get("error"));
return jsonResponse;
} else {
return jsonResponse;
}
} catch (ClientProtocolException e) {
throw new JSONRPCException("HTTP error", e);
} catch (IOException e) {
throw new JSONRPCException("IO error", e);
} catch (JSONException e) {
throw new JSONRPCException("Invalid JSON response", e);
}
}
| 0
|
public void createFile(File src, String filename) throws IOException {
try {
FileInputStream fis = new FileInputStream(src);
OutputStream fos = this.fileResourceManager.writeResource(this.txId, filename);
IOUtils.copy(fis, fos);
fos.close();
fis.close();
} catch (ResourceManagerException e) {
LOGGER.error(e);
}
}
|
private boolean authenticate(Module module) throws Exception {
SecureRandom rand = SecureRandom.getInstance("SHA1PRNG");
rand.setSeed(System.currentTimeMillis());
byte[] challenge = new byte[16];
rand.nextBytes(challenge);
String b64 = Util.base64(challenge);
Util.writeASCII(out, RSYNCD_AUTHREQD + b64 + "\n");
String reply = Util.readLine(in);
if (reply.indexOf(" ") < 0) {
Util.writeASCII(out, AT_ERROR + ": bad response\n");
if (remoteVersion < 25) Util.writeASCII(out, RSYNCD_EXIT + "\n");
socket.close();
throw new IOException("bad response");
}
String user = reply.substring(0, reply.indexOf(" "));
String response = reply.substring(reply.indexOf(" ") + 1);
if (!module.users.contains(user)) {
Util.writeASCII(out, AT_ERROR + ": user " + user + " not allowed\n");
if (remoteVersion < 25) Util.writeASCII(out, RSYNCD_EXIT + "\n");
socket.close();
throw new IOException("user " + user + " not allowed");
}
LineNumberReader secrets = new LineNumberReader(new FileReader(module.secretsFile));
MessageDigest md4 = MessageDigest.getInstance("BrokenMD4");
String line;
while ((line = secrets.readLine()) != null) {
if (line.startsWith(user + ":")) {
String passwd = line.substring(line.lastIndexOf(":") + 1);
md4.update(new byte[4]);
md4.update(passwd.getBytes("US-ASCII"));
md4.update(b64.getBytes("US-ASCII"));
String hash = Util.base64(md4.digest());
if (hash.equals(response)) {
secrets.close();
return true;
} else {
Util.writeASCII(out, AT_ERROR + ": auth failed on module " + module.name + "\n");
if (remoteVersion < 25) Util.writeASCII(out, RSYNCD_EXIT + "\n");
socket.close();
secrets.close();
logger.error("auth failed on module " + module.name);
return false;
}
}
}
Util.writeASCII(out, AT_ERROR + ": auth failed on module " + module.name + "\n");
if (remoteVersion < 25) Util.writeASCII(out, RSYNCD_EXIT + "\n");
socket.close();
secrets.close();
logger.error("auth failed on module " + module.name);
return false;
}
| 0
|
public static void doVersionCheck(View view) {
view.showWaitCursor();
try {
URL url = new URL(jEdit.getProperty("version-check.url"));
InputStream in = url.openStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
String line;
String develBuild = null;
String stableBuild = null;
while ((line = bin.readLine()) != null) {
if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim();
}
bin.close();
if (develBuild != null && stableBuild != null) {
doVersionCheck(view, stableBuild, develBuild);
}
} catch (IOException e) {
String[] args = { jEdit.getProperty("version-check.url"), e.toString() };
GUIUtilities.error(view, "read-error", args);
}
view.hideWaitCursor();
}
|
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md;
md = MessageDigest.getInstance("MD5");
byte[] md5hash = new byte[32];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
md5hash = md.digest();
return convertToHex(md5hash);
}
| 0
|
public static synchronized Document readRemoteDocument(URL url, boolean validate) throws IOException, SAXParseException {
if (DEBUG) System.out.println("DocumentUtilities.readDocument( " + url + ")");
Document document = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setCoalescing(true);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDefaultUseCaches(false);
connection.setUseCaches(false);
connection.setRequestProperty("User-Agent", "eXchaNGeR/" + System.getProperty("xngr.version") + " (http://xngr.org/)");
connection.connect();
InputStream stream = connection.getInputStream();
document = factory.newDocumentBuilder().parse(stream);
stream.close();
connection.disconnect();
} catch (SAXException e) {
if (e instanceof SAXParseException) {
throw (SAXParseException) e;
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
if (DEBUG) System.out.println("DocumentUtilities.readDocument( " + url + ") [" + document + "]");
return document;
}
|
public void genDropSchema(DiagramModel diagramModel, boolean foreignKeys) {
try {
con.setAutoCommit(false);
stmt = con.createStatement();
Collection boxes = diagramModel.getBoxes();
BoxModel box;
String sqlQuery;
if (foreignKeys) {
for (Iterator x = boxes.iterator(); x.hasNext(); ) {
box = (BoxModel) x.next();
if (!box.isAbstractDef()) {
dropForeignKeys(box);
}
}
}
int counter = 0;
for (Iterator x = boxes.iterator(); x.hasNext(); ) {
box = (BoxModel) x.next();
if (!box.isAbstractDef()) {
sqlQuery = sqlDropTable(box);
System.out.println(sqlQuery);
try {
stmt.executeUpdate(sqlQuery);
counter++;
} catch (SQLException e) {
String tableName = box.getName();
System.out.println("// Problem while dropping table " + tableName + " : " + e.getMessage());
String msg = Para.getPara().getText("tableNotDropped") + " -- " + tableName;
this.informUser(msg);
}
}
}
con.commit();
if (counter > 0) {
String msg = Para.getPara().getText("schemaDropped") + " -- " + counter + " " + Para.getPara().getText("tables");
this.informUser(msg);
} else {
this.informUser(Para.getPara().getText("schemaNotDropped"));
}
} catch (SQLException e) {
System.out.println(e.getMessage() + " // Problem with the JDBC schema generation! ");
try {
con.rollback();
this.informUser(Para.getPara().getText("schemaNotDropped"));
} catch (SQLException e1) {
System.out.println(e1.getMessage() + " // Problem with the connection rollback! ");
}
} finally {
try {
con.setAutoCommit(true);
stmt.close();
} catch (SQLException e1) {
System.out.println(e1.getMessage() + " // Problem with the connection disconnect! ");
}
}
}
| 0
|
public static void main(String[] args) {
File srcDir = new File(args[0]);
File dstDir = new File(args[1]);
File[] srcFiles = srcDir.listFiles();
for (File f : srcFiles) {
if (f.isDirectory()) continue;
try {
FileChannel srcChannel = new FileInputStream(f).getChannel();
FileChannel dstChannel = new FileOutputStream(dstDir.getAbsolutePath() + System.getProperty("file.separator") + f.getName()).getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int nr = 0;
srcChannel.position(nr);
nr += srcChannel.read(buffer);
while (nr < f.length()) {
buffer.flip();
dstChannel.write(buffer);
buffer.clear();
nr += srcChannel.read(buffer);
}
srcChannel.close();
dstChannel.close();
} catch (IOException e) {
}
}
}
|
public void testPreparedStatement0009() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0009 " + " (i integer not null, " + " s char(10) not null) ");
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement("insert into #t0009 values (?, ?)");
int rowsToAdd = 8;
final String theString = "abcdefghijklmnopqrstuvwxyz";
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
pstmt.close();
assertEquals(count, rowsToAdd);
con.rollback();
ResultSet rs = stmt.executeQuery("select s, i from #t0009");
assertNotNull(rs);
count = 0;
while (rs.next()) {
count++;
assertEquals(rs.getString(1).trim().length(), rs.getInt(2));
}
assertEquals(count, 0);
con.commit();
pstmt = con.prepareStatement("insert into #t0009 values (?, ?)");
rowsToAdd = 6;
count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
assertEquals(count, rowsToAdd);
con.commit();
pstmt.close();
rs = stmt.executeQuery("select s, i from #t0009");
count = 0;
while (rs.next()) {
count++;
assertEquals(rs.getString(1).trim().length(), rs.getInt(2));
}
assertEquals(count, rowsToAdd);
con.commit();
stmt.close();
con.setAutoCommit(true);
}
| 0
|
protected void doSetInput(IEditorInput input, IProgressMonitor monitor) throws CoreException {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IFileFormat format = null;
Object source = null;
InputStream in = null;
try {
IPath path;
if (input instanceof IStorageEditorInput) {
IStorage s = ((IStorageEditorInput) input).getStorage();
in = s.getContents();
if (s instanceof IFile) {
IFile file = (IFile) s;
path = file.getRawLocation();
if (root.exists(path)) {
path = root.getLocation().append(path);
}
source = path.toFile();
}
} else if (input instanceof IPathEditorInput) {
path = ((IPathEditorInput) input).getPath();
source = path.toFile();
} else if (input instanceof IURIEditorInput) {
URI uri = ((IURIEditorInput) input).getURI();
if (URIUtil.isFileURI(uri)) {
source = URIUtil.toFile(uri);
} else {
URL url = URIUtil.toURL(uri);
in = url.openStream();
}
}
if (source == null) {
if (!in.markSupported()) {
in = new BufferedInputStream(in);
}
in.mark(10);
source = in;
}
IContentDescription cd = Platform.getContentTypeManager().getDescriptionFor(in, input.getName(), new QualifiedName[] { ImageCore.VALID_FORMATS });
if (in != null) {
in.reset();
}
Collection<?> valid = (Collection<?>) cd.getProperty(ImageCore.VALID_FORMATS);
if (valid.isEmpty()) throw new CoreException(new Status(Status.ERROR, ImageUI.PLUGIN_ID, "Unsupported file format."));
ImageInputStream stream = ImageIO.createImageInputStream(source);
format = (IFileFormat) valid.iterator().next();
IDocument document = format.decode(stream, monitor);
setDocument(document);
} catch (IOException e) {
Status status = new Status(Status.ERROR, ImageUI.PLUGIN_ID, "IO Error", e);
throw new CoreException(status);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
super.setInput(input);
}
|
public static void doVersionCheck(View view) {
view.showWaitCursor();
try {
URL url = new URL(jEdit.getProperty("version-check.url"));
InputStream in = url.openStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
String line;
String develBuild = null;
String stableBuild = null;
while ((line = bin.readLine()) != null) {
if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim();
}
bin.close();
if (develBuild != null && stableBuild != null) {
doVersionCheck(view, stableBuild, develBuild);
}
} catch (IOException e) {
String[] args = { jEdit.getProperty("version-check.url"), e.toString() };
GUIUtilities.error(view, "read-error", args);
}
view.hideWaitCursor();
}
| 0
|
private static long copy(InputStream source, OutputStream sink) {
try {
return IOUtils.copyLarge(source, sink);
} catch (IOException e) {
logger.error(e.toString(), e);
throw new FaultException("System error copying stream", e);
} finally {
IOUtils.closeQuietly(source);
IOUtils.closeQuietly(sink);
}
}
|
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new URL(urlInfo).openStream()));
String ligneEnCours;
int i = 0;
informations = "";
while ((ligneEnCours = in.readLine()) != null) {
switch(i) {
case 0:
version = ligneEnCours;
break;
case 1:
url = ligneEnCours;
break;
default:
informations += ligneEnCours + '\n';
break;
}
i++;
}
in.close();
erreur = false;
} catch (IOException e) {
erreur = true;
texteErreur = e.getMessage();
if (texteErreur.equals("Network is unreachable")) {
texteErreur = "Pas de réseau";
numErreur = 1;
}
if (e instanceof FileNotFoundException) {
texteErreur = "Problème paramétrage";
numErreur = 2;
}
e.printStackTrace();
} finally {
for (ActionListener al : listeners) {
al.actionPerformed(null);
}
}
}
| 0
|
public String getServerHash(String passwordHash, String PasswordSalt) throws PasswordHashingException {
byte[] hash;
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
digest.update(PasswordSalt.getBytes("UTF-16"));
hash = digest.digest(passwordHash.getBytes("UTF-16"));
return bytesToHex(hash);
} catch (NoSuchAlgorithmException ex) {
throw new PasswordHashingException("Current environment does not supply needed security algorithms. Please update Java");
} catch (UnsupportedEncodingException ex) {
throw new PasswordHashingException("Current environment does not supply needed character encoding. Please update Java");
}
}
|
public HttpResponseExchange execute() throws Exception {
HttpResponseExchange forwardResponse = null;
int fetchSizeLimit = Config.getInstance().getFetchLimitSize();
while (null != lastContentRange) {
forwardRequest.setBody(new byte[0]);
ContentRangeHeaderValue old = lastContentRange;
long sendSize = fetchSizeLimit;
if (old.getInstanceLength() - old.getLastBytePos() - 1 < fetchSizeLimit) {
sendSize = (old.getInstanceLength() - old.getLastBytePos() - 1);
}
if (sendSize <= 0) {
break;
}
lastContentRange = new ContentRangeHeaderValue(old.getLastBytePos() + 1, old.getLastBytePos() + sendSize, old.getInstanceLength());
forwardRequest.setHeader(HttpHeaders.Names.CONTENT_RANGE, lastContentRange);
forwardRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sendSize));
forwardResponse = syncFetch(forwardRequest);
if (sendSize < fetchSizeLimit) {
lastContentRange = null;
}
}
return forwardResponse;
}
| 0
|
public static String getMD5(String source) {
String s = null;
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
md.update(source.getBytes());
byte tmp[] = md.digest();
char str[] = new char[16 * 2];
int k = 0;
for (int i = 0; i < 16; i++) {
byte byte0 = tmp[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
s = new String(str);
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
|
private boolean getWave(String url, String Word) {
try {
File FF = new File(f.getParent() + "/" + f.getName() + "pron");
FF.mkdir();
URL url2 = new URL(url);
BufferedReader stream = new BufferedReader(new InputStreamReader(url2.openStream()));
File Fdel = new File(f.getParent() + "/" + f.getName() + "pron/" + Word + ".wav");
if (!Fdel.exists()) {
FileOutputStream outstream = new FileOutputStream(f.getParent() + "/" + f.getName() + "pron/" + Word + ".wav");
BufferedWriter bwriter = new BufferedWriter(new OutputStreamWriter(outstream));
char[] binput = new char[1024];
int len = stream.read(binput, 0, 1024);
while (len > 0) {
bwriter.write(binput, 0, len);
len = stream.read(binput, 0, 1024);
}
bwriter.close();
outstream.close();
}
stream.close();
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
return true;
}
| 0
|
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();
}
|
public static void insertDocumentToURL(String file, String target) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(file);
final URL url = new URL(target);
final URLConnection connection = url.openConnection();
os = connection.getOutputStream();
TestTools.copyStream(is, os);
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
}
| 0
|
public Document index() throws CrawlingException {
log.debug("BEGINIG indexing page [code=" + getCode() + "] ...");
URL url = null;
InputStream in = null;
String contentType = null;
try {
url = new URL(getServer().getProtocol() + "://" + getServer().getHost() + ":" + getServer().getPort() + getPath());
HttpURLConnection pageContent = (HttpURLConnection) url.openConnection();
if (pageContent.getResponseCode() != HttpURLConnection.HTTP_OK) {
log.debug("page pk[" + getCode() + "," + url.toExternalForm() + "] is invalid");
return null;
}
String redireccion = pageContent.getHeaderField("location");
if (redireccion != null) {
log.debug("Page " + url.toExternalForm() + " redirected to " + redireccion);
recordLink(redireccion);
return null;
}
contentType = pageContent.getContentType();
in = new BufferedInputStream(pageContent.getInputStream(), 32768);
} catch (MalformedURLException e) {
log.error("Invalid page address", e);
} catch (ConnectException e) {
if (getServer() != null) {
log.error("Unable to connect to page: " + getServer().getProtocol() + "://" + getServer().getHost() + ":" + getServer().getPort() + getPath(), e);
}
} catch (UnknownHostException uhe) {
log.warn("Unknow host indexing page " + getURL(), uhe);
} catch (IOException e) {
log.warn("Unable to index page " + getURL(), e);
}
Document doc = generateDocument(contentType, in);
log.debug("END indexing page [code=" + getCode() + "]");
return doc;
}
|
public void run(String[] args) throws Throwable {
FileInputStream input = new FileInputStream(args[0]);
FileOutputStream output = new FileOutputStream(args[0] + ".out");
Reader reader = $(Reader.class, $declass(input));
Writer writer = $(Writer.class, $declass(output));
Pump pump;
if (args.length > 1 && "diag".equals(args[1])) {
pump = $(new Reader() {
int counter;
@ToContext(mode = InvocationMode.sideEffect)
public int read(byte[] buffer, int off, int len) throws Exception {
Integer rd = (Integer) $next();
if (rd > 0) {
counter += rd;
}
return 0;
}
@ToContext(mode = InvocationMode.sideEffect)
public void close() throws Exception {
System.out.println("Read from input " + counter + " bytes.");
}
}, reader, writer, new Writer() {
int counter;
@ToContext(mode = InvocationMode.sideEffect)
public void write(byte[] buffer, int off, int len) throws Exception {
counter += len;
}
@ToContext(mode = InvocationMode.sideEffect)
public void close() throws Exception {
System.out.println("Written to output " + counter + " bytes.");
}
});
} else {
pump = $(reader, writer);
}
pump.pump();
}
| 0
|
private VelocityEngine newVelocityEngine() {
VelocityEngine velocityEngine = null;
InputStream is = null;
try {
URL url = ClassPathUtils.getResource(VELOCITY_PROPS_FILE);
is = url.openStream();
Properties props = new Properties();
props.load(is);
velocityEngine = new VelocityEngine(props);
velocityEngine.init();
} catch (Exception e) {
throw new RuntimeException("can not find velocity props file, file=" + VELOCITY_PROPS_FILE, e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return velocityEngine;
}
|
private static void copyFiles(String strPath, String dstPath) throws Exception {
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() + "\\" + list[i];
String src1 = src.getAbsolutePath() + "\\" + list[i];
copyFiles(src1, dest1);
}
} else {
FileChannel sourceChannel = new FileInputStream(src).getChannel();
FileChannel targetChannel = new FileOutputStream(dest).getChannel();
sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
sourceChannel.close();
targetChannel.close();
}
}
| 0
|
public void actionPerformed(ActionEvent e) {
if ("register".equals(e.getActionCommand())) {
buttonClicked = "register";
try {
String data = URLEncoder.encode("ver", "UTF-8") + "=" + URLEncoder.encode(Double.toString(questVer), "UTF-8");
data += "&" + URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name.getText(), "UTF-8");
data += "&" + URLEncoder.encode("os", "UTF-8") + "=" + URLEncoder.encode(os.getText(), "UTF-8");
data += "&" + URLEncoder.encode("jre", "UTF-8") + "=" + URLEncoder.encode(jre.getText(), "UTF-8");
data += "&" + URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email.getText(), "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("Qr7SchF", "UTF-8");
data += "&" + URLEncoder.encode("answers", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(getAnswers()), "UTF-8");
URL url = new URL("http://ubcdcreator.sourceforge.net/register.php");
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
}
rd.close();
wr.close();
} catch (Exception ex) {
}
setVisible(false);
} else if ("cancel".equals(e.getActionCommand())) {
buttonClicked = "cancel";
setVisible(false);
} else if ("never".equals(e.getActionCommand())) {
buttonClicked = "never";
setVisible(false);
}
}
|
public static void extractFile(String input, String output) throws ZipException, IOException {
FileReader reader = new FileReader(input);
InputStream in = reader.getInputStream();
OutputStream out = new FileOutputStream(new File(output));
byte[] buf = new byte[512];
int len;
while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
reader.close();
out.close();
}
| 0
|
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == jbutton) {
try {
String toservlet = "http://localhost:8080/direto-project/arquivos/teste.odt";
URL servleturl = new URL(toservlet);
URLConnection servletconnection = servleturl.openConnection();
servletconnection.setDoInput(true);
servletconnection.setDoOutput(true);
servletconnection.setUseCaches(false);
servletconnection.setDefaultUseCaches(false);
DataInputStream inputFromClient = new DataInputStream(servletconnection.getInputStream());
inputFromClient.readByte();
OutputStream fos = new FileOutputStream("/home/danillo/arquivo_carregado.odt");
byte[] buf = new byte[1024];
int bytesread;
while ((bytesread = inputFromClient.read(buf)) > -1) {
fos.write(buf, 0, bytesread);
}
inputFromClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
public static boolean copyFile(final File src, final File dst) {
boolean result = false;
FileChannel inChannel = null;
FileChannel outChannel = null;
synchronized (FileUtil.DATA_LOCK) {
try {
inChannel = new FileInputStream(src).getChannel();
outChannel = new FileOutputStream(dst).getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
result = true;
} catch (IOException e) {
} finally {
if (inChannel != null && inChannel.isOpen()) {
try {
inChannel.close();
} catch (IOException e) {
}
}
if (outChannel != null && outChannel.isOpen()) {
try {
outChannel.close();
} catch (IOException e) {
}
}
}
}
return result;
}
| 0
|
public static String createPseudoUUID() {
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(new UID().toString().getBytes());
try {
String localHost = InetAddress.getLocalHost().toString();
messageDigest.update(localHost.getBytes());
} catch (UnknownHostException e) {
throw new OXFException(e);
}
byte[] digestBytes = messageDigest.digest();
StringBuffer sb = new StringBuffer();
sb.append(toHexString(NumberUtils.readIntBigEndian(digestBytes, 0)));
sb.append('-');
sb.append(toHexString(NumberUtils.readShortBigEndian(digestBytes, 4)));
sb.append('-');
sb.append(toHexString(NumberUtils.readShortBigEndian(digestBytes, 6)));
sb.append('-');
sb.append(toHexString(NumberUtils.readShortBigEndian(digestBytes, 8)));
sb.append('-');
sb.append(toHexString(NumberUtils.readShortBigEndian(digestBytes, 10)));
sb.append(toHexString(NumberUtils.readIntBigEndian(digestBytes, 12)));
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new OXFException(e);
}
}
|
public Processing getProcess(long processId) throws BookKeeprCommunicationException {
try {
synchronized (httpClient) {
HttpGet req = new HttpGet(remoteHost.getUrl() + "/id/" + Long.toHexString(processId));
HttpResponse resp = httpClient.execute(req);
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
try {
XMLAble xmlable = XMLReader.read(resp.getEntity().getContent());
if (xmlable instanceof Processing) {
Processing p = (Processing) xmlable;
return p;
} else {
throw new BookKeeprCommunicationException("BookKeepr returned the wrong thing for pointingID");
}
} catch (SAXException ex) {
Logger.getLogger(BookKeeprConnection.class.getName()).log(Level.WARNING, "Got a malformed message from the bookkeepr", ex);
throw new BookKeeprCommunicationException(ex);
}
} else {
resp.getEntity().consumeContent();
throw new BookKeeprCommunicationException("Got a " + resp.getStatusLine().getStatusCode() + " from the BookKeepr");
}
}
} catch (HttpException ex) {
throw new BookKeeprCommunicationException(ex);
} catch (IOException ex) {
throw new BookKeeprCommunicationException(ex);
} catch (URISyntaxException ex) {
throw new BookKeeprCommunicationException(ex);
}
}
| 0
|
@Test(expected = GadgetException.class)
public void malformedGadgetSpecIsCachedAndThrows() throws Exception {
HttpRequest request = createCacheableRequest();
expect(pipeline.execute(request)).andReturn(new HttpResponse("malformed junk")).once();
replay(pipeline);
try {
specFactory.getGadgetSpec(createContext(SPEC_URL, false));
fail("No exception thrown on bad parse");
} catch (GadgetException e) {
}
specFactory.getGadgetSpec(createContext(SPEC_URL, false));
}
|
@ActionMethod
public void upload() throws IOException {
final int fileResult = fileChooser.showOpenDialog(frame);
if (fileResult != JFileChooser.APPROVE_OPTION) {
return;
}
final InputStream in = new FileInputStream(fileChooser.getSelectedFile());
try {
final URL url = new URL("http://127.0.0.1:" + testPort + "/databases/" + fileChooser.getSelectedFile().getName());
final HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("PUT");
con.setDoOutput(true);
con.setRequestProperty(Http11Header.AUTHORIZATION, "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
con.setRequestProperty(Http11Header.WWW_AUTHENTICATE, "Basic realm=\"karatasi\"");
con.setRequestProperty(Http11Header.CONTENT_LENGTH, Long.toString(fileChooser.getSelectedFile().length()));
con.setRequestProperty(Http11Header.CONTENT_TYPE, "application/octet-stream");
final OutputStream out = con.getOutputStream();
try {
Util.copy(in, out);
con.connect();
final InputStream in2 = con.getInputStream();
try {
textArea.setText("");
final byte[] buf = new byte[4096];
for (int bytesRead; (bytesRead = in2.read(buf)) != -1; ) {
textArea.append(new String(buf, 0, bytesRead));
}
} finally {
in2.close();
}
} finally {
out.close();
}
} finally {
in.close();
}
}
| 0
|
public void testTransactions() throws Exception {
con = TestUtil.openDB();
Statement st;
ResultSet rs;
con.setAutoCommit(false);
assertTrue(!con.getAutoCommit());
con.setAutoCommit(true);
assertTrue(con.getAutoCommit());
st = con.createStatement();
st.executeUpdate("insert into test_a (imagename,image,id) values ('comttest',1234,5678)");
con.setAutoCommit(false);
st.executeUpdate("update test_a set image=9876 where id=5678");
con.commit();
rs = st.executeQuery("select image from test_a where id=5678");
assertTrue(rs.next());
assertEquals(9876, rs.getInt(1));
rs.close();
st.executeUpdate("update test_a set image=1111 where id=5678");
con.rollback();
rs = st.executeQuery("select image from test_a where id=5678");
assertTrue(rs.next());
assertEquals(9876, rs.getInt(1));
rs.close();
TestUtil.closeDB(con);
}
|
public boolean referredFilesChanged() throws MalformedURLException, IOException {
for (String file : referredFiles) {
if (FileUtils.isURI(file)) {
URLConnection url = new URL(file).openConnection();
if (url.getLastModified() > created) return true;
} else if (FileUtils.isFile(file)) {
File f = new File(file);
if (f.lastModified() > created) return true;
}
}
return false;
}
| 0
|
public boolean deleteRoleType(int id, int namespaceId, boolean removeReferencesInRoleTypes, DTSPermission permit) throws SQLException, PermissionException, DTSValidationException {
checkPermission(permit, String.valueOf(namespaceId));
boolean exist = isRoleTypeUsed(namespaceId, id);
if (exist) {
throw new DTSValidationException(ApelMsgHandler.getInstance().getMsg("DTS-0034"));
}
if (!removeReferencesInRoleTypes) {
StringBuffer msgBuf = new StringBuffer();
DTSTransferObject[] objects = fetchRightIdentityReferences(namespaceId, id);
if (objects.length > 0) {
msgBuf.append("Role Type is Right Identity in one or more Role Types.");
}
objects = fetchParentReferences(namespaceId, id);
if (objects.length > 0) {
if (msgBuf.length() > 0) {
msgBuf.append("\n");
}
msgBuf.append("Role Type is Parent of one or more Role Types.");
}
if (msgBuf.length() > 0) {
throw new DTSValidationException(msgBuf.toString());
}
}
String sqlRightId = getDAO().getStatement(ROLE_TYPE_TABLE_KEY, "DELETE_RIGHT_IDENTITY_REF");
String sqlParent = getDAO().getStatement(ROLE_TYPE_TABLE_KEY, "DELETE_PARENT_REF");
String sql = getDAO().getStatement(ROLE_TYPE_TABLE_KEY, "DELETE");
PreparedStatement pstmt = null;
boolean success = false;
long typeGid = getGID(namespaceId, id);
conn.setAutoCommit(false);
int defaultLevel = conn.getTransactionIsolation();
conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
try {
pstmt = conn.prepareStatement(sqlRightId);
pstmt.setLong(1, typeGid);
pstmt.executeUpdate();
pstmt.close();
pstmt = conn.prepareStatement(sqlParent);
pstmt.setLong(1, typeGid);
pstmt.executeUpdate();
pstmt.close();
pstmt = conn.prepareStatement(sql);
pstmt.setLong(1, typeGid);
int count = pstmt.executeUpdate();
success = (count == 1);
conn.commit();
} catch (SQLException e) {
conn.rollback();
throw e;
} finally {
conn.setTransactionIsolation(defaultLevel);
conn.setAutoCommit(true);
closeStatement(pstmt);
}
return success;
}
|
public static boolean copyFile(String sourceName, String destName) {
FileChannel sourceChannel = null;
FileChannel destChannel = null;
boolean wasOk = false;
try {
sourceChannel = new FileInputStream(sourceName).getChannel();
destChannel = new FileOutputStream(destName).getChannel();
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
wasOk = true;
} catch (Throwable exception) {
logger.log(Level.SEVERE, "Exception in copyFile", exception);
} finally {
try {
if (sourceChannel != null) sourceChannel.close();
} catch (Throwable tt) {
}
try {
if (destChannel != null) destChannel.close();
} catch (Throwable tt) {
}
}
return wasOk;
}
| 0
|
static File copy(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);
return out;
} catch (IOException e) {
throw e;
} finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
}
|
private void update(String statement, SyrupConnection con, boolean do_log) throws Exception {
Statement s = null;
try {
s = con.createStatement();
s.executeUpdate(statement);
con.commit();
} catch (Throwable e) {
if (do_log) {
logger.log(Level.INFO, "Update failed. Transaction is rolled back", e);
}
con.rollback();
}
}
| 0
|
private static String lastModified(URL url) {
try {
URLConnection conn = url.openConnection();
return long2date(conn.getLastModified());
} catch (Exception e) {
SWGAide.printDebug("cach", 1, "SWGCraftCache:lastModified: " + e.getMessage());
}
return "0";
}
|
public static String getMessageDigest(String[] inputs) {
if (inputs.length == 0) return null;
try {
MessageDigest sha = MessageDigest.getInstance("SHA-1");
for (String input : inputs) sha.update(input.getBytes());
byte[] hash = sha.digest();
String CPass = "";
int h = 0;
String s = "";
for (int i = 0; i < 20; i++) {
h = hash[i];
if (h < 0) h += 256;
s = Integer.toHexString(h);
if (s.length() < 2) CPass = CPass.concat("0");
CPass = CPass.concat(s);
}
CPass = CPass.toUpperCase();
return CPass;
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e.getMessage());
}
}
| 0
|
public void uncaughtException(final Thread t, final Throwable e) {
final Display display = Display.getCurrent();
final Shell shell = new Shell(display);
final MessageBox message = new MessageBox(shell, SWT.OK | SWT.CANCEL | SWT.ICON_ERROR);
message.setText("Hawkscope Error");
message.setMessage(e.getMessage() + "\nSubmit Hawkscope Error Report to Issue Tracker?");
log.error("Uncaught exception", e);
if (message.open() == SWT.OK) {
IOUtils.copyToClipboard(Version.getBugReport(e));
try {
Program.launch(Constants.HAWKSCOPE_URL_ROOT + "issues/entry?comment=" + URLEncoder.encode("Please paste the Hawkscope Error " + "Report here. It's currently copied to your " + "clipboard. Thank you for your support!", Constants.ENCODING));
} catch (final Exception e1) {
Program.launch(Constants.HAWKSCOPE_URL_ROOT + "issues/entry");
}
}
shell.dispose();
}
|
public static InputStream getResourceAsStreamIfAny(String resPath) {
URL url = findResource(resPath);
try {
return url == null ? null : url.openStream();
} catch (IOException e) {
ZMLog.warn(e, " URL open Connection got an exception!");
return null;
}
}
| 0
|
public PageLoader(String pageAddress) throws Exception {
URL url = new URL(pageAddress);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
inputLine = "";
while (in.ready()) {
inputLine = inputLine + in.readLine();
}
in.close();
}
|
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException {
int k_blockSize = 1024;
int byteCount;
char[] buf = new char[k_blockSize];
File ofp = new File(outFile);
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp));
zos.setMethod(ZipOutputStream.DEFLATED);
OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1");
BufferedWriter bw = new BufferedWriter(osw);
ZipEntry zot = null;
File ifp = new File(inFile);
ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp));
InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1");
BufferedReader br = new BufferedReader(isr);
ZipEntry zit = null;
while ((zit = zis.getNextEntry()) != null) {
if (zit.getName().equals("content.xml")) {
continue;
}
zot = new ZipEntry(zit.getName());
zos.putNextEntry(zot);
while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount);
bw.flush();
zos.closeEntry();
}
zos.putNextEntry(new ZipEntry("content.xml"));
bw.flush();
osw = new OutputStreamWriter(zos, "UTF8");
bw = new BufferedWriter(osw);
return bw;
}
| 0
|
private void parse() throws Exception {
BufferedReader br = null;
InputStream httpStream = null;
URL fileURL = new URL(url);
URLConnection urlConnection = fileURL.openConnection();
httpStream = urlConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(httpStream, "UTF-8"));
String ligne;
String post;
String date;
String titre;
String resume;
String url2DL;
while ((ligne = br.readLine()) != null) {
if (ligne.indexOf("div class=\"post\" id=\"post") != -1) {
post = null;
date = null;
titre = null;
try {
post = ligne.substring(ligne.indexOf("post-") + 5, ligne.indexOf("\"", ligne.indexOf("post-")));
ligne = br.readLine();
date = ligne.substring(ligne.indexOf("<div class=\"date\"><span>") + 24);
date = date.replaceAll("</span>", "").replaceAll("</div>", "").trim();
log.info("Post : " + post + " du " + date);
ligne = br.readLine();
ligne = br.readLine();
titre = ligne.substring(ligne.indexOf(">", ligne.indexOf("title")) + 1, ligne.indexOf("</a>"));
titre = titre.replaceAll("’", "'").replaceAll("“", "\"").replaceAll("”", "\"");
url2DL = ligne.substring(ligne.indexOf("<a href=\"") + 9, ligne.indexOf("/\"")).trim();
url2DL = url2DL.replace("mega-films.net", "mega-protect.com") + ".php";
log.info("Titre : " + titre);
log.info("To DL : " + url2DL);
ligne = br.readLine();
ligne = br.readLine();
ligne = br.readLine();
ligne = br.readLine();
ligne = br.readLine();
ligne = br.readLine();
ligne = br.readLine();
resume = ligne.substring(ligne.indexOf("<em>") + 4, ligne.indexOf("</em>"));
resume = resume.replaceAll("’", "'").replaceAll("“", "\"").replaceAll("”", "\"");
log.info("Resume : " + resume);
} catch (Exception e) {
log.error("ERREUR : Le film n'a pas pu etre parse...");
}
log.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
}
}
}
|
public Converter(String input, String output) {
try {
FileInputStream fis = new FileInputStream(new File(input));
BufferedReader in = new BufferedReader(new InputStreamReader(fis, "SJIS"));
FileOutputStream fos = new FileOutputStream(new File(output));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));
int len = 80;
char buf[] = new char[len];
int numRead;
while ((numRead = in.read(buf, 0, len)) != -1) out.write(buf, 0, numRead);
out.close();
in.close();
} catch (IOException e) {
System.out.println("An I/O Exception Occurred: " + e);
}
}
| 0
|
private String executePost(String targetURL, String urlParameters) {
URL url;
HttpURLConnection connection = null;
try {
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.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();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
|
public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException {
FileChannel inputChannel = new FileInputStream(inputFile).getChannel();
FileChannel outputChannel = new FileOutputStream(outputFile).getChannel();
try {
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
} catch (IOException e) {
throw e;
} finally {
if (inputChannel != null) inputChannel.close();
if (outputChannel != null) outputChannel.close();
}
}
| 0
|
public static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost(postURL);
File file = new File("d:/hai.html");
System.out.println(ukeycookie);
httppost.setHeader("Cookie", ukeycookie + ";" + skeycookie + ";" + usercookie);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("", cbFile);
httppost.setEntity(mpEntity);
System.out.println("Now uploading your file into mediafire...........................");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Getting upload response key value..........");
uploadresponsekey = EntityUtils.toString(resEntity);
getUploadResponseKey();
System.out.println("upload resoponse key " + uploadresponsekey);
}
}
|
public Wget2(URL url, File f) throws IOException {
System.out.println("bajando: " + url);
if (f == null) {
by = new ByteArrayOutputStream();
} else {
by = new FileOutputStream(f);
}
URLConnection uc = url.openConnection();
if (uc instanceof HttpURLConnection) {
leerHttp((HttpURLConnection) uc);
} else {
throw new IOException("solo se pueden descargar url http");
}
}
| 0
|
static Matrix readMatrix(String filename, int nrow, int ncol) {
Matrix cij = new Matrix(nrow, ncol);
try {
URL url = filename.getClass().getResource(filename);
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(url.openStream()));
for (int i = 0; i < nrow; i++) for (int j = 0; j < ncol; j++) cij.set(i, j, Double.parseDouble(lnr.readLine()));
} catch (Exception xc) {
xc.printStackTrace();
}
return cij;
}
|
public static void copyFile(File in, File out) throws Exception {
FileChannel sourceChannel = null;
FileChannel destinationChannel = null;
try {
sourceChannel = new FileInputStream(in).getChannel();
destinationChannel = new FileOutputStream(out).getChannel();
sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
} finally {
if (sourceChannel != null) sourceChannel.close();
if (destinationChannel != null) destinationChannel.close();
}
}
| 0
|
private static List runITQLQuery(String itqlQuery) throws Exception {
String escapedItqlQuery = URLEncoder.encode(itqlQuery, "UTF-8");
String url = "http://" + Config.getProperty("FEDORA_SOAP_HOST") + ":" + Config.getProperty("FEDORA_SOAP_ACCESS_PORT") + "/fedora/risearch?type=tuples" + "&lang=iTQL" + "&format=CSV" + "&distinct=on" + "&stream=on" + "&query=" + escapedItqlQuery;
logger.debug("url for risearch query: " + url);
URL urlObject = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObject.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
logger.debug("response code: " + con.getResponseCode());
if (con.getResponseCode() != 200 && con.getResponseCode() != 302) {
throw new FedoraAccessException("Could not access the risearch service at url: " + url);
}
ArrayList arrayList = new ArrayList();
String inputLine;
int counter = 0;
while ((inputLine = br.readLine()) != null) {
logger.debug("reading line:" + inputLine);
if (inputLine.indexOf("<html>") >= 0) {
logger.error("problem quering the relationship");
throw new Exception("Problem querying relationships; probably a bad ITQL query:" + itqlQuery);
}
if (counter >= 1 && inputLine.indexOf("/") >= 0 && inputLine.trim().length() > 0) {
logger.debug("adding line:" + inputLine);
inputLine = inputLine.substring(inputLine.indexOf("/") + 1);
arrayList.add(inputLine);
logger.debug("found relationship to item: " + inputLine);
}
counter++;
}
br.close();
logger.debug("num relationships found: " + arrayList.size());
return arrayList;
}
|
public void transport(File file) throws TransportException {
if (file.exists()) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
transport(file);
}
} else if (file.isFile()) {
try {
FileChannel inChannel = new FileInputStream(file).getChannel();
FileChannel outChannel = new FileOutputStream(destinationDir).getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
log.error("File transfer failed", e);
}
}
}
}
| 0
|
public static String encrypt(String plainText) {
if (TextUtils.isEmpty(plainText)) {
plainText = "";
}
StringBuilder text = new StringBuilder();
for (int i = plainText.length() - 1; i >= 0; i--) {
text.append(plainText.charAt(i));
}
plainText = text.toString();
MessageDigest mDigest;
try {
mDigest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
return plainText;
}
mDigest.update(plainText.getBytes());
byte d[] = mDigest.digest();
StringBuffer hash = new StringBuffer();
for (int i = 0; i < d.length; i++) {
hash.append(Integer.toHexString(0xFF & d[i]));
}
return hash.toString();
}
|
public static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost(postURL);
File file = new File("d:/hai.html");
System.out.println(ukeycookie);
httppost.setHeader("Cookie", ukeycookie + ";" + skeycookie + ";" + usercookie);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("", cbFile);
httppost.setEntity(mpEntity);
System.out.println("Now uploading your file into mediafire...........................");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Getting upload response key value..........");
uploadresponsekey = EntityUtils.toString(resEntity);
getUploadResponseKey();
System.out.println("upload resoponse key " + uploadresponsekey);
}
}
| 0
|
private synchronized void loadDDL() throws IOException {
try {
conn.createStatement().executeQuery("SELECT * FROM non_generic_favs").close();
} catch (SQLException e) {
Statement stmt = null;
if (!e.getMessage().matches(ERR_MISSING_TABLE)) {
e.printStackTrace(System.out);
throw new IOException("Error on initial data store read");
}
String[] qry = { "CREATE TABLE non_generic_favs (id INT NOT NULL PRIMARY KEY)", "CREATE TABLE ignore_chan_favs (id INT NOT NULL PRIMARY KEY, chanlist LONG VARCHAR)", "CREATE TABLE settings (var VARCHAR(32) NOT NULL, val VARCHAR(255) NOT NULL, PRIMARY KEY(var))", "INSERT INTO settings (var, val) VALUES ('schema', '1')" };
try {
conn.setAutoCommit(false);
stmt = conn.createStatement();
for (String q : qry) stmt.executeUpdate(q);
conn.commit();
} catch (SQLException e2) {
try {
conn.rollback();
} catch (SQLException e3) {
e3.printStackTrace(System.out);
}
e2.printStackTrace(new PrintWriter(System.out));
throw new IOException("Error initializing data store");
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e4) {
e4.printStackTrace(System.out);
throw new IOException("Unable to cleanup data store resources");
}
}
try {
conn.setAutoCommit(true);
} catch (SQLException e3) {
e3.printStackTrace(System.out);
throw new IOException("Unable to reset data store auto commit");
}
}
}
return;
}
|
private void compress(String outputFile, ArrayList<String> inputFiles, PrintWriter log, boolean compress) throws Exception {
String absPath = getAppConfig().getPathConfig().getAbsoluteServerPath();
log.println("Concat files into: " + outputFile);
OutputStream out = new FileOutputStream(absPath + outputFile);
byte[] buffer = new byte[4096];
int readBytes;
for (String file : inputFiles) {
log.println(" Read: " + file);
InputStream in = new FileInputStream(absPath + file);
while ((readBytes = in.read(buffer)) != -1) {
out.write(buffer, 0, readBytes);
}
in.close();
}
out.close();
if (compress) {
long normalSize = new File(absPath + outputFile).length();
ProcessBuilder builder = new ProcessBuilder("java", "-jar", "WEB-INF/yuicompressor.jar", outputFile, "-o", outputFile, "--line-break", "4000");
builder.directory(new File(absPath));
Process process = builder.start();
process.waitFor();
long minSize = new File(absPath + outputFile).length();
long diff = normalSize - minSize;
double percentage = Math.floor((double) diff / normalSize * 1000.0) / 10.0;
double diffSize = (Math.floor(diff / 1024.0 * 10.0) / 10.0);
log.println("Result: " + percentage + " % (" + diffSize + " KB)");
}
}
| 0
|
@Override
public InputStream getInputStream() {
try {
String url = webBrowserObject.resourcePath;
File file = Utils.getLocalFile(url);
if (file != null) {
url = webBrowserObject.getLocalFileURL(file);
}
url = url.substring(0, url.lastIndexOf('/')) + "/" + resource;
return new URL(url).openStream();
} catch (Exception e) {
}
return null;
}
|
private boolean getWave(String url, String Word) {
try {
File FF = new File(f.getParent() + "/" + f.getName() + "pron");
FF.mkdir();
URL url2 = new URL(url);
BufferedReader stream = new BufferedReader(new InputStreamReader(url2.openStream()));
File Fdel = new File(f.getParent() + "/" + f.getName() + "pron/" + Word + ".wav");
if (!Fdel.exists()) {
FileOutputStream outstream = new FileOutputStream(f.getParent() + "/" + f.getName() + "pron/" + Word + ".wav");
BufferedWriter bwriter = new BufferedWriter(new OutputStreamWriter(outstream));
char[] binput = new char[1024];
int len = stream.read(binput, 0, 1024);
while (len > 0) {
bwriter.write(binput, 0, len);
len = stream.read(binput, 0, 1024);
}
bwriter.close();
outstream.close();
}
stream.close();
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
return true;
}
| 0
|
public void actualizar() throws SQLException, ClassNotFoundException, Exception {
Connection conn = null;
PreparedStatement ms = null;
registroActualizado = false;
try {
conn = ToolsBD.getConn();
conn.setAutoCommit(false);
Date fechaSystem = new Date();
DateFormat aaaammdd = new SimpleDateFormat("yyyyMMdd");
int fzafsis = Integer.parseInt(aaaammdd.format(fechaSystem));
DateFormat hhmmss = new SimpleDateFormat("HHmmss");
DateFormat sss = new SimpleDateFormat("S");
String ss = sss.format(fechaSystem);
if (ss.length() > 2) {
ss = ss.substring(0, 2);
}
int fzahsis = Integer.parseInt(hhmmss.format(fechaSystem) + ss);
ms = conn.prepareStatement(SENTENCIA_UPDATE);
ms.setString(1, descartadoEntrada);
ms.setString(2, usuarioEntrada);
ms.setString(3, motivosDescarteEntrada);
ms.setInt(4, Integer.parseInt(anoOficio));
ms.setInt(5, Integer.parseInt(oficinaOficio));
ms.setInt(6, Integer.parseInt(numeroOficio));
ms.setInt(7, anoEntrada != null ? Integer.parseInt(anoEntrada) : 0);
ms.setInt(8, oficinaEntrada != null ? Integer.parseInt(oficinaEntrada) : 0);
ms.setInt(9, numeroEntrada != null ? Integer.parseInt(numeroEntrada) : 0);
int afectados = ms.executeUpdate();
if (afectados > 0) {
registroActualizado = true;
} else {
registroActualizado = false;
}
conn.commit();
} catch (Exception ex) {
System.out.println("Error inesperat, no s'ha desat el registre: " + ex.getMessage());
ex.printStackTrace();
registroActualizado = false;
errores.put("", "Error inesperat, no s'ha desat el registre" + ": " + ex.getClass() + "->" + ex.getMessage());
try {
if (conn != null) conn.rollback();
} catch (SQLException sqle) {
throw new RemoteException("S'ha produït un error i no s'han pogut tornar enrere els canvis efectuats", sqle);
}
throw new RemoteException("Error inesperat, no s'ha modifcat el registre", ex);
} finally {
ToolsBD.closeConn(conn, ms, null);
}
}
|
@Override
public File call() throws IOException {
HttpURLConnection conn = null;
ReadableByteChannel fileDownloading = null;
FileChannel fileWriting = null;
try {
conn = (HttpURLConnection) url.openConnection();
if (size == -1) {
size = conn.getContentLength();
}
fileDownloading = Channels.newChannel(conn.getInputStream());
fileWriting = new FileOutputStream(file).getChannel();
long left = size;
long chunkSize = BLOCK_SIZE;
for (long downloaded = 0; downloaded < size; left = size - downloaded) {
if (left < BLOCK_SIZE) {
chunkSize = left;
}
fileWriting.transferFrom(fileDownloading, downloaded, chunkSize);
downloaded += chunkSize;
setProgress(downloaded);
}
} finally {
if (file != null) {
file.deleteOnExit();
}
if (conn != null) {
conn.disconnect();
}
if (fileDownloading != null) {
try {
fileDownloading.close();
} catch (IOException ioe) {
Helper.logger.log(Level.SEVERE, "Не удалось закрыть поток скачивания", ioe);
}
}
if (fileWriting != null) {
try {
fileWriting.close();
} catch (IOException ioe) {
Helper.logger.log(Level.SEVERE, "Не удалось закрыть поток записи в файл", ioe);
}
}
}
return file;
}
| 0
|
public boolean actEstadoEnBD(int idRonda) {
int intResult = 0;
String sql = "UPDATE ronda " + " SET estado = 1" + " WHERE numeroRonda = " + idRonda;
try {
connection = conexionBD.getConnection();
connection.setAutoCommit(false);
ps = connection.prepareStatement(sql);
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);
}
|
public String digest(String message) throws NoSuchAlgorithmException, EncoderException {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(message.getBytes());
byte[] raw = messageDigest.digest();
byte[] chars = new Base64().encode(raw);
return new String(chars);
}
| 0
|
@Test
public void testLoadHttpGzipped() throws Exception {
String url = HTTP_GZIPPED;
LoadingInfo loadingInfo = Utils.openFileObject(fsManager.resolveFile(url));
InputStream contentInputStream = loadingInfo.getContentInputStream();
byte[] actual = IOUtils.toByteArray(contentInputStream);
byte[] expected = IOUtils.toByteArray(new GZIPInputStream(new URL(url).openStream()));
assertEquals(expected.length, actual.length);
}
|
private boolean saveNodeMeta(NodeInfo info, int properties) {
boolean rCode = false;
String query = mServer + "save.php" + ("?id=" + info.getId());
try {
URL url = new URL(query);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
byte[] body = Helpers.EncodeString(Helpers.ASCII, createURLEncodedPropertyString(info, properties));
conn.setAllowUserInteraction(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
setCredentials(conn);
conn.setDoOutput(true);
conn.getOutputStream().write(body);
rCode = saveNode(info, conn);
} catch (Exception ex) {
System.out.println("Exception: " + ex.toString());
}
return rCode;
}
| 0
|
public static void main(String[] args) {
FTPClient client = new FTPClient();
FileOutputStream fos = null;
try {
client.connect("192.168.1.10");
client.login("a", "123456");
String filename = "i.exe";
fos = new FileOutputStream(filename);
client.retrieveFile("/" + filename, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
@Test
public void testSpeedyShareUpload() throws Exception {
request.setUrl("http://www.speedyshare.com/upload.php");
request.setFile("fileup0", file);
HttpResponse response = httpClient.execute(request);
assertTrue(response.is2xxSuccess());
assertTrue(response.getResponseHeaders().size() > 0);
String body = IOUtils.toString(response.getResponseBody());
assertTrue(body.contains("Download link"));
assertTrue(body.contains("Delete password"));
response.close();
}
| 0
|
public static void copyFile(File in, File out) throws Exception {
FileChannel sourceChannel = new FileInputStream(in).getChannel();
FileChannel destinationChannel = new FileOutputStream(out).getChannel();
sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
sourceChannel.close();
destinationChannel.close();
}
|
public static void doVersionCheck(View view) {
view.showWaitCursor();
try {
URL url = new URL(jEdit.getProperty("version-check.url"));
InputStream in = url.openStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
String line;
String develBuild = null;
String stableBuild = null;
while ((line = bin.readLine()) != null) {
if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim();
}
bin.close();
if (develBuild != null && stableBuild != null) {
doVersionCheck(view, stableBuild, develBuild);
}
} catch (IOException e) {
String[] args = { jEdit.getProperty("version-check.url"), e.toString() };
GUIUtilities.error(view, "read-error", args);
}
view.hideWaitCursor();
}
| 0
|
static Matrix readMatrix(String filename, int nrow, int ncol) {
Matrix cij = new Matrix(nrow, ncol);
try {
URL url = filename.getClass().getResource(filename);
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(url.openStream()));
for (int i = 0; i < nrow; i++) for (int j = 0; j < ncol; j++) cij.set(i, j, Double.parseDouble(lnr.readLine()));
} catch (Exception xc) {
xc.printStackTrace();
}
return cij;
}
|
public void patch() throws IOException {
if (mods.isEmpty()) {
return;
}
IOUtils.copy(new FileInputStream(Paths.getMinecraftJarPath()), new FileOutputStream(new File(Paths.getMinecraftBackupPath())));
JarFile mcjar = new JarFile(Paths.getMinecraftJarPath());
}
| 0
|
public boolean referredFilesChanged() throws MalformedURLException, IOException {
for (String file : referredFiles) {
if (FileUtils.isURI(file)) {
URLConnection url = new URL(file).openConnection();
if (url.getLastModified() > created) return true;
} else if (FileUtils.isFile(file)) {
File f = new File(file);
if (f.lastModified() > created) return true;
}
}
return false;
}
|
public FTPClient sample3a(String ftpserver, int ftpport, String proxyserver, int proxyport, String username, String password) throws SocketException, IOException {
FTPHTTPClient ftpClient = new FTPHTTPClient(proxyserver, proxyport);
ftpClient.connect(ftpserver, ftpport);
ftpClient.login(username, password);
return ftpClient;
}
| 0
|
protected void truncate(final File file) {
LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started.");
if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) {
final File backupRoot = new File(this.getBackupDir());
if (!backupRoot.exists() && !backupRoot.mkdirs()) {
throw new AppenderInitializationError("Can't create backup dir for backup storage");
}
SimpleDateFormat df;
try {
df = new SimpleDateFormat(this.getBackupDateFormat());
} catch (final Exception e) {
throw new AppenderInitializationError("Invalid date formate for backup files: " + this.getBackupDateFormat(), e);
}
final String date = df.format(new Date(file.lastModified()));
final File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");
ZipOutputStream zos = null;
FileInputStream fis = null;
try {
zos = new ZipOutputStream(new FileOutputStream(zipFile));
final ZipEntry entry = new ZipEntry(file.getName());
entry.setMethod(ZipEntry.DEFLATED);
entry.setCrc(FileUtils.checksumCRC32(file));
zos.putNextEntry(entry);
fis = FileUtils.openInputStream(file);
final byte[] buffer = new byte[1024];
int readed;
while ((readed = fis.read(buffer)) != -1) {
zos.write(buffer, 0, readed);
}
} catch (final Exception e) {
throw new AppenderInitializationError("Can't create zip file", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (final IOException e) {
LogLog.warn("Can't close zip file", e);
}
}
if (fis != null) {
try {
fis.close();
} catch (final IOException e) {
LogLog.warn("Can't close zipped file", e);
}
}
}
if (!file.delete()) {
throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath());
}
}
}
|
public void deleteAuthors() throws Exception {
if (proposalIds.equals("") || usrIds.equals("")) throw new Exception("No proposal or author selected.");
String[] pids = proposalIds.split(",");
String[] uids = usrIds.split(",");
int pnum = pids.length;
int unum = uids.length;
if (pnum == 0 || unum == 0) throw new Exception("No proposal or author selected.");
int i, j;
PreparedStatement prepStmt = null;
try {
con = database.getConnection();
con.setAutoCommit(false);
String pStr = "delete from event where ACTION_ID='member added' AND PROPOSAL_ID=? AND SUBJECTUSR_ID=?";
prepStmt = con.prepareStatement(pStr);
for (i = 0; i < pnum; i++) {
for (j = 0; j < unum; j++) {
if (!uids[j].equals(userId)) {
prepStmt.setString(1, pids[i]);
prepStmt.setString(2, uids[j]);
prepStmt.executeUpdate();
}
}
}
con.commit();
} catch (Exception e) {
if (!con.isClosed()) {
con.rollback();
prepStmt.close();
con.close();
}
throw e;
}
}
| 0
|
public void writeConfiguration(Writer out) throws IOException {
if (myResource == null) {
out.append("# Unable to print configuration resource\n");
} else {
URL url = myResource.getUrl();
InputStream in = url.openStream();
if (in != null) {
try {
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(in);
}
} else {
out.append("# Unable to print configuration resource\n");
}
}
}
|
private static String scramble(String text) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(text.getBytes("UTF-8"));
StringBuffer sb = new StringBuffer();
for (byte b : md.digest()) sb.append(Integer.toString(b & 0xFF, 16));
return sb.toString();
} catch (UnsupportedEncodingException e) {
return null;
} catch (NoSuchAlgorithmException e) {
return null;
}
}
| 0
|
public void testJPEGRaster() throws MalformedURLException, IOException {
System.out.println("JPEGCodec RasterImage:");
long start = Calendar.getInstance().getTimeInMillis();
for (int i = 0; i < images.length; i++) {
String url = Constants.getDefaultURIMediaConnectorBasePath() + "albums/hund/" + images[i];
InputStream istream = (new URL(url)).openStream();
JPEGImageDecoder dec = JPEGCodec.createJPEGDecoder(istream);
Raster raster = dec.decodeAsRaster();
int width = raster.getWidth();
int height = raster.getHeight();
istream.close();
System.out.println("w: " + width + " - h: " + height);
}
long stop = Calendar.getInstance().getTimeInMillis();
System.out.println("zeit: " + (stop - start));
}
|
@Test
public void test30_passwordAging() throws Exception {
Db db = DbConnection.defaultCieDbRW();
try {
db.begin();
Config.setProperty(db, "com.entelience.esis.security.passwordAge", "5", 1);
PreparedStatement pst = db.prepareStatement("UPDATE e_people SET last_passwd_change = '2006-07-01' WHERE user_name = ?");
pst.setString(1, "esis");
db.executeUpdate(pst);
db.commit();
p_logout();
t30login1();
assertTrue(isPasswordExpired());
PeopleInfoLine me = getCurrentPeople();
assertNotNull(me.getPasswordExpirationDate());
assertTrue(me.getPasswordExpirationDate().before(DateHelper.now()));
t30chgpasswd();
assertFalse(isPasswordExpired());
me = getCurrentPeople();
assertNotNull(me.getPasswordExpirationDate());
assertTrue(me.getPasswordExpirationDate().after(DateHelper.now()));
p_logout();
t30login2();
assertFalse(isPasswordExpired());
t30chgpasswd2();
db.begin();
Config.setProperty(db, "com.entelience.esis.security.passwordAge", "0", 1);
db.commit();
} catch (Exception e) {
e.printStackTrace();
db.rollback();
} finally {
db.safeClose();
}
}
| 0
|
public boolean crear() {
int result = 0;
String sql = "insert into jugador" + "(apellidoPaterno, apellidoMaterno, nombres, fechaNacimiento, pais, rating, sexo)" + "values (?, ?, ?, ?, ?, ?, ?)";
try {
connection = conexionBD.getConnection();
connection.setAutoCommit(false);
ps = connection.prepareStatement(sql);
populatePreparedStatement(elJugador);
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);
}
|
private static final String hash(String input, String algorithm) {
try {
MessageDigest dig = MessageDigest.getInstance(algorithm);
dig.update(input.getBytes());
StringBuffer result = new StringBuffer();
byte[] digest = dig.digest();
String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
for (int i = 0; i < digest.length; i++) {
int u = digest[i];
u &= 0x000000FF;
int highCount = u / 16;
int lowCount = u - (highCount * 16);
result.append(hex[highCount]);
result.append(hex[lowCount]);
}
return result.toString();
} catch (NoSuchAlgorithmException e) {
return null;
}
}
| 0
|
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);
}
}
|
public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException {
HttpURLConnection con = null;
InputStream is = null;
try {
URL u = new URL(url);
if (url.startsWith("file://")) {
is = new BufferedInputStream(u.openStream());
} else {
Proxy proxy;
if (proxyHost != null) {
proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
} else {
proxy = Proxy.NO_PROXY;
}
con = (HttpURLConnection) u.openConnection(proxy);
con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6");
con.addRequestProperty("Accept-Charset", "UTF-8");
con.addRequestProperty("Accept-Language", "en-US,en");
con.addRequestProperty("Accept", "text/html,image/*");
con.setDoInput(true);
con.setDoOutput(false);
con.connect();
is = new BufferedInputStream(con.getInputStream());
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(is, baos);
return baos.toByteArray();
} finally {
IOUtils.closeQuietly(is);
if (con != null) {
con.disconnect();
}
}
}
| 0
|
public static void copy(String fileFrom, String fileTo) throws IOException {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputStream = new FileInputStream(fileFrom);
outputStream = new FileOutputStream(fileTo);
inputChannel = inputStream.getChannel();
outputChannel = outputStream.getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
} finally {
try {
inputChannel.close();
} finally {
try {
outputChannel.close();
} finally {
try {
inputStream.close();
} finally {
outputStream.close();
}
}
}
}
}
|
public String encrypt(String password) throws Exception {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(password.getBytes());
BigInteger hash = new BigInteger(1, md5.digest());
String hashword = hash.toString(16);
return hashword;
}
| 0
|
@SuppressWarnings("unchecked")
private ReaderFeed processEntrys(String urlStr, String currentFlag) throws UnsupportedEncodingException, IOException, JDOMException {
String key = "processEntrys@" + urlStr + "_" + currentFlag;
if (cache.containsKey(key)) {
return (ReaderFeed) cache.get(key);
}
List<Post> postList = new ArrayList<Post>();
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Cookie", "SID=" + sid);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
SAXBuilder builder = new SAXBuilder(false);
Document doc = builder.build(reader);
Element root = doc.getRootElement();
Namespace grNamespace = root.getNamespace("gr");
Namespace namespace = root.getNamespace();
String newflag = root.getChildText("continuation", grNamespace);
String title = root.getChildText("title", namespace);
String subTitle = root.getChildText("subtitle", namespace);
List<Element> entryList = root.getChildren("entry", namespace);
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
for (Element e : entryList) {
Post post = new Post();
post.setTitle(e.getChildText("title", namespace));
try {
post.setDate(sdf.parse(e.getChildText("published", namespace)));
} catch (ParseException e1) {
}
post.setUrl(e.getChild("link", namespace).getAttributeValue("href"));
post.setSauthor(e.getChild("author", namespace).getChildText("name", namespace));
String content = e.getChildText("content", namespace);
if (StringUtils.isEmpty(content)) {
content = e.getChildText("description", namespace);
}
if (StringUtils.isEmpty(content)) {
content = e.getChildText("summary", namespace);
}
post.setContent(content);
postList.add(post);
}
ReaderFeed readerFeed = new ReaderFeed();
readerFeed.setTitle(title);
readerFeed.setSubTitle(subTitle);
readerFeed.setFlag(newflag);
readerFeed.setPostList(postList);
cache.put(key, readerFeed);
return readerFeed;
}
|
public void test() throws Exception {
StorageStringWriter s = new StorageStringWriter(2048, "UTF-8");
s.addText("Test");
try {
s.getOutputStream();
fail("Should throw IOException as method not supported.");
} catch (IOException e) {
}
s.getWriter().write("ing is important");
s.close(ResponseStateOk.getInstance());
assertEquals("Testing is important", s.getText());
InputStream input = s.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "UTF-8");
assertEquals("Testing is important", writer.toString());
try {
s.getWriter();
fail("Should throw IOException as storage is closed.");
} catch (IOException e) {
}
}
| 0
|
protected String getRequestContent(String urlText) throws Exception {
URL url = new URL(urlText);
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream()));
String line = reader.readLine();
reader.close();
urlcon.disconnect();
return line;
}
|
public void copyLogic() {
if (getState() == States.Idle) {
setState(States.Synchronizing);
try {
FileChannel sourceChannel = new FileInputStream(new File(_properties.getProperty("binPath") + name + ".class")).getChannel();
FileChannel destinationChannel = new FileOutputStream(new File(_properties.getProperty("agentFileLocation") + name + ".class")).getChannel();
sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
sourceChannel.close();
destinationChannel.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
setState(States.Idle);
}
}
| 0
|
public Configuration(URL url) {
InputStream in = null;
try {
load(in = url.openStream());
} catch (Exception e) {
throw new RuntimeException("Could not load configuration from " + url, e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ignore) {
}
}
}
}
|
public static final synchronized String hash(String data) {
if (digest == null) {
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException nsae) {
System.err.println("Failed to load the MD5 MessageDigest. " + "unable to function normally.");
nsae.printStackTrace();
}
}
digest.update(data.getBytes());
return encodeHex(digest.digest());
}
| 0
|
public static void doVersionCheck(View view) {
view.showWaitCursor();
try {
URL url = new URL(jEdit.getProperty("version-check.url"));
InputStream in = url.openStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
String line;
String develBuild = null;
String stableBuild = null;
while ((line = bin.readLine()) != null) {
if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim();
}
bin.close();
if (develBuild != null && stableBuild != null) {
doVersionCheck(view, stableBuild, develBuild);
}
} catch (IOException e) {
String[] args = { jEdit.getProperty("version-check.url"), e.toString() };
GUIUtilities.error(view, "read-error", args);
}
view.hideWaitCursor();
}
|
private String copyImageFile(String urlString, String filePath) {
FileOutputStream destination = null;
File destination_file = null;
String inLine;
String dest_name = "";
byte[] buffer;
int bytes_read;
int last_offset = 0;
int offset = 0;
InputStream imageFile = null;
try {
URL url = new URL(urlString);
imageFile = url.openStream();
dest_name = url.getFile();
offset = 0;
last_offset = 0;
offset = dest_name.indexOf('/', offset + 1);
while (offset > -1) {
last_offset = offset + 1;
offset = dest_name.indexOf('/', offset + 1);
}
dest_name = filePath + File.separator + dest_name.substring(last_offset);
destination_file = new File(dest_name);
if (destination_file.exists()) {
if (destination_file.isFile()) {
if (!destination_file.canWrite()) {
System.out.println("FileCopy: destination " + "file is unwriteable: " + dest_name);
}
System.out.println("File " + dest_name + " already exists. File will be overwritten.");
} else {
System.out.println("FileCopy: destination " + "is not a file: " + dest_name);
}
} else {
File parentdir = parent(destination_file);
if (!parentdir.exists()) {
System.out.println("FileCopy: destination " + "directory doesn't exist: " + dest_name);
}
if (!parentdir.canWrite()) {
System.out.println("FileCopy: destination " + "directory is unwriteable: " + dest_name);
}
}
destination = new FileOutputStream(dest_name);
buffer = new byte[1024];
while (true) {
bytes_read = imageFile.read(buffer);
if (bytes_read == -1) break;
destination.write(buffer, 0, bytes_read);
}
} catch (MalformedURLException ex) {
System.out.println("Bad URL " + urlString);
} catch (IOException ex) {
System.out.println(" IO error: " + ex.getMessage());
} finally {
if (imageFile != null) {
try {
imageFile.close();
} catch (IOException e) {
}
}
if (destination != null) {
try {
destination.close();
} catch (IOException e) {
}
}
}
return (dest_name);
}
| 0
|
public static String encrypt(String text) {
char[] toEncrypt = text.toCharArray();
StringBuffer hexString = new StringBuffer();
try {
MessageDigest dig = MessageDigest.getInstance("MD5");
dig.reset();
String pw = "";
for (int i = 0; i < toEncrypt.length; i++) {
pw += toEncrypt[i];
}
dig.update(pw.getBytes());
byte[] digest = dig.digest();
int digestLength = digest.length;
for (int i = 0; i < digestLength; i++) {
hexString.append(hexDigit(digest[i]));
}
} catch (java.security.NoSuchAlgorithmException ae) {
ae.printStackTrace();
}
return hexString.toString();
}
|
public Resource createNew(String name, InputStream in, Long length, String contentType) throws IOException {
File dest = new File(this.getRealFile(), name);
LOGGER.debug("PUT?? - real file: " + this.getRealFile() + ",name: " + name);
if (isOwner) {
if (!".request".equals(name) && !".tokens".equals(name)) {
FileOutputStream out = null;
try {
out = new FileOutputStream(dest);
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(out);
}
} else {
if (ServerConfiguration.isDynamicSEL()) {
} else {
}
FileOutputStream out = null;
try {
out = new FileOutputStream(dest);
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(out);
}
}
return factory.resolveFile(this.host, dest);
} else {
LOGGER.error("User isn't owner of this folder");
return null;
}
}
| 0
|
@Override
public InputStream getResourceByClassName(String className) {
URL url = resourceFetcher.getResource("/fisce_scripts/" + className + ".class");
if (url == null) {
return null;
} else {
try {
return url.openStream();
} catch (IOException e) {
return null;
}
}
}
|
protected BufferedImage handleFCLAException() {
if (params.uri.startsWith("http://image11.fcla.edu/cgi")) try {
params.uri = params.uri.substring(params.uri.indexOf("q1=") + 3);
params.uri = params.uri.substring(0, params.uri.indexOf("&"));
params.uri = "http://image11.fcla.edu/m/map/thumb/" + params.uri.substring(params.uri.length() - 3, params.uri.length() - 2) + "/" + params.uri.substring(params.uri.length() - 2, params.uri.length() - 1) + "/" + params.uri.substring(params.uri.length() - 1, params.uri.length()) + "/" + params.uri + ".jpg";
URL url = new URL(params.uri);
URLConnection connection = url.openConnection();
return processNewUri(connection);
} catch (Exception e) {
}
return null;
}
| 0
|
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();
}
}
|
private boolean getWave(String url, String Word) {
try {
File FF = new File(f.getParent() + "/" + f.getName() + "pron");
FF.mkdir();
URL url2 = new URL(url);
BufferedReader stream = new BufferedReader(new InputStreamReader(url2.openStream()));
File Fdel = new File(f.getParent() + "/" + f.getName() + "pron/" + Word + ".wav");
if (!Fdel.exists()) {
FileOutputStream outstream = new FileOutputStream(f.getParent() + "/" + f.getName() + "pron/" + Word + ".wav");
BufferedWriter bwriter = new BufferedWriter(new OutputStreamWriter(outstream));
char[] binput = new char[1024];
int len = stream.read(binput, 0, 1024);
while (len > 0) {
bwriter.write(binput, 0, len);
len = stream.read(binput, 0, 1024);
}
bwriter.close();
outstream.close();
}
stream.close();
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
return true;
}
| 0
|
public static String hashPasswordForOldMD5(String password) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes("UTF-8"));
byte messageDigest[] = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String hex = Integer.toHexString(0xFF & messageDigest[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException nsae) {
throw new IllegalStateException(nsae.getMessage());
} catch (UnsupportedEncodingException uee) {
throw new IllegalStateException(uee.getMessage());
}
}
|
public void testCodingEmptyFile() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
WritableByteChannel channel = newChannel(baos);
HttpParams params = new BasicHttpParams();
SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16);
encoder.write(wrap("stuff;"));
File tmpFile = File.createTempFile("testFile", "txt");
FileOutputStream fout = new FileOutputStream(tmpFile);
OutputStreamWriter wrtout = new OutputStreamWriter(fout);
wrtout.flush();
wrtout.close();
FileChannel fchannel = new FileInputStream(tmpFile).getChannel();
encoder.transfer(fchannel, 0, 20);
encoder.write(wrap("more stuff"));
String s = baos.toString("US-ASCII");
assertTrue(encoder.isCompleted());
assertEquals("stuff;more stuff", s);
tmpFile.delete();
}
| 0
|
public static GameRecord[] get(String url, float lat, float lon, int count) {
try {
HttpURLConnection req = (HttpURLConnection) new URL(url).openConnection();
req.setRequestMethod("GET");
req.setRequestProperty(GameRecord.GAME_LATITUDE_HEADER, df.format(lat));
req.setRequestProperty(GameRecord.GAME_LONGITUDE_HEADER, df.format(lon));
req.setRequestProperty("X-GameQueryCount", String.valueOf(count));
req.connect();
if (req.getResponseCode() == HttpURLConnection.HTTP_OK) {
List<GameRecord> gl = new ArrayList<GameRecord>();
BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
if (!line.startsWith("#")) {
gl.add(GameRecord.decode(line));
}
}
return gl.toArray(new GameRecord[gl.size()]);
} else {
System.out.println(req.getResponseMessage());
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
|
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;
}
| 0
|
public boolean connect() {
boolean isConnected = false;
try {
try {
this.ftpClient.connect(this.server, this.port);
} catch (SocketException e) {
status = ErrorResult.CONNECTNOTPOSSIBLE.code;
return false;
} catch (IOException e) {
status = ErrorResult.CONNECTNOTPOSSIBLE.code;
return false;
}
int reply = this.ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
this.disconnect();
status = ErrorResult.CONNECTNOTCORRECT.code;
return false;
}
try {
if (this.account == null) {
if (!this.ftpClient.login(this.username, this.passwd)) {
status = ErrorResult.LOGINNOTCORRECT.code;
this.ftpClient.logout();
return false;
}
} else if (!this.ftpClient.login(this.username, this.passwd, this.account)) {
status = ErrorResult.LOGINACCTNOTCORRECT.code;
this.ftpClient.logout();
return false;
}
} catch (IOException e) {
status = ErrorResult.ERRORWHILECONNECT.code;
try {
this.ftpClient.logout();
} catch (IOException e1) {
}
return false;
}
isConnected = true;
return true;
} finally {
if ((!isConnected) && this.ftpClient.isConnected()) {
this.disconnect();
}
}
}
|
private void redirect(TargetApp app, HttpServletRequest request, HttpServletResponse response) throws IOException {
URL url = new URL(app.getUrl() + request.getRequestURI());
s_log.debug("Redirecting to " + url);
URLConnection urlConnection = url.openConnection();
Map<String, List<String>> fields = urlConnection.getHeaderFields();
for (String key : fields.keySet()) {
StringBuffer values = new StringBuffer();
boolean comma = false;
for (String value : fields.get(key)) {
if (comma) {
values.append(", ");
}
values.append(value);
comma = true;
}
if (key != null) {
response.setHeader(key, values.toString());
} else {
response.setStatus(Integer.parseInt(values.toString().split(" ")[1]));
}
}
InputStream in = urlConnection.getInputStream();
try {
ServletOutputStream out = response.getOutputStream();
byte[] buff = new byte[1024];
int len;
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
} finally {
in.close();
}
}
| 0
|
protected static void copyDeleting(File source, File dest) throws IOException {
byte[] buf = new byte[8 * 1024];
FileInputStream in = new FileInputStream(source);
try {
FileOutputStream out = new FileOutputStream(dest);
try {
int count;
while ((count = in.read(buf)) >= 0) out.write(buf, 0, count);
} finally {
out.close();
}
} finally {
in.close();
}
}
|
public static byte[] encrypt(String x) throws Exception {
java.security.MessageDigest d = null;
d = java.security.MessageDigest.getInstance("SHA-1");
d.reset();
d.update(x.getBytes());
return d.digest();
}
| 0
|
ClassFile getClassFile(String name) throws IOException, ConstantPoolException {
URL url = getClass().getResource(name);
InputStream in = url.openStream();
try {
return ClassFile.read(in);
} finally {
in.close();
}
}
|
public void deleteAuthors() throws Exception {
if (proposalIds.equals("") || usrIds.equals("")) throw new Exception("No proposal or author selected.");
String[] pids = proposalIds.split(",");
String[] uids = usrIds.split(",");
int pnum = pids.length;
int unum = uids.length;
if (pnum == 0 || unum == 0) throw new Exception("No proposal or author selected.");
int i, j;
PreparedStatement prepStmt = null;
try {
con = database.getConnection();
con.setAutoCommit(false);
String pStr = "delete from event where ACTION_ID='member added' AND PROPOSAL_ID=? AND SUBJECTUSR_ID=?";
prepStmt = con.prepareStatement(pStr);
for (i = 0; i < pnum; i++) {
for (j = 0; j < unum; j++) {
if (!uids[j].equals(userId)) {
prepStmt.setString(1, pids[i]);
prepStmt.setString(2, uids[j]);
prepStmt.executeUpdate();
}
}
}
con.commit();
} catch (Exception e) {
if (!con.isClosed()) {
con.rollback();
prepStmt.close();
con.close();
}
throw e;
}
}
| 0
|
private InputStream openRemoteStream(String remoteURL, String pathSuffix) {
URL url;
InputStream in = null;
try {
url = new URL(remoteURL + pathSuffix);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
in = connection.getInputStream();
} catch (Exception e) {
}
return in;
}
|
public synchronized String encryptPassword(String passwordString) throws Exception {
MessageDigest digest = null;
digest = MessageDigest.getInstance("SHA");
digest.update(passwordString.getBytes("UTF-8"));
byte raw[] = digest.digest();
String hash = (new BASE64Encoder()).encode(raw);
return hash;
}
| 0
|
@Override
public void respondGet(HttpServletResponse resp) throws IOException {
setHeaders(resp);
final OutputStream os;
if (willDeflate()) {
resp.setHeader("Content-Encoding", "gzip");
os = new GZIPOutputStream(resp.getOutputStream(), bufferSize);
} else os = resp.getOutputStream();
transferStreams(url.openStream(), os);
}
|
@Override
public Cal3dModel loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException {
boolean baseURLWasNull = setBaseURLFromModelURL(url);
Cal3dModel model = new Cal3dModel(getFlags());
loadCal3dModel(getBaseURL(), url.toExternalForm(), new InputStreamReader(url.openStream()), model);
if (baseURLWasNull) {
popBaseURL();
}
return (model);
}
| 0
|
@Override
public void makeRead(final String user, final long databaseID, final long time) throws SQLException {
final String query = "insert into fs.read_post (post, user, read_date) values (?, ?, ?)";
ensureConnection();
final PreparedStatement statement = m_connection.prepareStatement(query);
try {
statement.setLong(1, databaseID);
statement.setString(2, user);
statement.setTimestamp(3, new Timestamp(time));
final int count = statement.executeUpdate();
if (0 == count) {
throw new SQLException("Nothing updated.");
}
m_connection.commit();
} catch (final SQLException e) {
m_connection.rollback();
throw e;
} finally {
statement.close();
}
}
|
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());
}
| 0
|
private String getEncoding() throws IOException {
BufferedReader reader = null;
String encoding = null;
try {
URLConnection connection = url.openConnection();
Map<String, List<String>> header = connection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : header.entrySet()) {
if (entry.getKey().toLowerCase().equals("content-type")) {
String item = entry.getValue().toString().toLowerCase();
if (item.contains("charset")) {
encoding = extractEncoding(item);
if (encoding != null && !encoding.isEmpty()) return encoding;
}
}
}
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
line = line.toLowerCase();
if (line.contains("charset") || line.contains("encoding")) {
encoding = extractEncoding(line);
if (encoding != null && !encoding.isEmpty()) return encoding;
}
}
return STANDARDENCODING;
} finally {
if (reader != null) reader.close();
}
}
|
public static String md5(String message, boolean base64) {
MessageDigest md5 = null;
String digest = message;
try {
md5 = MessageDigest.getInstance("MD5");
md5.update(message.getBytes());
byte[] digestData = md5.digest();
if (base64) {
Base64Encoder enc = new Base64Encoder();
enc.translate(digestData);
digest = new String(enc.getCharArray());
} else {
digest = byteArrayToHex(digestData);
}
} catch (NoSuchAlgorithmException e) {
LOG.warn("MD5 not supported. Using plain string as password!");
} catch (Exception e) {
LOG.warn("Digest creation failed. Using plain string as password!");
}
return digest;
}
| 0
|
public static void copyOverWarFile() {
System.out.println("Copy Over War File:");
File dir = new File(theAppsDataDir);
FileFilter ff = new WildcardFileFilter("*.war");
if (dir.listFiles(ff).length == 0) {
dir = new File(System.getProperty("user.dir") + "/war");
if (dir.exists()) {
File[] files = dir.listFiles(ff);
for (File f : files) {
try {
File newFile = new File("" + theAppsDataDir + "/" + f.getName());
System.out.println("Creating new file \"" + f.getAbsolutePath() + "\"");
newFile.createNewFile();
InputStream fi = new FileInputStream(f);
OutputStream fo = new FileOutputStream(newFile);
IOUtils.copy(fi, fo);
moveUnzipAndExtract(newFile);
} catch (Exception ex) {
Logger.getLogger(AppDataDir.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
} else {
System.out.println("Found a war in the apps data dir, ignoring a fresh copy");
}
new JFileChooser().setCurrentDirectory(new File(theAppsDataDir));
System.setProperty("user.dir", theAppsDataDir);
System.out.println("User.dir : " + System.getProperty("user.dir"));
}
|
public static void doVersionCheck(View view) {
view.showWaitCursor();
try {
URL url = new URL(jEdit.getProperty("version-check.url"));
InputStream in = url.openStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
String line;
String develBuild = null;
String stableBuild = null;
while ((line = bin.readLine()) != null) {
if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim();
}
bin.close();
if (develBuild != null && stableBuild != null) {
doVersionCheck(view, stableBuild, develBuild);
}
} catch (IOException e) {
String[] args = { jEdit.getProperty("version-check.url"), e.toString() };
GUIUtilities.error(view, "read-error", args);
}
view.hideWaitCursor();
}
| 0
|
String runScript(String scriptName) {
String data = "";
try {
URL url = new URL(getCodeBase().toString() + scriptName);
InputStream in = url.openStream();
BufferedInputStream buffIn = new BufferedInputStream(in);
do {
int temp = buffIn.read();
if (temp == -1) break;
data = data + (char) temp;
} while (true);
} catch (Exception e) {
data = "error!";
}
return data;
}
|
private boolean getWave(String url, String Word) {
try {
File FF = new File(f.getParent() + "/" + f.getName() + "pron");
FF.mkdir();
URL url2 = new URL(url);
BufferedReader stream = new BufferedReader(new InputStreamReader(url2.openStream()));
File Fdel = new File(f.getParent() + "/" + f.getName() + "pron/" + Word + ".wav");
if (!Fdel.exists()) {
FileOutputStream outstream = new FileOutputStream(f.getParent() + "/" + f.getName() + "pron/" + Word + ".wav");
BufferedWriter bwriter = new BufferedWriter(new OutputStreamWriter(outstream));
char[] binput = new char[1024];
int len = stream.read(binput, 0, 1024);
while (len > 0) {
bwriter.write(binput, 0, len);
len = stream.read(binput, 0, 1024);
}
bwriter.close();
outstream.close();
}
stream.close();
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
return true;
}
| 0
|
@Before
public void setUp() throws Exception {
connectionDigestHandler = new ConnectionDigestHandlerDefaultImpl();
URL url = null;
try {
url = new URL("http://dev2dev.bea.com.cn/bbs/servlet/D2DServlet/download/64104-35000-204984-2890/webwork2guide.pdf");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
uc = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
}
|
@Test
public void test02_ok() throws Exception {
DefaultHttpClient client = new DefaultHttpClient();
try {
HttpPost post = new HttpPost(chartURL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("ws", "getDomainEvolution"));
nameValuePairs.add(new BasicNameValuePair("chartTitle", "test"));
nameValuePairs.add(new BasicNameValuePair("type", "chart"));
nameValuePairs.add(new BasicNameValuePair("firstDate", "20111124"));
nameValuePairs.add(new BasicNameValuePair("lastDate", "20111125"));
nameValuePairs.add(new BasicNameValuePair("wsParams", "type,counting,protocol,unit,proxy,domain,timeScale,period"));
nameValuePairs.add(new BasicNameValuePair("wsParamsValues", "chart,volume,all,hits,all,google.com,day,360"));
nameValuePairs.add(new BasicNameValuePair("serieTitle", "serie"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
assertNotNull(entity);
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
System.out.println(reader.readLine());
instream.close();
assertEquals("error :" + response.getStatusLine(), 200, response.getStatusLine().getStatusCode());
} finally {
client.getConnectionManager().shutdown();
}
}
| 0
|
private String unJar(String jarPath, String jarEntry) {
String path;
if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/"));
String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/"));
try {
new File(path + "/" + relPath).mkdirs();
JarFile jar = new JarFile(jarPath);
ZipEntry ze = jar.getEntry(jarEntry);
File bin = new File(path + "/" + jarEntry);
IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin));
} catch (Exception e) {
e.printStackTrace();
}
return path + "/" + jarEntry;
}
|
public void run() {
URL url;
try {
url = new URL("http://localhost:8080/glowaxes/dailytrend.jsp");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
while ((str = in.readLine()) != null) {
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}
| 0
|
public static void copyFile(File srcFile, File destFile) throws IOException {
if (!(srcFile.exists() && srcFile.isFile())) throw new IllegalArgumentException("Source file doesn't exist: " + srcFile.getAbsolutePath());
if (destFile.exists() && destFile.isDirectory()) throw new IllegalArgumentException("Destination file is directory: " + destFile.getAbsolutePath());
FileInputStream in = new FileInputStream(srcFile);
FileOutputStream out = new FileOutputStream(destFile);
byte[] buffer = new byte[4096];
int no = 0;
try {
while ((no = in.read(buffer)) != -1) out.write(buffer, 0, no);
} finally {
in.close();
out.close();
}
}
|
public static boolean loadContentFromURL(String fromURL, String toFile) {
try {
URL url = new URL("http://bible-desktop.com/xml" + fromURL);
File file = new File(toFile);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
} catch (IOException e) {
Log.e(TAG, e);
return false;
}
return true;
}
| 0
|
public String readRemoteFile() throws IOException {
String response = "";
boolean eof = false;
URL url = new URL(StaticData.remoteFile);
InputStream is = url.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String s;
s = br.readLine();
response = s;
while (!eof) {
try {
s = br.readLine();
if (s == null) {
eof = true;
br.close();
} else response += s;
} catch (EOFException eo) {
eof = true;
} catch (IOException e) {
System.out.println("IO Error : " + e.getMessage());
}
}
return response;
}
|
public static String encrypt(String text) throws NoSuchAlgorithmException {
MessageDigest md;
md = MessageDigest.getInstance("MD5");
byte[] md5hash = new byte[32];
try {
md.update(text.getBytes("iso-8859-1"), 0, text.length());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
md5hash = md.digest();
return convertToHex(md5hash);
}
| 0
|
protected int deleteBitstreamInfo(int id, Connection conn) {
PreparedStatement stmt = null;
int numDeleted = 0;
try {
stmt = conn.prepareStatement(DELETE_BITSTREAM_INFO);
stmt.setInt(1, id);
numDeleted = stmt.executeUpdate();
if (numDeleted > 1) {
conn.rollback();
throw new IllegalStateException("Too many rows deleted! Number of rows deleted: " + numDeleted + " only one row should be deleted for bitstream id " + id);
}
} catch (SQLException e) {
LOG.error("Problem deleting bitstream. " + e.getMessage(), e);
throw new RuntimeException("Problem deleting bitstream. " + e.getMessage(), e);
} finally {
cleanup(stmt);
}
return numDeleted;
}
|
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;
}
| 0
|
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;
}
|
@Override
public Content getContent(Object principal, ContentPath path, Version version, Map<String, Object> properties) throws ContentException {
String uniqueName = path.getBaseName();
URL url = buildURL(uniqueName);
URLContent content = new URLContent(url, this.getName(), uniqueName);
content.setUniqueName(uniqueName);
content.setReadable(true);
content.setWritable(writable);
content.setExists(true);
try {
URLConnection connection = url.openConnection();
String mimeType = connection.getContentType();
content.setMimeType(mimeType);
content.setWritable(true);
} catch (IOException ex) {
throw new ContentException("unable to obtain mime type of " + url, ex);
}
return content;
}
| 0
|
public static void fileDownload(String fAddress, String destinationDir) {
int slashIndex = fAddress.lastIndexOf('/');
int periodIndex = fAddress.lastIndexOf('.');
String fileName = fAddress.substring(slashIndex + 1);
URL url;
try {
url = new URL(fAddress);
URLConnection uc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
File file = new File(destinationDir + "/download.pdf");
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
int inputLine;
while ((inputLine = in.read()) != -1) out.write(inputLine);
in.close();
} catch (Exception ex) {
Logger.getLogger(UrlDownload.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
public void testHttpsConnection_Not_Found_Response() throws Throwable {
setUpStoreProperties();
try {
SSLContext ctx = getContext();
ServerSocket ss = ctx.getServerSocketFactory().createServerSocket(0);
TestHostnameVerifier hnv = new TestHostnameVerifier();
HttpsURLConnection.setDefaultHostnameVerifier(hnv);
URL url = new URL("https://localhost:" + ss.getLocalPort());
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
try {
doInteraction(connection, ss, NOT_FOUND_CODE);
fail("Expected exception was not thrown.");
} catch (FileNotFoundException e) {
if (DO_LOG) {
System.out.println("Expected exception was thrown: " + e.getMessage());
}
}
connection.connect();
} finally {
tearDownStoreProperties();
}
}
| 0
|
public static int[] sortAscending(float input[]) {
int[] order = new int[input.length];
for (int i = 0; i < order.length; i++) order[i] = i;
for (int i = input.length; --i >= 0; ) {
for (int j = 0; j < i; j++) {
if (input[j] > input[j + 1]) {
float mem = input[j];
input[j] = input[j + 1];
input[j + 1] = mem;
int id = order[j];
order[j] = order[j + 1];
order[j + 1] = id;
}
}
}
return order;
}
|
public void write() throws IOException {
JarOutputStream jarOut = new JarOutputStream(outputStream, manifest);
if (includeJars != null) {
HashSet allEntries = new HashSet(includeJars);
if (!ignoreDependencies) expandSet(allEntries);
for (Iterator iterator = allEntries.iterator(); iterator.hasNext(); ) {
JarFile jar = getJarFile(iterator.next());
Enumeration jarEntries = jar.entries();
while (jarEntries.hasMoreElements()) {
ZipEntry o1 = (ZipEntry) jarEntries.nextElement();
if (o1.getName().equalsIgnoreCase("META-INF/MANIFEST.MF") || o1.getSize() <= 0) continue;
jarOut.putNextEntry(o1);
InputStream entryStream = jar.getInputStream(o1);
IOUtils.copy(entryStream, jarOut);
jarOut.closeEntry();
}
}
}
jarOut.finish();
jarOut.close();
}
| 0
|
public static String fetchUrl(String urlString) {
try {
URL url = new URL(urlString);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line = null;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
reader.close();
return builder.toString();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return "";
}
|
private String digest(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md5hash = new byte[64];
md.update(input.getBytes("iso-8859-1"), 0, input.length());
md5hash = md.digest();
return this.convertToHex(md5hash);
}
| 0
|
private void doFinishLoadAttachment(long attachmentId) {
if (attachmentId != mLoadAttachmentId) {
return;
}
Attachment attachment = Attachment.restoreAttachmentWithId(MessageView.this, attachmentId);
Uri attachmentUri = AttachmentProvider.getAttachmentUri(mAccountId, attachment.mId);
Uri contentUri = AttachmentProvider.resolveAttachmentIdToContentUri(getContentResolver(), attachmentUri);
if (mLoadAttachmentSave) {
try {
File file = createUniqueFile(Environment.getExternalStorageDirectory(), attachment.mFileName);
InputStream in = getContentResolver().openInputStream(contentUri);
OutputStream out = new FileOutputStream(file);
IOUtils.copy(in, out);
out.flush();
out.close();
in.close();
Toast.makeText(MessageView.this, String.format(getString(R.string.message_view_status_attachment_saved), file.getName()), Toast.LENGTH_LONG).show();
new MediaScannerNotifier(this, file, mHandler);
} catch (IOException ioe) {
Toast.makeText(MessageView.this, getString(R.string.message_view_status_attachment_not_saved), Toast.LENGTH_LONG).show();
}
} else {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(contentUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
} catch (ActivityNotFoundException e) {
mHandler.attachmentViewError();
}
}
}
|
public static String getHashedPassword(String password) {
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(password.getBytes());
BigInteger hashedInt = new BigInteger(1, digest.digest());
return String.format("%1$032X", hashedInt);
} catch (NoSuchAlgorithmException nsae) {
System.err.println(nsae.getMessage());
}
return "";
}
| 0
|
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String senha = "";
String email = request.getParameter("EmailLogin");
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(request.getParameter("SenhaLogin").getBytes(), 0, request.getParameter("SenhaLogin").length());
senha = new BigInteger(1, messageDigest.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Usuario usuario = UsuarioBll.getUsuarioByEmailAndSenha(email, senha);
String redirect = request.getHeader("REFERER").replace("?msg=3", "").replace("&msg=3", "") + "?&msg=3";
if (request.getHeader("REFERER").indexOf("?") != -1) {
redirect = request.getHeader("REFERER").replace("?msg=3", "").replace("&msg=3", "") + "&msg=3";
}
if (usuario.getNome() != null) {
HttpSession session = request.getSession();
session.setAttribute("usuario", usuario);
redirect = "index.jsp";
}
response.sendRedirect(redirect);
}
|
public void run(String[] args) throws Throwable {
FileInputStream input = new FileInputStream(args[0]);
FileOutputStream output = new FileOutputStream(args[0] + ".out");
Reader reader = $(Reader.class, $declass(input));
Writer writer = $(Writer.class, $declass(output));
Pump pump;
if (args.length > 1 && "diag".equals(args[1])) {
pump = $(new Reader() {
int counter;
@ToContext(mode = InvocationMode.sideEffect)
public int read(byte[] buffer, int off, int len) throws Exception {
Integer rd = (Integer) $next();
if (rd > 0) {
counter += rd;
}
return 0;
}
@ToContext(mode = InvocationMode.sideEffect)
public void close() throws Exception {
System.out.println("Read from input " + counter + " bytes.");
}
}, reader, writer, new Writer() {
int counter;
@ToContext(mode = InvocationMode.sideEffect)
public void write(byte[] buffer, int off, int len) throws Exception {
counter += len;
}
@ToContext(mode = InvocationMode.sideEffect)
public void close() throws Exception {
System.out.println("Written to output " + counter + " bytes.");
}
});
} else {
pump = $(reader, writer);
}
pump.pump();
}
| 0
|
public static void main(String args[]) {
int temp;
int[] a1 = { 6, 2, -3, 7, -1, 8, 9, 0 };
for (int j = 0; j < (a1.length * a1.length); j++) {
for (int i = 0; i < a1.length - 1; i++) {
if (a1[i] > a1[i + 1]) {
temp = a1[i];
a1[i] = a1[i + 1];
a1[i + 1] = temp;
}
}
}
for (int i = 0; i < a1.length; i++) {
System.out.print(" " + a1[i]);
}
}
|
private String getFullScreenUrl() {
progressDown.setIndeterminate(true);
System.out.println("Har: " + ytUrl);
String u = ytUrl;
URLConnection conn = null;
String line = null;
String data = "";
String fullUrl = "";
try {
URL url = new URL(u);
conn = url.openConnection();
conn.setDoOutput(true);
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null) {
if (line.contains("fullscreenUrl")) {
data = line.trim();
}
}
rd.close();
System.out.println(data);
int start = 0;
String[] lines = data.split("&");
String[] tmp = null;
String video_id = null;
String t = null;
String title = null;
for (int i = 0; i < lines.length; i++) {
if (lines[i].startsWith("video_id=")) {
tmp = lines[i].split("=");
video_id = tmp[1];
}
if (lines[i].startsWith("t=")) {
tmp = lines[i].split("=");
t = tmp[1];
}
if (lines[i].startsWith("title=")) {
tmp = lines[i].split("=");
title = tmp[1].substring(0, (tmp[1].length() - 2));
}
System.out.println(lines[i]);
}
System.out.println("So we got...");
System.out.println("video_id: " + video_id);
System.out.println("t: " + t);
System.out.println("title: " + title);
ytTitle = title;
fullUrl = "http://www.youtube.com/get_video.php?video_id=" + video_id + "&t=" + t;
} catch (Exception e) {
System.err.println("Error: " + e.getLocalizedMessage());
}
progressDown.setIndeterminate(false);
return fullUrl;
}
| 0
|
public static final void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.apache.org/");
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
httpget.abort();
}
|
public void run() {
BufferedReader reader = null;
String message = null;
int messageStyle = SWT.ICON_WARNING;
try {
URL url = new URL(Version.LATEST_VERSION_URL);
URLConnection conn = url.openConnection();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String latestVersion = reader.readLine();
latestVersion = latestVersion.substring(latestVersion.indexOf(' ') + 1);
if (!Version.getVersion().equals(latestVersion)) {
message = Labels.getLabel("text.version.old");
message = message.replaceFirst("%LATEST", latestVersion);
message = message.replaceFirst("%VERSION", Version.getVersion());
messageStyle = SWT.ICON_QUESTION | SWT.YES | SWT.NO;
} else {
message = Labels.getLabel("text.version.latest");
messageStyle = SWT.ICON_INFORMATION;
}
} catch (Exception e) {
message = Labels.getLabel("exception.UserErrorException.version.latestFailed");
Logger.getLogger(getClass().getName()).log(Level.WARNING, message, e);
} finally {
try {
if (reader != null) reader.close();
} catch (IOException e) {
}
final String messageToShow = message;
final int messageStyleToShow = messageStyle;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
statusBar.setStatusText(null);
MessageBox messageBox = new MessageBox(statusBar.getShell(), messageStyleToShow);
messageBox.setText(Version.getFullName());
messageBox.setMessage(messageToShow);
if (messageBox.open() == SWT.YES) {
BrowserLauncher.openURL(Version.DOWNLOAD_URL);
}
}
});
}
}
| 0
|
public String readPage(boolean ignoreComments) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
String html = "";
if (ignoreComments) {
while ((inputLine = in.readLine()) != null) {
if (inputLine.length() > 0) {
if (inputLine.substring(0, 1).compareTo("#") != 0) {
html = html + inputLine + "\n";
}
}
}
} else {
while ((inputLine = in.readLine()) != null) {
html = html + inputLine + "\n";
}
}
in.close();
return html;
}
|
private String encode(String plaintext) {
try {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(plaintext.getBytes("UTF-8"));
byte raw[] = md.digest();
return (new BASE64Encoder()).encode(raw);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Error encoding: " + e);
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Error encoding: " + e);
}
}
| 0
|
public static Body decodeBody(InputStream in, String contentTransferEncoding) throws IOException {
if (contentTransferEncoding != null) {
contentTransferEncoding = MimeUtility.getHeaderParameter(contentTransferEncoding, null);
if ("quoted-printable".equalsIgnoreCase(contentTransferEncoding)) {
in = new QuotedPrintableInputStream(in);
} else if ("base64".equalsIgnoreCase(contentTransferEncoding)) {
in = new Base64InputStream(in);
}
}
BinaryTempFileBody tempBody = new BinaryTempFileBody();
OutputStream out = tempBody.getOutputStream();
IOUtils.copy(in, out);
out.close();
return tempBody;
}
|
public void googleImageSearch(String search, String start) {
try {
String u = "http://images.google.com/images?q=" + search + start;
if (u.contains(" ")) {
u = u.replace(" ", "+");
}
URL url = new URL(u);
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
httpcon.addRequestProperty("User-Agent", "Mozilla/4.76");
BufferedReader readIn = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));
googleImages.clear();
String text = "";
String lin = "";
while ((lin = readIn.readLine()) != null) {
text += lin;
}
readIn.close();
if (text.contains("\n")) {
text = text.replace("\n", "");
}
String[] array = text.split("\\Qhref=\"/imgres?imgurl=\\E");
for (String s : array) {
if (s.startsWith("http://") || s.startsWith("https://") && s.contains("&")) {
String s1 = s.substring(0, s.indexOf("&"));
googleImages.add(s1);
}
}
} catch (Exception ex4) {
MusicBoxView.showErrorDialog(ex4);
}
MusicBoxView.jButton7.setEnabled(true);
ImageIcon icon;
try {
icon = new ImageIcon(new URL(googleImages.elementAt(MusicBoxView.googleImageLocation)));
ImageIcon ico = new ImageIcon(icon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH));
MusicBoxView.albumArtLabel.setIcon(ico);
} catch (MalformedURLException ex1) {
MusicBoxView.showErrorDialog(ex1);
}
}
| 0
|
public static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost(postURL);
File file = new File("d:/hai.html");
System.out.println(ukeycookie);
httppost.setHeader("Cookie", ukeycookie + ";" + skeycookie + ";" + usercookie);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("", cbFile);
httppost.setEntity(mpEntity);
System.out.println("Now uploading your file into mediafire...........................");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Getting upload response key value..........");
uploadresponsekey = EntityUtils.toString(resEntity);
getUploadResponseKey();
System.out.println("upload resoponse key " + uploadresponsekey);
}
}
|
private void unzip(File filename) throws ZipException, IOException {
ZipInputStream in = new ZipInputStream(new BufferedInputStream(new FileInputStream(filename)));
ZipEntry entry = null;
boolean first_entry = true;
while ((entry = in.getNextEntry()) != null) {
if (first_entry) {
if (!entry.isDirectory()) {
File subdir = new File(dir + File.separator + filename.getName().substring(0, filename.getName().length() - SUFFIX_ZIP.length()));
if (!subdir.exists()) {
subdir.mkdir();
dir = subdir;
}
}
first_entry = false;
}
if (entry.isDirectory()) {
FileUtils.forceMkdir(new File(dir + File.separator + entry.getName()));
} else {
File outfile = new File(dir + File.separator + entry.getName());
File outdir = new File(outfile.getAbsolutePath().substring(0, outfile.getAbsolutePath().length() - outfile.getName().length()));
if (!outdir.exists()) FileUtils.forceMkdir(outdir);
FileOutputStream fo = new FileOutputStream(outfile);
BufferedOutputStream bos = new BufferedOutputStream(fo, BUFFER);
int read;
byte data[] = new byte[BUFFER];
while ((read = in.read(data, 0, BUFFER)) != -1) {
read_position++;
bos.write(data, 0, read);
}
bos.flush();
bos.close();
}
}
in.close();
}
| 0
|
public void testPost() throws Exception {
HttpPost request = new HttpPost(baseUri + "/echo");
request.setEntity(new StringEntity("test"));
HttpResponse response = client.execute(request);
assertEquals(200, response.getStatusLine().getStatusCode());
assertEquals("test", TestUtil.getResponseAsString(response));
}
|
public void metodo1() {
int temp;
boolean flagDesordenado = true;
while (flagDesordenado) {
flagDesordenado = false;
for (int i = 0; i < this.tamanoTabla - 1; i++) {
if (tabla[i] > tabla[i + 1]) {
flagDesordenado = true;
temp = tabla[i];
tabla[i] = tabla[i + 1];
tabla[i + 1] = temp;
}
}
}
}
| 0
|
public static DigitalObjectContent byReference(final InputStream inputStream) {
try {
File tempFile = File.createTempFile("tempContent", "tmp");
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copyLarge(inputStream, out);
out.close();
return new ImmutableContent(tempFile);
} catch (IOException e) {
e.printStackTrace();
}
throw new IllegalStateException("Could not create content for input stream: " + inputStream);
}
|
public static SVNConfiguracion load(URL urlConfiguracion) {
SVNConfiguracion configuracion = null;
try {
XMLDecoder xenc = new XMLDecoder(urlConfiguracion.openStream());
configuracion = (SVNConfiguracion) xenc.readObject();
configuracion.setFicheroConfiguracion(urlConfiguracion);
xenc.close();
} catch (Exception exception) {
exception.printStackTrace();
}
return configuracion;
}
| 0
|
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.getURIString());
}
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.getURIString());
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 {
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(" ");
}
digest.update(s.getBytes());
byte[] newDigestValue = digest.digest();
if (logger.isLoggable(Level.FINEST)) {
logger.finest("Recalculated content digest for " + curi.getURIString() + " old: " + Base32.encode((byte[]) curi.getContentDigest()) + ", new: " + Base32.encode(newDigestValue));
}
curi.setContentDigest(newDigestValue);
}
|
void addDataFromURL(URL theurl) {
String line;
InputStream in = null;
try {
in = theurl.openStream();
BufferedReader data = new BufferedReader(new InputStreamReader(in));
while ((line = data.readLine()) != null) {
thetext.append(line + "\n");
}
} catch (Exception e) {
System.out.println(e.toString());
thetext.append(theurl.toString());
}
try {
in.close();
} catch (Exception e) {
}
}
| 0
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 11