Java Code Examples for org.apache.commons.httpclient.methods.PutMethod#setRequestEntity()

The following examples show how to use org.apache.commons.httpclient.methods.PutMethod#setRequestEntity() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DavExchangeSession.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
protected PutMethod internalCreateOrUpdate(String encodedHref, byte[] mimeContent) throws IOException {
    PutMethod putmethod = new PutMethod(encodedHref);
    putmethod.setRequestHeader("Translate", "f");
    putmethod.setRequestHeader("Overwrite", "f");
    if (etag != null) {
        putmethod.setRequestHeader("If-Match", etag);
    }
    if (noneMatch != null) {
        putmethod.setRequestHeader("If-None-Match", noneMatch);
    }
    putmethod.setRequestHeader("Content-Type", "message/rfc822");
    putmethod.setRequestEntity(new ByteArrayRequestEntity(mimeContent, "message/rfc822"));
    try {
        httpClient.executeMethod(putmethod);
    } finally {
        putmethod.releaseConnection();
    }
    return putmethod;
}
 
Example 2
Source File: HttpUtils.java    From Java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * 处理Put请求
 * @param url
 * @param headers
 * @param object
 * @param property
 * @return
 */
public static JSONObject doPut(String url, Map<String, String> headers,String jsonString) {

	HttpClient httpClient = new HttpClient();
	
	PutMethod putMethod = new PutMethod(url);
	
	//设置header
	setHeaders(putMethod,headers);
	
	//设置put传递的json数据
	if(jsonString!=null&&!"".equals(jsonString)){
		putMethod.setRequestEntity(new ByteArrayRequestEntity(jsonString.getBytes()));
	}
	
	String responseStr = "";
	
	try {
		httpClient.executeMethod(putMethod);
		responseStr = putMethod.getResponseBodyAsString();
	} catch (Exception e) {
		log.error(e);
		responseStr="{status:0}";
	} 
	return JSONObject.parseObject(responseStr);
}
 
Example 3
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Test machine format for gender and date
 */
@Test
public void testCreateUser2() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final UserVO vo = new UserVO();
    final String username = UUID.randomUUID().toString();
    vo.setLogin(username);
    vo.setFirstName("John");
    vo.setLastName("Smith");
    vo.setEmail(username + "@frentix.com");
    vo.putProperty("telOffice", "39847592");
    vo.putProperty("telPrivate", "39847592");
    vo.putProperty("telMobile", "39847592");
    vo.putProperty("gender", "female");// male or female
    vo.putProperty("birthDay", "20091212");

    final String stringuifiedAuth = stringuified(vo);
    final PutMethod method = createPut("/users", MediaType.APPLICATION_JSON, true);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    method.setRequestEntity(entity);
    method.addRequestHeader("Accept-Language", "en");

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final UserVO savedVo = parse(body, UserVO.class);

    final Identity savedIdent = securityManager.findIdentityByName(username);

    assertNotNull(savedVo);
    assertNotNull(savedIdent);
    assertEquals(savedVo.getKey(), savedIdent.getKey());
    assertEquals(savedVo.getLogin(), savedIdent.getName());
    assertEquals("Female", userService.getUserProperty(savedIdent.getUser(), UserConstants.GENDER, Locale.ENGLISH));
    assertEquals("39847592", userService.getUserProperty(savedIdent.getUser(), UserConstants.TELPRIVATE, Locale.ENGLISH));
    assertEquals("12/12/09", userService.getUserProperty(savedIdent.getUser(), UserConstants.BIRTHDAY, Locale.ENGLISH));
}
 
Example 4
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportTest() throws HttpException, IOException, URISyntaxException {
    final URL cpUrl = RepositoryEntriesITCase.class.getResource("qti-demo.zip");
    assertNotNull(cpUrl);
    final File cp = new File(cpUrl.toURI());

    final HttpClient c = loginWithCookie("administrator", "olat");
    final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
    final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "qti-demo.zip"), new StringPart("resourcename", "QTI demo"),
            new StringPart("displayname", "QTI demo") };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
    assertNotNull(vo);

    final Long key = vo.getKey();
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
    assertNotNull(re);
    assertNotNull(re.getOwnerGroup());
    assertNotNull(re.getOlatResource());
    assertEquals("QTI demo", re.getDisplayname());
    log.info(re.getOlatResource().getResourceableTypeName());
}
 
