List of usage examples for java.io DataOutputStream writeBytes
public final void writeBytes(String s) throws IOException
From source file:com.hollandhaptics.babyapp.BabyService.java
/** * @param sourceFile The file to upload. * @return int The server's response code. * @brief Uploads a file to the server. Is called by uploadAudioFiles(). *//* w w w . j a va 2 s . c om*/ public int uploadFile(File sourceFile) { HttpURLConnection conn; DataOutputStream dos; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1024 * 1024; String sourceFileUri = sourceFile.getAbsolutePath(); if (!sourceFile.isFile()) { Log.e("uploadFile", "Source File does not exist :" + sourceFileUri); return 0; } else { try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("fileToUpload", sourceFileUri); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"fileToUpload\";filename=\"" + sourceFileUri + "\"" + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 200) { boolean deleted = sourceFile.delete(); Log.i("Deleted succes", String.valueOf(deleted)); } //close the streams // fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); Log.e("Upload file to server", "Exception : " + e.getMessage(), e); } return serverResponseCode; } // End else block }
From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceIntegrationTest.java
@Test @RunAsClient/*from w ww. ja v a 2s . c om*/ public void testCreatePackageFromJAXB(@ArquillianResource URL baseURL) throws Exception { Package p = createTestPackage("TestCreatePackageFromJAXB"); p.setDescription("desc for testCreatePackageFromJAXB"); JAXBContext context = JAXBContext.newInstance(p.getClass()); Marshaller marshaller = context.createMarshaller(); StringWriter sw = new StringWriter(); marshaller.marshal(p, sw); String xml = sw.toString(); URL url = new URL(baseURL, "rest/packages"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", MediaType.APPLICATION_XML); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_XML); connection.setRequestProperty("Content-Length", Integer.toString(xml.getBytes().length)); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(xml); wr.flush(); wr.close(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_XML, connection.getContentType()); //System.out.println(IOUtils.toString(connection.getInputStream())); Package result = unmarshalPackageXML(connection.getInputStream()); assertEquals("TestCreatePackageFromJAXB", result.getTitle()); assertEquals("desc for testCreatePackageFromJAXB", result.getDescription()); assertNotNull(result.getPublished()); assertEquals(new URL(baseURL, "rest/packages/TestCreatePackageFromJAXB/source").toExternalForm(), result.getSourceLink().toString()); assertEquals(new URL(baseURL, "rest/packages/TestCreatePackageFromJAXB/binary").toExternalForm(), result.getBinaryLink().toString()); PackageMetadata pm = result.getMetadata(); assertFalse(pm.isArchived()); assertNotNull(pm.getCreated()); assertNotNull(pm.getUuid()); }
From source file:edu.slu.action.ObjectAction.java
public static String getAccessTokenWithAuth(String auth_code) throws UnsupportedEncodingException { System.out.println("Getting an access token"); String token = ""; int rcode = 0; String tokenURL = "https://cubap.auth0.com/oauth/token"; JSONObject body = new JSONObject(); //body.element("grant_type", "authorization_code"); body.element("grant_type", "client_credentials"); body.element("client_id", getRerumProperty("clientID")); body.element("client_secret", getRerumProperty("rerumSecret")); body.element("audience", "http://rerum.io/api"); //body.element("code", auth_code); body.element("redirect_uri", Constant.RERUM_BASE); //System.out.println("I will be using this body: "); //System.out.println(body); try {/*from w ww. j a v a 2s .c om*/ URL tURL = new URL(tokenURL); HttpURLConnection connection; connection = (HttpURLConnection) tURL.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.connect(); rcode = connection.getResponseCode(); if (connection.getResponseCode() == 401) { //One of the values used was wrong. The secret may have expired, the clientID may be wrong, the auth_code may be wrong or the user may not be a part of the RERUM client. token = "Auth0 responded 401. Contact RERUM."; } else if (connection.getResponseCode() >= 500) { token = "Auth0 had an internal error. Try again later. " + rcode; } else if (connection.getResponseCode() == 200) { DataOutputStream jsonString = new DataOutputStream(connection.getOutputStream()); jsonString.writeBytes(body.toString()); jsonString.flush(); jsonString.close(); BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder responseBlob = new StringBuilder(); String line; while ((line = input.readLine()) != null) { responseBlob.append(line); } input.close(); connection.disconnect(); JSONObject responseObj = new JSONObject(); if (responseBlob.length() > 0) { try { responseObj = JSONObject.fromObject(responseBlob.toString()); } catch (Exception e) { //response was not JSON, so let it an empty object. } } if (responseObj.containsKey("access_token")) { token = responseObj.getString("access_token"); if ("".equals(token)) { token = "Auth0 did not respond with a token."; } } else { token = "Auth0 did not respond with a token. "; } } else { token = "There was an issue contacting Auth0. " + rcode + ". Contact RERUM."; } } catch (ProtocolException ex) { Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex); } return token; }
From source file:com.acc.android.network.operator.base.BaseHttpOperator.java
private static void addFormField(Map<Object, Object> params, DataOutputStream output) { if (params == null || params.size() == 0) { return;//w ww . j a v a 2 s. co m } StringBuilder sb = new StringBuilder(); for (Map.Entry<Object, Object> param : params.entrySet()) { try { String encodeValue = URLEncoder.encode(param.getValue().toString(), HttpConstant.ENCODE); sb.append(UploadConstant.TWOHYPHENS + UploadConstant.BOUNDARY + UploadConstant.LINEEND); sb.append( "Content-Disposition: form-data; name=\"" + param.getKey() + "\"" + UploadConstant.LINEEND); sb.append(UploadConstant.LINEEND); sb.append(encodeValue + UploadConstant.LINEEND); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { output.writeBytes(sb.toString()); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.att.android.arodatacollector.main.AROCollectorService.java
/** * issue the kill -9 command if ffmpeg couldn't be stopped with kill -15 *///from w ww . j av a2s .co m private void kill9Ffmpeg() { Process sh = null; DataOutputStream os = null; int pid = 0, exitValue = -1; try { //have a 1 sec delay since it takes some time for the kill -15 to end ffmpeg Thread.sleep(1000); pid = mAroUtils.getProcessID("ffmpeg"); if (pid != 0) { //ffmpeg still running if (DEBUG) { Log.i(TAG, "ffmpeg still running after kill -15. Will issue kill -9 " + pid); } sh = Runtime.getRuntime().exec("su"); os = new DataOutputStream(sh.getOutputStream()); String Command = "kill -9 " + pid + "\n"; os.writeBytes(Command); Command = "exit\n"; os.writeBytes(Command); os.flush(); //clear the streams so that it doesnt block the process //sh.inputStream is actually the output from the process StreamClearer stdoutClearer = new StreamClearer(sh.getInputStream(), "stdout", false); new Thread(stdoutClearer).start(); StreamClearer stderrClearer = new StreamClearer(sh.getErrorStream(), "stderr", true); new Thread(stderrClearer).start(); exitValue = sh.waitFor(); if (exitValue == 0) { mVideoRecording = false; } else { Log.e(TAG, "could not kill ffmpeg in kill9Ffmpeg, exitValue=" + exitValue); } } else { mVideoRecording = false; if (DEBUG) { Log.i(TAG, "ffmpeg had been ended successfully by kill -15"); } } } catch (Exception e1) { Log.e(TAG, "exception in kill9Ffmpeg", e1); } finally { try { if (os != null) { os.close(); } if (sh != null) { sh.destroy(); } } catch (Exception e) { Log.e(TAG, "exception in kill9Ffmpeg DataOutputStream close", e); } } }
From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceIntegrationTest.java
@Test @RunAsClient/*ww w . j a va 2 s . c om*/ public void testUpdatePackageFromJAXB(@ArquillianResource URL baseURL) throws Exception { //create a package for fixtures Package p = createTestPackage("testUpdatePackageFromJAXB"); p.setDescription("desc for testUpdatePackageFromJAXB"); p.getMetadata().setCheckinComment("checkincomment for testUpdatePackageFromJAXB"); JAXBContext context = JAXBContext.newInstance(p.getClass()); Marshaller marshaller = context.createMarshaller(); StringWriter sw = new StringWriter(); marshaller.marshal(p, sw); String xml = sw.toString(); URL url = new URL(baseURL, "rest/packages"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_XML); connection.setRequestProperty("Content-Length", Integer.toString(xml.getBytes().length)); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Accept", MediaType.APPLICATION_XML); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(xml); wr.flush(); wr.close(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_XML, connection.getContentType()); //System.out.println(IOUtils.toString(connection.getInputStream())); Package result = unmarshalPackageXML(connection.getInputStream()); assertEquals("testUpdatePackageFromJAXB", result.getTitle()); assertEquals("desc for testUpdatePackageFromJAXB", result.getDescription()); assertNotNull(result.getPublished()); assertEquals(new URL(baseURL, "rest/packages/testUpdatePackageFromJAXB/source").toExternalForm(), result.getSourceLink().toString()); assertEquals(new URL(baseURL, "rest/packages/testUpdatePackageFromJAXB/binary").toExternalForm(), result.getBinaryLink().toString()); PackageMetadata pm = result.getMetadata(); assertFalse(pm.isArchived()); assertNotNull(pm.getCreated()); assertNotNull(pm.getUuid()); assertEquals("checkincomment for testUpdatePackageFromJAXB", pm.getCheckinComment()); //Test update package Package p2 = createTestPackage("testUpdatePackageFromJAXB"); p2.setDescription("update package testUpdatePackageFromJAXB"); PackageMetadata meta = new PackageMetadata(); meta.setCheckinComment("checkInComment: update package testUpdatePackageFromJAXB"); p2.setMetadata(meta); JAXBContext context2 = JAXBContext.newInstance(p2.getClass()); Marshaller marshaller2 = context2.createMarshaller(); StringWriter sw2 = new StringWriter(); marshaller2.marshal(p2, sw2); String xml2 = sw2.toString(); URL url2 = new URL(baseURL, "rest/packages/testUpdatePackageFromJAXB"); HttpURLConnection connection2 = (HttpURLConnection) url2.openConnection(); connection2.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection2.setRequestMethod("PUT"); connection2.setRequestProperty("Content-Type", MediaType.APPLICATION_XML); connection2.setRequestProperty("Content-Length", Integer.toString(xml2.getBytes().length)); connection2.setUseCaches(false); //connection2.setDoInput(true); connection2.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection2.getOutputStream()); out.write(xml2); out.close(); connection2.getInputStream(); //Verify URL url3 = new URL(baseURL, "rest/packages/testUpdatePackageFromJAXB"); HttpURLConnection connection3 = (HttpURLConnection) url3.openConnection(); connection3.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection3.setRequestMethod("GET"); connection3.setRequestProperty("Accept", MediaType.APPLICATION_XML); connection3.connect(); assertEquals(200, connection3.getResponseCode()); assertEquals(MediaType.APPLICATION_XML, connection3.getContentType()); //System.out.println("------------------------"); //System.out.println(IOUtils.toString(connection.getInputStream())); Package p3 = unmarshalPackageXML(connection3.getInputStream()); assertEquals("testUpdatePackageFromJAXB", p3.getTitle()); assertEquals("update package testUpdatePackageFromJAXB", p3.getDescription()); assertNotNull(p3.getPublished()); assertEquals(new URL(baseURL, "rest/packages/testUpdatePackageFromJAXB/source").toExternalForm(), p3.getSourceLink().toString()); assertEquals(new URL(baseURL, "rest/packages/testUpdatePackageFromJAXB/binary").toExternalForm(), p3.getBinaryLink().toString()); PackageMetadata pm3 = p3.getMetadata(); assertFalse(pm3.isArchived()); assertNotNull(pm3.getCreated()); assertNotNull(pm3.getUuid()); assertEquals("checkInComment: update package testUpdatePackageFromJAXB", pm3.getCheckinComment()); }
From source file:com.etalio.android.EtalioBase.java
protected String multipartRequest(String urlTo, InputStream fileInputStream, String filefield, String filename) throws ParseException, IOException, EtalioHttpException { HttpURLConnection connection = null; DataOutputStream outputStream = null; InputStream inputStream = null; String twoHyphens = "--"; String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****"; String lineEnd = "\r\n"; String result = ""; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; try {/*from w ww .j av a 2s. co m*/ URL url = new URL(urlTo); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Authorization", " Bearer " + getEtalioToken().getAccessToken()); connection.setRequestProperty("User-Agent", getEtalioUserAgent()); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + filename + "\"" + lineEnd); outputStream.writeBytes("Content-Type: " + MimeTypeUtil.getMimeType(filename) + lineEnd); outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.writeBytes(lineEnd); outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); inputStream = connection.getInputStream(); if (connection.getResponseCode() > 300) { result = convertStreamToString(connection.getErrorStream()); } else { result = this.convertStreamToString(inputStream); } fileInputStream.close(); inputStream.close(); outputStream.flush(); outputStream.close(); return result; } catch (Exception e) { throw new EtalioHttpException(connection.getResponseCode(), connection.getResponseMessage(), e.getMessage()); } }
From source file:com.att.android.arodatacollector.main.AROCollectorService.java
/** * Stops the Screen video capture//from w w w .j a v a 2 s . c om */ private void stopScreenVideoCapture() { Log.i(TAG, "enter stopScreenVideoCapture at " + System.currentTimeMillis()); Process sh = null; DataOutputStream os = null; int pid = 0, exitValue = -1; try { pid = mAroUtils.getProcessID("ffmpeg"); } catch (IOException e1) { Log.e(TAG, "IOException in stopScreenVideoCapture", e1); } catch (InterruptedException e1) { Log.e(TAG, "exception in stopScreenVideoCapture", e1); } if (DEBUG) { Log.i(TAG, "stopScreenVideoCapture=" + pid); } if (pid != 0) { try { sh = Runtime.getRuntime().exec("su"); os = new DataOutputStream(sh.getOutputStream()); String command = "kill -15 " + pid + "\n"; os.writeBytes(command); command = "exit\n"; os.writeBytes(command); os.flush(); //clear the streams so that it doesnt block the process //sh.inputStream is actually the output from the process StreamClearer stdoutClearer = new StreamClearer(sh.getInputStream(), "stdout", false); new Thread(stdoutClearer).start(); StreamClearer stderrClearer = new StreamClearer(sh.getErrorStream(), "stderr", true); new Thread(stderrClearer).start(); exitValue = sh.waitFor(); if (exitValue == 0) { mVideoRecording = false; } if (DEBUG) { Log.i(TAG, "successfully returned from kill -15; exitValue= " + exitValue); } } catch (IOException e) { Log.e(TAG, "exception in stopScreenVideoCapture", e); } catch (InterruptedException e) { Log.e(TAG, "exception in stopScreenVideoCapture", e); } finally { try { kill9Ffmpeg(); if (os != null) { os.close(); } if (sh != null) { sh.destroy(); } } catch (Exception e) { Log.e(TAG, "exception in stopScreenVideoCapture finally block", e); } if (DEBUG) { Log.i(TAG, "Stopped Video Capture in stopScreenVideoCapture()"); } } } if (DEBUG) { Log.i(TAG, "exit stopScreenVideoCapture"); } }
From source file:com.appcelerator.titanium.desktop.ui.wizard.Packager.java
private IStatus invokeCloudService(URL baseURL, Map<String, String> data, String type) { DataOutputStream outputStream = null; try {/* ww w. ja v a 2 s .c o m*/ if (type == null) { type = "POST"; //$NON-NLS-1$ } if (data == null) { data = new HashMap<String, String>(); } // always pass MID data.put("mid", TitaniumCorePlugin.getMID()); //$NON-NLS-1$ ITitaniumUser user = TitaniumCorePlugin.getDefault().getUserManager().getSignedInUser(); data.put("sid", user.getSessionID()); //$NON-NLS-1$ data.put("token", user.getToken()); //$NON-NLS-1$ data.put("uid", user.getUID()); //$NON-NLS-1$ data.put("uidt", user.getUIDT()); //$NON-NLS-1$ // If this is not a POST, append query params don't put as data in body! if (!"POST".equals(type)) //$NON-NLS-1$ { baseURL = makeURL(baseURL.toString(), data); } HttpURLConnection con = (HttpURLConnection) baseURL.openConnection(); con.setUseCaches(false); con.setRequestMethod(type); con.setRequestProperty("User-Agent", TitaniumConstants.USER_AGENT); //$NON-NLS-1$ if ("POST".equals(type)) //$NON-NLS-1$ { con.setDoOutput(true); // Write the data to the connection outputStream = new DataOutputStream(con.getOutputStream()); outputStream.writeBytes(getQueryString(data)); outputStream.flush(); } IdeLog.logInfo(DesktopPlugin.getDefault(), MessageFormat.format("API Request: {0}", baseURL), //$NON-NLS-1$ com.appcelerator.titanium.core.IDebugScopes.API); // Force to finish, grab response code int code = con.getResponseCode(); // If the http code is 200 from POST, parse response as JSON. Else display error if (code == 200) { String responseText = IOUtil.read(con.getInputStream()); IdeLog.logInfo(DesktopPlugin.getDefault(), MessageFormat.format("API Response: {0}:{1}", code, responseText), //$NON-NLS-1$ com.appcelerator.titanium.core.IDebugScopes.API); return new Status(IStatus.OK, DesktopPlugin.PLUGIN_ID, code, responseText, null); } // TODO Read from connection to populate message! return new Status(IStatus.ERROR, DesktopPlugin.PLUGIN_ID, code, null, null); } catch (Exception e) { return new Status(IStatus.ERROR, DesktopPlugin.PLUGIN_ID, 0, e.getMessage(), e); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { // ignores the exception } } } }
From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceIntegrationTest.java
@Test @RunAsClient//from w w w . ja v a2 s . c o m public void testRenamePackageFromXML(@ArquillianResource URL baseURL) throws Exception { //create a package for testing Package p = createTestPackage("testRenamePackageFromXML"); p.setDescription("desc for testRenamePackageFromXML"); JAXBContext context = JAXBContext.newInstance(p.getClass()); Marshaller marshaller = context.createMarshaller(); StringWriter sw = new StringWriter(); marshaller.marshal(p, sw); String xml = sw.toString(); URL url = new URL(baseURL, "rest/packages"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_XML); connection.setRequestProperty("Content-Length", Integer.toString(xml.getBytes().length)); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Accept", MediaType.APPLICATION_XML); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(xml); wr.flush(); wr.close(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_XML, connection.getContentType()); //System.out.println(IOUtils.toString(connection.getInputStream())); Package result = unmarshalPackageXML(connection.getInputStream()); assertEquals("testRenamePackageFromXML", result.getTitle()); assertEquals("desc for testRenamePackageFromXML", result.getDescription()); assertNotNull(result.getPublished()); assertEquals(new URL(baseURL, "rest/packages/testRenamePackageFromXML/source").toExternalForm(), result.getSourceLink().toString()); assertEquals(new URL(baseURL, "rest/packages/testRenamePackageFromXML/binary").toExternalForm(), result.getBinaryLink().toString()); PackageMetadata pm = result.getMetadata(); assertFalse(pm.isArchived()); assertNotNull(pm.getCreated()); assertNotNull(pm.getUuid()); //Test rename package p.setDescription("renamed package testRenamePackageFromXML"); p.setTitle("testRenamePackageFromXMLNew"); JAXBContext context2 = JAXBContext.newInstance(p.getClass()); Marshaller marshaller2 = context2.createMarshaller(); StringWriter sw2 = new StringWriter(); marshaller2.marshal(p, sw2); String xml2 = sw2.toString(); URL url2 = new URL(baseURL, "rest/packages/testRenamePackageFromXML"); HttpURLConnection connection2 = (HttpURLConnection) url2.openConnection(); connection2.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection2.setRequestMethod("PUT"); connection2.setRequestProperty("Content-Type", MediaType.APPLICATION_XML); connection2.setRequestProperty("Content-Length", Integer.toString(xml2.getBytes().length)); connection2.setUseCaches(false); //connection2.setDoInput(true); connection2.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection2.getOutputStream()); out.write(xml2); out.close(); connection2.getInputStream(); //assertEquals (200, connection2.getResponseCode()); //Verify the new package is available after renaming URL url3 = new URL(baseURL, "rest/packages/testRenamePackageFromXMLNew"); HttpURLConnection conn3 = (HttpURLConnection) url3.openConnection(); conn3.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); conn3.setRequestMethod("GET"); conn3.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); conn3.connect(); //System.out.println(GetContent(conn)); assertEquals(200, conn3.getResponseCode()); assertEquals(MediaType.APPLICATION_ATOM_XML, conn3.getContentType()); InputStream in = conn3.getInputStream(); assertNotNull(in); Document<Entry> doc = abdera.getParser().parse(in); Entry entry = doc.getRoot(); assertEquals(baseURL.getPath() + "rest/packages/testRenamePackageFromXMLNew", entry.getBaseUri().getPath()); assertEquals("testRenamePackageFromXMLNew", entry.getTitle()); assertTrue(entry.getPublished() != null); assertEquals("renamed package testRenamePackageFromXML", entry.getSummary()); //Verify the old package does not exist after renaming URL url4 = new URL(baseURL, "rest/packages/testRenamePackageFromXML"); HttpURLConnection conn4 = (HttpURLConnection) url4.openConnection(); conn4.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); conn4.setRequestMethod("GET"); conn4.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); conn4.connect(); //System.out.println(IOUtils.toString(connection.getInputStream())); assertEquals(404, conn4.getResponseCode()); //Roll back changes. Abdera abdera = new Abdera(); AbderaClient client = new AbderaClient(abdera); client.addCredentials(baseURL.toExternalForm(), null, null, new org.apache.commons.httpclient.UsernamePasswordCredentials("admin", "admin")); ClientResponse resp = client .delete(new URL(baseURL, "rest/packages/testRenamePackageFromXMLNew").toExternalForm()); assertEquals(ResponseType.SUCCESS, resp.getType()); //Verify the package is indeed deleted URL url5 = new URL(baseURL, "rest/packages/testRenamePackageFromXMLNew"); HttpURLConnection conn5 = (HttpURLConnection) url5.openConnection(); conn5.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); conn5.setRequestMethod("GET"); conn5.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); conn5.connect(); //System.out.println(IOUtils.toString(connection.getInputStream())); assertEquals(404, conn5.getResponseCode()); }