Example 5
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportCp() throws HttpException, IOException, URISyntaxException {
    final URL cpUrl = RepositoryEntriesITCase.class.getResource("cp-demo.zip");
    assertNotNull(cpUrl);
    final File cp = new File(cpUrl.toURI());

    final HttpClient c = loginWithCookie("administrator", "olat");
    final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
    final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "cp-demo.zip"), new StringPart("resourcename", "CP demo"),
            new StringPart("displayname", "CP demo") };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
    assertNotNull(vo);

    final Long key = vo.getKey();
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
    assertNotNull(re);
    assertNotNull(re.getOwnerGroup());
    assertNotNull(re.getOlatResource());
    assertEquals("CP demo", re.getDisplayname());
}
 
Example 6
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportCp() throws HttpException, IOException, URISyntaxException {
    final URL cpUrl = RepositoryEntriesITCase.class.getResource("cp-demo.zip");
    assertNotNull(cpUrl);
    final File cp = new File(cpUrl.toURI());

    final HttpClient c = loginWithCookie("administrator", "olat");
    final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
    final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "cp-demo.zip"), new StringPart("resourcename", "CP demo"),
            new StringPart("displayname", "CP demo") };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
    assertNotNull(vo);

    final Long key = vo.getKey();
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
    assertNotNull(re);
    assertNotNull(re.getOwnerGroup());
    assertNotNull(re.getOlatResource());
    assertEquals("CP demo", re.getDisplayname());
}
 
Example 7
Source File: DifidoClient.java    From difido-reports with Apache License 2.0 5 votes vote down vote up
public void updateMachine(int executionId, int machineId, MachineNode machine) throws Exception {
	PutMethod method = new PutMethod(baseUri + "executions/" + executionId + "/machines/" + machineId);
	method.setRequestHeader(new Header("Content-Type", "application/json"));
	final ObjectMapper mapper = new ObjectMapper();
	final String json = mapper.writeValueAsString(machine);
	final RequestEntity entity = new StringRequestEntity(json,"application/json","UTF-8");
	method.setRequestEntity(entity);
	int responseCode = client.executeMethod(method);
	handleResponseCode(method, responseCode);
}
 
Example 8
Source File: DifidoClient.java    From difido-reports with Apache License 2.0 5 votes vote down vote up
public void updateMachine(int executionId, int machineId, MachineNode machine) throws Exception {
	PutMethod method = new PutMethod(baseUri + "executions/" + executionId + "/machines/" + machineId);
	method.setRequestHeader(new Header("Content-Type", "application/json"));
	final ObjectMapper mapper = new ObjectMapper();
	final String json = mapper.writeValueAsString(machine);
	final RequestEntity entity = new StringRequestEntity(json,"application/json","UTF-8");
	method.setRequestEntity(entity);
	int responseCode = client.executeMethod(method);
	handleResponseCode(method, responseCode);
}
 
Example 9
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportBlog() throws HttpException, IOException, URISyntaxException {
    final URL cpUrl = RepositoryEntriesITCase.class.getResource("blog-demo.zip");
    assertNotNull(cpUrl);
    final File cp = new File(cpUrl.toURI());

    final HttpClient c = loginWithCookie("administrator", "olat");
    final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
    final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "blog-demo.zip"), new StringPart("resourcename", "Blog demo"),
            new StringPart("displayname", "Blog demo") };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
    assertNotNull(vo);

    final Long key = vo.getKey();
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
    assertNotNull(re);
    assertNotNull(re.getOwnerGroup());
    assertNotNull(re.getOlatResource());
    assertEquals("Blog demo", re.getDisplayname());
    log.info(re.getOlatResource().getResourceableTypeName());
}
 
Example 10
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateUserWithValidationError() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final UserVO vo = new UserVO();
    vo.setLogin("rest-809");
    vo.setFirstName("John");
    vo.setLastName("Smith");
    vo.setEmail("");
    vo.putProperty("gender", "lu");

    final String stringuifiedAuth = stringuified(vo);
    final PutMethod method = createPut("/users", MediaType.APPLICATION_JSON, true);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    method.setRequestEntity(entity);

    final int code = c.executeMethod(method);
    assertTrue(code == 406);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<ErrorVO> errors = parseErrorArray(body);
    assertNotNull(errors);
    assertFalse(errors.isEmpty());
    assertTrue(errors.size() >= 2);
    assertNotNull(errors.get(0).getCode());
    assertNotNull(errors.get(0).getTranslation());
    assertNotNull(errors.get(1).getCode());
    assertNotNull(errors.get(1).getTranslation());

    final Identity savedIdent = securityManager.findIdentityByName("rest-809");
    assertNull(savedIdent);
}
 
Example 11
Source File: AbstractSubmarineServerTest.java    From submarine with Apache License 2.0 5 votes vote down vote up
protected static PutMethod httpPut(String path, String body, String user, String pwd) throws IOException {
  LOG.info("Connecting to {}", URL + path);
  HttpClient httpClient = new HttpClient();
  PutMethod putMethod = new PutMethod(URL + path);
  putMethod.addRequestHeader("Origin", URL);
  putMethod.setRequestHeader("Content-type", "application/yaml");
  RequestEntity entity = new ByteArrayRequestEntity(body.getBytes("UTF-8"));
  putMethod.setRequestEntity(entity);
  if (userAndPasswordAreNotBlank(user, pwd)) {
    putMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
  }
  httpClient.executeMethod(putMethod);
  LOG.info("{} - {}", putMethod.getStatusCode(), putMethod.getStatusText());
  return putMethod;
}
 
Example 12
Source File: Tr069DMAdapter.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void callPutFileApi(String fileType, String url, String filePath, String oui, String prodClass, String version) throws HttpException, IOException, HitDMException {
	org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
	
	PutMethod putMethod = new PutMethod(url);
	File input = new File(filePath);
	RequestEntity entity = new FileRequestEntity(input, "Content-Length: 1431");
	putMethod.setRequestEntity(entity);
	putMethod.setRequestHeader("fileType", fileType);
	putMethod.setRequestHeader("oui", oui);
	putMethod.setRequestHeader("productClass", prodClass);
	putMethod.setRequestHeader("version", version);
	
	client.executeMethod(putMethod);
	
	if (putMethod.getStatusCode() != 200) {
		String debugStr = "DM Server return:"+ putMethod.getStatusCode();
		byte[] body;
		try {
			body = putMethod.getResponseBody();
			if (body != null) {
				debugStr += "\r\nBody:"+new String(body);
			}
		} catch (Exception e) {
			debugStr += e.getMessage();
		}
		
		throw new HitDMException(putMethod.getStatusCode(), debugStr);
	}
	
}
 
Example 13
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportWiki() throws HttpException, IOException, URISyntaxException {
    final URL cpUrl = RepositoryEntriesITCase.class.getResource("wiki-demo.zip");
    assertNotNull(cpUrl);
    final File cp = new File(cpUrl.toURI());

    final HttpClient c = loginWithCookie("administrator", "olat");
    final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
    final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "wiki-demo.zip"), new StringPart("resourcename", "Wiki demo"),
            new StringPart("displayname", "Wiki demo") };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
    assertNotNull(vo);

    final Long key = vo.getKey();
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
    assertNotNull(re);
    assertNotNull(re.getOwnerGroup());
    assertNotNull(re.getOlatResource());
    assertEquals("Wiki demo", re.getDisplayname());
    log.info(re.getOlatResource().getResourceableTypeName());
}
 
Example 14
Source File: CatalogITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutCategoryJson() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final CatalogEntryVO subEntry = new CatalogEntryVO();
    subEntry.setName("Sub-entry-1");
    subEntry.setDescription("Sub-entry-description-1");
    subEntry.setType(CatalogEntry.TYPE_NODE);
    final String entity = stringuified(subEntry);

    final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).build();
    final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.APPLICATION_JSON);
    final RequestEntity requestEntity = new StringRequestEntity(entity, MediaType.APPLICATION_JSON, "UTF-8");
    method.setRequestEntity(requestEntity);

    final int code = c.executeMethod(method);
    assertEquals(200, code);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final CatalogEntryVO vo = parse(body, CatalogEntryVO.class);
    assertNotNull(vo);

    final List<CatalogEntry> children = catalogService.getChildrenOf(entry1);
    boolean saved = false;
    for (final CatalogEntry child : children) {
        if (vo.getKey().equals(child.getKey())) {
            saved = true;
            break;
        }
    }

    assertTrue(saved);
}
 
Example 15
Source File: PublicApiHttpClient.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public HttpResponse put(final Class<?> c, final RequestContext rq, final Object entityId, final Object relationshipEntityId, final String body)
            throws IOException
{
    RestApiEndpoint endpoint = new RestApiEndpoint(c, rq.getNetworkId(), entityId, relationshipEntityId, null);
    String url = endpoint.getUrl();

    PutMethod req = new PutMethod(url);
    if (body != null)
    {
        StringRequestEntity requestEntity = new StringRequestEntity(body, "application/json", "UTF-8");
        req.setRequestEntity(requestEntity);
    }
    return submitRequest(req, rq);
}
 
Example 16
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportWiki() throws HttpException, IOException, URISyntaxException {
    final URL cpUrl = RepositoryEntriesITCase.class.getResource("wiki-demo.zip");
    assertNotNull(cpUrl);
    final File cp = new File(cpUrl.toURI());

    final HttpClient c = loginWithCookie("administrator", "olat");
    final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
    final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "wiki-demo.zip"), new StringPart("resourcename", "Wiki demo"),
            new StringPart("displayname", "Wiki demo") };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
    assertNotNull(vo);

    final Long key = vo.getKey();
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
    assertNotNull(re);
    assertNotNull(re.getOwnerGroup());
    assertNotNull(re.getOlatResource());
    assertEquals("Wiki demo", re.getDisplayname());
    log.info(re.getOlatResource().getResourceableTypeName());
}
 
Example 17
Source File: UploadBitsCommand.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected ServerStatus _doIt() {
	/* multi server status */
	MultiServerStatus status = new MultiServerStatus();

	try {

		/* upload project contents */
		File appPackage = packager.getDeploymentPackage(super.getApplication(), appStore, command);
		deployedAppPackageName = PackageUtils.getApplicationPackageType(appStore);

		if (appPackage == null) {
			status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to read application content", null));
			return status;
		}

		URI targetURI = URIUtil.toURI(target.getUrl());
		PutMethod uploadMethod = new PutMethod(targetURI.resolve("/v2/apps/" + getApplication().getGuid() + "/bits?async=true").toString());
		uploadMethod.addRequestHeader(new Header("Authorization", "bearer " + target.getCloud().getAccessToken().getString("access_token")));

		Part[] parts = {new StringPart(CFProtocolConstants.V2_KEY_RESOURCES, "[]"), new FilePart(CFProtocolConstants.V2_KEY_APPLICATION, appPackage)};
		uploadMethod.setRequestEntity(new MultipartRequestEntity(parts, uploadMethod.getParams()));

		/* send request */
		ServerStatus jobStatus = HttpUtil.executeMethod(uploadMethod);
		status.add(jobStatus);
		if (!jobStatus.isOK())
			return status;

		/* long running task, keep track */
		int attemptsLeft = MAX_ATTEMPTS;
		JSONObject resp = jobStatus.getJsonData();
		String taksStatus = resp.getJSONObject(CFProtocolConstants.V2_KEY_ENTITY).getString(CFProtocolConstants.V2_KEY_STATUS);
		while (!CFProtocolConstants.V2_KEY_FINISHED.equals(taksStatus) && !CFProtocolConstants.V2_KEY_FAILURE.equals(taksStatus)) {
			if (CFProtocolConstants.V2_KEY_FAILED.equals(taksStatus)) {
				/* delete the tmp file */
				appPackage.delete();
				status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Upload failed", null));
				return status;
			}

			if (attemptsLeft == 0) {
				/* delete the tmp file */
				appPackage.delete();
				status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Upload timeout exceeded", null));
				return status;
			}

			/* two seconds */
			Thread.sleep(2000);

			/* check whether job has finished */
			URI jobLocation = targetURI.resolve(resp.getJSONObject(CFProtocolConstants.V2_KEY_METADATA).getString(CFProtocolConstants.V2_KEY_URL));
			GetMethod jobRequest = new GetMethod(jobLocation.toString());
			ServerStatus confStatus = HttpUtil.configureHttpMethod(jobRequest, target.getCloud());
			if (!confStatus.isOK())
				return confStatus;

			/* send request */
			jobStatus = HttpUtil.executeMethod(jobRequest);
			status.add(jobStatus);
			if (!jobStatus.isOK())
				return status;

			resp = jobStatus.getJsonData();
			taksStatus = resp.getJSONObject(CFProtocolConstants.V2_KEY_ENTITY).getString(CFProtocolConstants.V2_KEY_STATUS);

			--attemptsLeft;
		}

		if (CFProtocolConstants.V2_KEY_FAILURE.equals(jobStatus)) {
			status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to upload application bits", null));
			return status;
		}

		/* delete the tmp file */
		appPackage.delete();
		return status;

	} catch (Exception e) {
		String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
		logger.error(msg, e);
		status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
		return status;
	}
}
 
Example 18
Source File: SystemRegistrationWorker.java    From olat with Apache License 2.0 4 votes vote down vote up
protected boolean doTheWork(String registrationData, String url, String version) {
    String registrationKey = propertyService.getStringProperty(PropertyLocator.SYSTEM_REG_SECRET_KEY);
    boolean regStatus = false;
    if (StringHelper.containsNonWhitespace(registrationData)) {
        // only send when there is something to send
        final HttpClient client = HttpClientFactory.getHttpClientInstance();
        client.getParams().setParameter("http.useragent", "OLAT Registration Agent ; " + version);

        log.info("URL:" + url, null);
        final PutMethod method = new PutMethod(url);
        if (registrationKey != null) {
            // updating
            method.setRequestHeader("Authorization", registrationKey);
            if (log.isDebugEnabled()) {
                log.debug("Authorization: " + registrationKey, null);
            } else {
                log.debug("Authorization: EXISTS", null);
            }
        } else {
            log.info("Authorization: NONE", null);
        }
        method.setRequestHeader("Content-Type", "application/xml; charset=utf-8");
        try {
            method.setRequestEntity(new StringRequestEntity(registrationData, "application/xml", "UTF8"));
            client.executeMethod(method);
            final int status = method.getStatusCode();
            if (status == HttpStatus.SC_NOT_MODIFIED || status == HttpStatus.SC_OK) {
                log.info("Successfully registered OLAT installation on olat.org server, thank you for your support!", null);
                registrationKey = method.getResponseBodyAsString();
                propertyService.setProperty(PropertyLocator.SYSTEM_REG_SECRET_KEY, registrationKey);
                regStatus = true;
            } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                log.error("File could be created not on registration server::" + method.getStatusLine().toString(), null);
                regStatus = false;
            } else if (method.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
                log.info(method.getResponseBodyAsString() + method.getStatusText());
                regStatus = false;
            } else {
                log.error("Unexpected HTTP Status::" + method.getStatusLine().toString() + " during registration call", null);
                regStatus = false;
            }
        } catch (final Exception e) {
            log.error("Unexpected exception during registration call", e);
            regStatus = false;
        }
    } else {
        log.warn(
                "****************************************************************************************************************************************************************************",
                null);
        log.warn(
                "* This OLAT installation is not registered. Please, help us with your statistical data and register your installation under Adminisration - Systemregistration. THANK YOU! *",
                null);
        log.warn(
                "****************************************************************************************************************************************************************************",
                null);
    }
    return regStatus;
}
 
Example 19
Source File: SystemRegistrationWorker.java    From olat with Apache License 2.0 4 votes vote down vote up
protected boolean doTheWork(String registrationData, String url, String version) {
    String registrationKey = propertyService.getStringProperty(PropertyLocator.SYSTEM_REG_SECRET_KEY);
    boolean regStatus = false;
    if (StringHelper.containsNonWhitespace(registrationData)) {
        // only send when there is something to send
        final HttpClient client = HttpClientFactory.getHttpClientInstance();
        client.getParams().setParameter("http.useragent", "OLAT Registration Agent ; " + version);

        log.info("URL:" + url, null);
        final PutMethod method = new PutMethod(url);
        if (registrationKey != null) {
            // updating
            method.setRequestHeader("Authorization", registrationKey);
            if (log.isDebugEnabled()) {
                log.debug("Authorization: " + registrationKey, null);
            } else {
                log.debug("Authorization: EXISTS", null);
            }
        } else {
            log.info("Authorization: NONE", null);
        }
        method.setRequestHeader("Content-Type", "application/xml; charset=utf-8");
        try {
            method.setRequestEntity(new StringRequestEntity(registrationData, "application/xml", "UTF8"));
            client.executeMethod(method);
            final int status = method.getStatusCode();
            if (status == HttpStatus.SC_NOT_MODIFIED || status == HttpStatus.SC_OK) {
                log.info("Successfully registered OLAT installation on olat.org server, thank you for your support!", null);
                registrationKey = method.getResponseBodyAsString();
                propertyService.setProperty(PropertyLocator.SYSTEM_REG_SECRET_KEY, registrationKey);
                regStatus = true;
            } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                log.error("File could be created not on registration server::" + method.getStatusLine().toString(), null);
                regStatus = false;
            } else if (method.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
                log.info(method.getResponseBodyAsString() + method.getStatusText());
                regStatus = false;
            } else {
                log.error("Unexpected HTTP Status::" + method.getStatusLine().toString() + " during registration call", null);
                regStatus = false;
            }
        } catch (final Exception e) {
            log.error("Unexpected exception during registration call", e);
            regStatus = false;
        }
    } else {
        log.warn(
                "****************************************************************************************************************************************************************************",
                null);
        log.warn(
                "* This OLAT installation is not registered. Please, help us with your statistical data and register your installation under Adminisration - Systemregistration. THANK YOU! *",
                null);
        log.warn(
                "****************************************************************************************************************************************************************************",
                null);
    }
    return regStatus;
}
 
Example 20
Source File: UpdateApplicationCommand.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected ServerStatus _doIt() {
	try {
		// get stack object
		Object stackId = JSONObject.NULL;
		if (stack != null) {
			GetStackByNameCommand getStackCommand = new GetStackByNameCommand(target, stack);
			ServerStatus getStackStatus = (ServerStatus) getStackCommand.doIt();
			if (!getStackStatus.isOK())
				return getStackStatus;
			if (getStackCommand.getStack() == null)
				return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, NLS.bind("Stack {0} not found", stack), null);
			stackId = getStackCommand.getStack().getGuid();
		}

		/* get application URL */
		URI targetURI = URIUtil.toURI(target.getUrl());
		URI appURI = targetURI.resolve(application.getAppJSON().getString(CFProtocolConstants.V2_KEY_URL));

		PutMethod updateApplicationMethod = new PutMethod(appURI.toString());
		ServerStatus confStatus = HttpUtil.configureHttpMethod(updateApplicationMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;

		updateApplicationMethod.setQueryString("async=true&inline-relations-depth=1"); //$NON-NLS-1$

		/* set request body */
		JSONObject updateAppRequest = new JSONObject();
		updateAppRequest.put(CFProtocolConstants.V2_KEY_NAME, appName);
		updateAppRequest.put(CFProtocolConstants.V2_KEY_INSTANCES, appInstances);
		updateAppRequest.put(CFProtocolConstants.V2_KEY_COMMAND, appCommand);
		updateAppRequest.put(CFProtocolConstants.V2_KEY_MEMORY, appMemory);
		updateAppRequest.put(CFProtocolConstants.V2_KEY_ENVIRONMENT_JSON, env != null ? env : new JSONObject());
		updateAppRequest.put(CFProtocolConstants.V2_KEY_BUILDPACK, buildPack != null ? buildPack : JSONObject.NULL);
		updateAppRequest.put(CFProtocolConstants.V2_KEY_STACK_GUID, stackId);

		updateApplicationMethod.setRequestEntity(new StringRequestEntity(updateAppRequest.toString(), "application/json", "utf-8")); //$NON-NLS-1$ //$NON-NLS-2$

		ServerStatus status = HttpUtil.executeMethod(updateApplicationMethod);
		if (!status.isOK())
			return status;
		GetAppCommand.expire(target, application.getName());
		return status;

	} catch (Exception e) {
		String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
		logger.error(msg, e);
		return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
	}
}