Java Code Examples for com.google.gwt.http.client.Response

The following are top voted examples for showing how to use com.google.gwt.http.client.Response. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: empiria.player   File: SynchronousScriptsLoaderTest.java   View source code 6 votes vote down vote up
@Test
public void shouldFireOnLoad_afterLastScriptLoaded() {
    // given
    ScriptUrl[] scripts = new ScriptUrl[]{firstScript, secondScript};
    Request request = mock(Request.class);
    Response response = mock(Response.class);
    when(response.getText()).thenReturn(RESPONSE_TEXT);

    // when
    testObj.injectScripts(scripts, synchronousScriptsCallback);
    verify(requestWrapper).get(eq(FIRST_SCRIPT_URL), requestCallbackCaptor.capture());
    RequestCallback requestCallback = requestCallbackCaptor.getValue();
    requestCallback.onResponseReceived(request, response);

    // then
    verify(scriptInjectorWrapper).fromString(RESPONSE_TEXT);

    verify(requestWrapper).get(SECOND_SCRIPT_URL, requestCallback);
    requestCallback.onResponseReceived(request, response);
    verify(synchronousScriptsCallback).onLoad();
}
 
Example 2
Project: sig-seguimiento-vehiculos   File: AbstractGitHubGetListRequest.java   View source code 6 votes vote down vote up
protected RestErrorCallback getErrorCallback() {
	return new RestErrorCallback() {

		@Override
		public boolean error(Request request, Throwable throwable) {
			autoMessageBox.hide();
			String message = "";
			int defaultCodeError = Response.SC_NOT_MODIFIED;
			try {
				throw throwable;
			} catch (ResponseException e) {
				Response response = e.getResponse();					
				message = response.getStatusText(); 
				defaultCodeError = response.getStatusCode();
				
			} catch (Throwable t) {
				message = t.getMessage();
			}
			
			messageDialogBuilder.createError(UIMessages.INSTANCE.warning() + " " + defaultCodeError, message).show();
			
			return false;
		}
	};
}
 
Example 3
Project: sig-seguimiento-vehiculos   File: GitHubGetRepositoryListRequest.java   View source code 6 votes vote down vote up
private RestErrorCallback getErrorCallback() {
	return new RestErrorCallback() {

		@Override
		public boolean error(Request request, Throwable throwable) {
			autoMessageBox.hide();
			String message = "";
			int defaultCodeError = Response.SC_NOT_MODIFIED;
			try {
				throw throwable;
			} catch (ResponseException e) {
				Response response = e.getResponse();					
				message = response.getStatusText(); 
				defaultCodeError = response.getStatusCode();
				
			} catch (Throwable t) {
				message = t.getMessage();
			}
			
			messageDialogBuilder.createError(UIMessages.INSTANCE.warning() + " " + defaultCodeError, message).show();
			
			return false;
		}
	};
}
 
Example 4
Project: sig-seguimiento-vehiculos   File: GitHubGetFileRequest.java   View source code 6 votes vote down vote up
private RestErrorCallback getErrorCallback() {
	return new RestErrorCallback() {

		@Override
		public boolean error(Request request, Throwable throwable) {
			autoMessageBox.hide();
			String message = "";
			int defaultCodeError = Response.SC_NOT_MODIFIED;
			try {
				throw throwable;
			} catch (ResponseException e) {
				Response response = e.getResponse();					
				message = response.getStatusText(); 
				defaultCodeError = response.getStatusCode();
				
			} catch (Throwable t) {
				message = t.getMessage();
			}
			
			messageDialogBuilder.createError(UIMessages.INSTANCE.warning() + " " + defaultCodeError, message).show();
			
			return false;
		}
	};
}
 
Example 5
Project: sig-seguimiento-vehiculos   File: GitHubUpdateFileExporter.java   View source code 6 votes vote down vote up
private RestErrorCallback getErrorCallback() {
	return new RestErrorCallback() {

		@Override
		public boolean error(Request request, Throwable throwable) {
			autoMessageBox.hide();
			String message = "";
			int defaultCodeError = Response.SC_NOT_MODIFIED;
			try {
				throw throwable;
			} catch (ResponseException e) {
				Response response = e.getResponse();					
				message = response.getStatusText(); 
				defaultCodeError = response.getStatusCode();
				
			} catch (Throwable t) {
				message = t.getMessage();
			}
			
			messageDialogBuilder.createError(UIMessages.INSTANCE.warning() + " " + defaultCodeError, message).show();
			
			return false;
		}
	};
}
 
Example 6
Project: sig-seguimiento-vehiculos   File: GitHubCreateFileExporter.java   View source code 6 votes vote down vote up
@Override
public void export(FileParameter fileParameter) {
	autoMessageBox = new ProgressBarDialog(false,
			UIMessages.INSTANCE.processing());
	autoMessageBox.show();

	final String fileName = fileParameter.getFileName() + "."
			+ fileParameter.getExtension();
	gitHubParameter = (GitHubParameter) fileParameter;
	final String userName = gitHubParameter.getUserName();
	final String password = gitHubParameter.getPassword();
	final String repository = gitHubParameter.getRepository();
	final String path = gitHubParameter.getPath();
	final String message = gitHubParameter.getMessageCommit();
	final String authorizationHeaderValue = BasicAuthenticationProvider
			.getAuthorizationHeaderValue(userName, password);
	final GitHubCreateFileRequest content = new GitHubCreateFileRequest();
	content.setContent(Base64.encode(fileParameter.getContent()));
	content.setMessage(message);
	RestClient.setJacksonMarshallingActive(true);
	RestClient.create(GitHubFileService.class, URL_BASE,
			getRemoteCallback(), getErrorCallback(), Response.SC_CREATED)
			.createFile(userName, repository, path, fileName,
					authorizationHeaderValue, content);
}
 
Example 7
Project: LAS   File: ColumnEditorWidget.java   View source code 6 votes vote down vote up
@Override
public void onResponseReceived(Request request, Response response) {
    String text = response.getText();
    PopupPanel popup = new PopupPanel(true);
    popup.add(new HTML("<strong>Saved edits for:<p></p></strong>"+text+"<p></p>Click outside box to dismiss."));
    popup.setPopupPosition(200, Window.getClientHeight()/3);
    popup.show();
    CellFormatter formatter = datatable.getCellFormatter();
    for (Iterator dirtyIt = dirtyrows.keySet().iterator(); dirtyIt.hasNext();) {
        Integer widgetrow = (Integer) dirtyIt.next();
        for (int i = 0; i < headers.length; i++) {
            formatter.removeStyleName(widgetrow, i, "dirty");
        }
        
        CheckBox box = (CheckBox) datatable.getWidget(widgetrow, 0);
        box.setValue(false);
    }
    dirtyrows.clear();
}
 
Example 8
Project: gwt-jackson-rest   File: RestRequestCallback.java   View source code 6 votes vote down vote up
@Override
public void onResponseReceived(Request request, Response response) {
    if (isSuccessStatusCode(response)) {
        if (null != callback) {
            R result;
            if (null != responseConverter && null != response.getText() && !response.getText().isEmpty()) {
                try {
                    result = responseConverter.read(response.getText());
                } catch (Exception e) {
                    onError(request, e);
                    return;
                }
            } else {
                result = null;
            }
            callback.onSuccess(response, result);
        }
    } else {
        if (null != callback) {
            callback.onError(response);
        } else {
            throw new RestException("An error occured. Status : " + response.getStatusCode());
        }
    }
}
 
Example 9
Project: scheduling-portal   File: JobsController.java   View source code 6 votes vote down vote up
/**
 * Fetch jobs state revision. If revision is more recent, fetch jobs.
 */
public void jobsStateRevision() {
    SchedulerServiceAsync scheduler = Scheduler.getSchedulerService();
    scheduler.schedulerStateRevision(LoginModel.getInstance().getSessionId(), new AsyncCallback<Long>() {

        public void onFailure(Throwable caught) {
            if (!LoginModel.getInstance().isLoggedIn()) {
                // might have been disconnected in between
                return;
            }
            if (JSONUtils.getJsonErrorCode(caught) == Response.SC_UNAUTHORIZED) {
                parentController.getParentController().teardown("You have been disconnected from the server.");
            }
            LogModel.getInstance().logCriticalMessage("Failed to get Scheduler Revision: " +
                                                      JSONUtils.getJsonErrorMessage(caught));
        }

        public void onSuccess(Long result) {
            fetchJobs(false);
        }
    });
}
 
Example 10
Project: che   File: MachineAsyncRequestFactory.java   View source code 6 votes vote down vote up
private Promise<String> requestCsrfToken() {
  if (csrfToken != null) {
    return Promises.resolve(csrfToken);
  }
  return createGetRequest(appContext.getMasterApiEndpoint() + "/profile")
      .header(CSRF_TOKEN_HEADER_NAME, "Fetch")
      .send(
          new Unmarshallable<String>() {
            @Override
            public void unmarshal(Response response) throws UnmarshallerException {
              csrfToken = response.getHeader(CSRF_TOKEN_HEADER_NAME);
              if (csrfToken != null) {
                appContext.getProperties().put(CSRF_TOKEN_HEADER_NAME, csrfToken);
              }
            }

            @Override
            public String getPayload() {
              return csrfToken;
            }
          });
}
 
Example 11
Project: che   File: AsyncRequestCallback.java   View source code 6 votes vote down vote up
/**
 * @see
 *     com.google.gwt.http.client.RequestCallback#onResponseReceived(com.google.gwt.http.client.Request,
 *     com.google.gwt.http.client.Response)
 */
@Override
public final void onResponseReceived(Request request, Response response) {
  if (loader != null) {
    loader.hide();
  }

  // If there is no connection to the server then status equals 0 ( In Internet Explorer status is
  // 12029 )
  if (response.getStatusCode() == 0 || response.getStatusCode() == 12029) {
    onServerDisconnected();
    return;
  }

  if (response.getStatusCode() == HTTPStatus.UNAUTHORIZED) {
    onUnauthorized(response);
    return;
  }

  if (isSuccessful(response)) {
    handleSuccess(response);
  } else {
    handleFailure(response);
  }
}
 
Example 12
Project: che   File: AsyncRequestCallback.java   View source code 6 votes vote down vote up
private String generateErrorMessage(Response response) {
  StringBuilder message = new StringBuilder();
  String protocol = Window.Location.getProtocol();
  String host = Window.Location.getHost();
  String url = this.request.getRequestBuilder().getUrl();

  // deletes query params
  url = url.substring(0, url.indexOf('?'));

  message
      .append(response.getStatusCode())
      .append(" ")
      .append(response.getStatusText())
      .append(" ")
      .append(protocol)
      .append("//")
      .append(host)
      .append(url);

  return message.toString();
}
 
Example 13
Project: che   File: AsyncRequestCallback.java   View source code 6 votes vote down vote up
protected final boolean isSuccessful(Response response) {
  if (successCodes == null) {
    successCodes = DEFAULT_SUCCESS_CODES;
  }

  if ("Authentication-required".equals(response.getHeader(HTTPHeader.JAXRS_BODY_PROVIDED))) {
    return false;
  }

  for (int code : successCodes) {
    if (response.getStatusCode() == code) {
      return true;
    }
  }
  return false;
}
 
Example 14
Project: onecmdb   File: MDRStartWidget.java   View source code 6 votes vote down vote up
public void doStop() {
 for (TabItem item : advanced.getItems()) {
	 final CIModel model = (CIModel)item.getData("model");

	 // Do a HTTP request..
	 RequestBuilder req = new RequestBuilder(RequestBuilder.GET, getStopURL(model));

	 try {
		 Info.display("Stop", "Send stop to " + model.getDisplayName());
		 req.sendRequest(null, new RequestCallback() {

			 public void onResponseReceived(Request request, Response response) {
				 Info.display("Stop", "COMPLETED. Stop sent to " + model.getDisplayName());
			 }

			 public void onError(Request arg0, Throwable arg1) {
				 Info.display("Stop", "FAILED. to stop " + model.getDisplayName());
			 }
		 });

	 } catch (RequestException e) {
		 Info.display("Stop", "ERROR. to stop " + model.getDisplayName());
	 } 
 }
}
 
Example 15
Project: geowe-core   File: AbstractGitHubGetListRequest.java   View source code 6 votes vote down vote up
protected RestErrorCallback getErrorCallback() {
	return new RestErrorCallback() {

		@Override
		public boolean error(Request request, Throwable throwable) {
			autoMessageBox.hide();
			String message = "";
			int defaultCodeError = Response.SC_NOT_MODIFIED;
			try {
				throw throwable;
			} catch (ResponseException e) {
				Response response = e.getResponse();					
				message = response.getStatusText(); 
				defaultCodeError = response.getStatusCode();
				
			} catch (Throwable t) {
				message = t.getMessage();
			}
			
			messageDialogBuilder.createError(UIMessages.INSTANCE.warning() + " " + defaultCodeError, message).show();
			
			return false;
		}
	};
}
 
Example 16
Project: geowe-core   File: GitHubGetRepositoryListRequest.java   View source code 6 votes vote down vote up
private RestErrorCallback getErrorCallback() {
	return new RestErrorCallback() {

		@Override
		public boolean error(Request request, Throwable throwable) {
			autoMessageBox.hide();
			String message = "";
			int defaultCodeError = Response.SC_NOT_MODIFIED;
			try {
				throw throwable;
			} catch (ResponseException e) {
				Response response = e.getResponse();					
				message = response.getStatusText(); 
				defaultCodeError = response.getStatusCode();
				
			} catch (Throwable t) {
				message = t.getMessage();
			}
			
			messageDialogBuilder.createError(UIMessages.INSTANCE.warning() + " " + defaultCodeError, message).show();
			
			return false;
		}
	};
}
 
Example 17
Project: geowe-core   File: GitHubGetFileRequest.java   View source code 6 votes vote down vote up
private RestErrorCallback getErrorCallback() {
	return new RestErrorCallback() {

		@Override
		public boolean error(Request request, Throwable throwable) {
			autoMessageBox.hide();
			String message = "";
			int defaultCodeError = Response.SC_NOT_MODIFIED;
			try {
				throw throwable;
			} catch (ResponseException e) {
				Response response = e.getResponse();					
				message = response.getStatusText(); 
				defaultCodeError = response.getStatusCode();
				
			} catch (Throwable t) {
				message = t.getMessage();
			}
			
			messageDialogBuilder.createError(UIMessages.INSTANCE.warning() + " " + defaultCodeError, message).show();
			
			return false;
		}
	};
}
 
Example 18
Project: geowe-core   File: GitHubUpdateFileExporter.java   View source code 6 votes vote down vote up
private RestErrorCallback getErrorCallback() {
	return new RestErrorCallback() {

		@Override
		public boolean error(Request request, Throwable throwable) {
			autoMessageBox.hide();
			String message = "";
			int defaultCodeError = Response.SC_NOT_MODIFIED;
			try {
				throw throwable;
			} catch (ResponseException e) {
				Response response = e.getResponse();					
				message = response.getStatusText(); 
				defaultCodeError = response.getStatusCode();
				
			} catch (Throwable t) {
				message = t.getMessage();
			}
			
			messageDialogBuilder.createError(UIMessages.INSTANCE.warning() + " " + defaultCodeError, message).show();
			
			return false;
		}
	};
}
 
Example 19
Project: geowe-core   File: GitHubCreateFileExporter.java   View source code 6 votes vote down vote up
@Override
public void export(FileParameter fileParameter) {
	autoMessageBox = new ProgressBarDialog(false,
			UIMessages.INSTANCE.processing());
	autoMessageBox.show();

	final String fileName = fileParameter.getFileName() + "."
			+ fileParameter.getExtension();
	gitHubParameter = (GitHubParameter) fileParameter;
	final String userName = gitHubParameter.getUserName();
	final String password = gitHubParameter.getPassword();
	final String repository = gitHubParameter.getRepository();
	final String path = gitHubParameter.getPath();
	final String message = gitHubParameter.getMessageCommit();
	final String authorizationHeaderValue = BasicAuthenticationProvider
			.getAuthorizationHeaderValue(userName, password);
	final GitHubCreateFileRequest content = new GitHubCreateFileRequest();
	content.setContent(Base64.encode(fileParameter.getContent()));
	content.setMessage(message);
	RestClient.setJacksonMarshallingActive(true);
	RestClient.create(GitHubFileService.class, URL_BASE,
			getRemoteCallback(), getErrorCallback(), Response.SC_CREATED)
			.createFile(userName, repository, path, fileName,
					authorizationHeaderValue, content);
}
 
Example 20
Project: firefly   File: HtmlRegionLoader.java   View source code 6 votes vote down vote up
public void load(String url, final String regionName) {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
    try {
        builder.sendRequest(null, new RequestCallback(){
            public void onResponseReceived(com.google.gwt.http.client.Request req, Response res) {
                updateHtml(res.getText(), regionName);
            }

            public void onError(com.google.gwt.http.client.Request request, Throwable exception) {
            }
        });
    } catch (RequestException e) {
        e.printStackTrace();
    }

}
 
Example 21
Project: gerrit   File: RestApi.java   View source code 6 votes vote down vote up
/** Is the Gerrit Code Review server likely to return this status? */
public static boolean isExpected(int statusCode) {
  switch (statusCode) {
    case SC_UNAVAILABLE:
    case Response.SC_BAD_REQUEST:
    case Response.SC_UNAUTHORIZED:
    case Response.SC_FORBIDDEN:
    case Response.SC_NOT_FOUND:
    case Response.SC_METHOD_NOT_ALLOWED:
    case Response.SC_CONFLICT:
    case Response.SC_PRECONDITION_FAILED:
    case 422: // Unprocessable Entity
    case 429: // Too Many Requests (RFC 6585)
      return true;

    default:
      // Assume any other code is not expected. These may be
      // local proxy server errors outside of our control.
      return false;
  }
}
 
Example 22
Project: platypus-js   File: AppClient.java   View source code 6 votes vote down vote up
public XMLHttpRequest2 syncRequest(String aUrl, ResponseType aResponseType) throws Exception {
	final XMLHttpRequest2 req = syncRequest(aUrl, aResponseType, null, RequestBuilder.GET);
	if (req.getStatus() == Response.SC_OK)
		return req;
	else
		throw new Exception(req.getStatus() + " " + req.getStatusText());
}
 
Example 23
Project: platypus-js   File: AppClient.java   View source code 6 votes vote down vote up
public XMLHttpRequest2 syncRequest(String aUrl, ResponseType aResponseType, String aBody, RequestBuilder.Method aMethod) throws Exception {
	final XMLHttpRequest2 req = XMLHttpRequest.create().<XMLHttpRequest2> cast();
	aUrl = Loader.URL_QUERY_PROCESSOR.process(aUrl);
	req.open(aMethod.toString(), aUrl, false);
	interceptRequest(req);
	/*
	 * Since W3C standard about sync XmlHttpRequest and response type. if
	 * (aResponseType != null && aResponseType != ResponseType.Default)
	 * req.setResponseType(aResponseType);
	 */
	req.setRequestHeader("Pragma", "no-cache");
	if (aBody != null)
		req.send(aBody);
	else
		req.send();
	if (req.getStatus() == Response.SC_OK)
		return req;
	else
		throw new Exception(req.getStatus() + " " + req.getStatusText());
}
 
Example 24
Project: gwt-angular   File: GwtHtmlResource.java   View source code 6 votes vote down vote up
@Override
public void link(final NGScope scope, final JQElement element, JSON attrs) {
    HtmlResource resource = scope.get(getName());
    if (resource == null) {
        LOG.log(Level.WARNING, "Mandatory attribute " + getName() + " value is mssing");
        return;
    }
    String url = resource.getSafeUri().asString();
    Promise<Response> promise = HttpUtils.get(q, url);
    promise.then(new Done<Response>() {
        @Override
        public void call(Response value) {
            String text = value.getText();
            element.append(text);
        }
    }).then(new Fail() {
        @Override
        public void call(Throwable cause) {
            LOG.log(Level.WARNING, "Failed to insert HtmlResource", cause);
        }
    });
    return;
}
 
Example 25
Project: gwt-angular   File: GwtDataResource.java   View source code 6 votes vote down vote up
@Override
public void link(final NGScope scope, final JQElement element, JSON attrs) {
    DataResource resource = scope.get(getName());
    if (resource == null) {
        LOG.log(Level.WARNING, "Mandatory attribute " + getName() + " value is mssing");
        return;
    }
    SafeUri safeUri = resource.getSafeUri();
    String url = safeUri.asString();
    Promise<Response> promise = HttpUtils.get(q, url);
    promise.then(new Done<Response>() {
        @Override
        public void call(Response value) {
            String text = value.getText();
            element.append(text);
        }
    });
    return;
}
 
Example 26
Project: errai-polymer   File: ComplaintForm.java   View source code 6 votes vote down vote up
@EventHandler("submit")
	private void onSubmit(ClickEvent e) {
		endpoint.call(new ResponseCallback() {
			@Override
			public void callback(Response response) {
				log.info("Back From Submiting UserComplaint. Response is : " + response.getStatusCode());
				if (response.getStatusCode() == Response.SC_CREATED) {
					review.toggle();
				}
			}
		}).create(userComplaint);
		
		log.info("Submiting UserComplaint : " + userComplaint);
//		log.info("Priority : " + radioGrp.getValue());
		
	}
 
Example 27
Project: OneCMDBwithMaven   File: MDRStartWidget.java   View source code 6 votes vote down vote up
public void doStop() {
 for (TabItem item : advanced.getItems()) {
	 final CIModel model = (CIModel)item.getData("model");

	 // Do a HTTP request..
	 RequestBuilder req = new RequestBuilder(RequestBuilder.GET, getStopURL(model));

	 try {
		 Info.display("Stop", "Send stop to " + model.getDisplayName());
		 req.sendRequest(null, new RequestCallback() {

			 public void onResponseReceived(Request request, Response response) {
				 Info.display("Stop", "COMPLETED. Stop sent to " + model.getDisplayName());
			 }

			 public void onError(Request arg0, Throwable arg1) {
				 Info.display("Stop", "FAILED. to stop " + model.getDisplayName());
			 }
		 });

	 } catch (RequestException e) {
		 Info.display("Stop", "ERROR. to stop " + model.getDisplayName());
	 } 
 }
}
 
Example 28
Project: sigmah   File: AbstractServlet.java   View source code 6 votes vote down vote up
/**
 * Returns the given {@code paramKey} corresponding value from the {@code request}.
 * 
 * @param request
 *          The HTTP request.
 * @param paramKey
 *          The {@link RequestParameter} key.
 * @param acceptNull
 *          {@code true} to accept a {@code null} value result, {@code false} to throw a
 *          {@link StatusServletException} if the value is {@code null}.
 * @return The given {@code paramKey} corresponding value from the {@code request}.
 * @throws StatusServletException
 *           If the parameter value is {@code null} <b>and</b> {@code acceptNull} is set to {@code false}.
 */
protected static final String getParameter(final HttpServletRequest request, final RequestParameter paramKey, boolean acceptNull)
		throws StatusServletException {

	final String value = ClientUtils.deletePreTags(request.getParameter(paramKey.getRequestName()));

	if (StringUtils.isBlank(value) || "null".equals(value)) {

		if (acceptNull) {
			return null;
		}

		if (LOG.isWarnEnabled()) {
			LOG.warn("No value for parameter key '{}'.", paramKey);
		}

		throw new StatusServletException(Response.SC_BAD_REQUEST);
	}

	return value;
}
 
Example 29
Project: sigmah   File: AbstractServlet.java   View source code 6 votes vote down vote up
/**
 * Returns the given {@code paramKey} corresponding {@link Integer} value from the {@code request}.
 * 
 * @param request
 *          The HTTP request.
 * @param paramKey
 *          The {@link RequestParameter} key.
 * @param acceptNull
 *          {@code true} to accept a {@code null} value result, {@code false} to throw a
 *          {@link StatusServletException} if the value is {@code null}.
 * @return The given {@code paramKey} corresponding {@link Integer} value from the {@code request}.
 * @throws StatusServletException
 *           If the parameter value is {@code null} <b>and</b> {@code acceptNull} is set to {@code false}.
 */
protected static final Integer getIntegerParameter(final HttpServletRequest request, final RequestParameter paramKey, boolean acceptNull)
		throws StatusServletException {

	final String intValue = getParameter(request, paramKey, acceptNull);

	if (StringUtils.isBlank(intValue)) {
		if (acceptNull) {
			return null;
		}
		throw new StatusServletException(Response.SC_BAD_REQUEST);
	}

	try {

		return Integer.parseInt(intValue);

	} catch (final NumberFormatException e) {
		LOG.error("Error while parsing the integer parameter '" + intValue + "'.", e);
		throw new StatusServletException(Response.SC_BAD_REQUEST);
	}
}
 
Example 30
Project: sigmah   File: AbstractServlet.java   View source code 6 votes vote down vote up
/**
 * Returns the given {@code paramKey} corresponding {@link Boolean} value from the {@code request}.
 * 
 * @param request
 *          The HTTP request.
 * @param paramKey
 *          The {@link RequestParameter} key.
 * @param acceptNull
 *          {@code true} to accept a {@code null} value result, {@code false} to throw a
 *          {@link StatusServletException} if the value is {@code null}.
 * @return The given {@code paramKey} corresponding {@link Boolean} value from the {@code request}.
 * @throws StatusServletException
 *           If the parameter value is {@code null} <b>and</b> {@code acceptNull} is set to {@code false}.
 */
protected static final Boolean getBooleanParameter(final HttpServletRequest request, final RequestParameter paramKey, boolean acceptNull)
		throws StatusServletException {

	final String booleanValue = getParameter(request, paramKey, acceptNull);

	if (StringUtils.isBlank(booleanValue)) {
		if (acceptNull) {
			return null;
		}
		throw new StatusServletException(Response.SC_BAD_REQUEST);
	}

	try {

		return Boolean.parseBoolean(booleanValue);

	} catch (final NumberFormatException e) {
		throw new StatusServletException(Response.SC_BAD_REQUEST);
	}
}
 
Example 31
Project: sigmah   File: FileServlet.java   View source code 6 votes vote down vote up
/**
 * See {@link ServletMethod#DOWNLOAD_LOGO} for JavaDoc.
 * 
 * @param request
 *          The HTTP request containing the file id parameter.
 * @param response
 *          The HTTP response on which the file content is written.
 * @param context
 *          The execution context.
 * @throws Exception
 *           If an error occurs during process.
 */
protected void downloadLogo(final HttpServletRequest request, final HttpServletResponse response, final ServletExecutionContext context) throws Exception {

	// Retrieves the file id.
	final String id = getParameter(request, RequestParameter.ID, false);

	if (LOG.isDebugEnabled()) {
		LOG.debug("Downloads logo with id '{}'.", id);
	}

	try {

		downloadBase64(id, fileStorageProvider.open(id), response);

	} catch (final NoSuchFileException e) {
		if (LOG.isInfoEnabled()) {
			LOG.info("No logo found for id '" + id + "'.", e);
		}
		throw new StatusServletException(Response.SC_NOT_FOUND, e);
	}
}
 
Example 32
Project: sigmah   File: FileServlet.java   View source code 6 votes vote down vote up
/**
 * See {@link ServletMethod#DOWNLOAD_ARCHIVE} for JavaDoc.
 * 
 * @param request
 *          The HTTP request containing the file id parameter.
 * @param response
 *          The HTTP response on which the file content is written.
 * @param context
 *          The execution context.
 * @throws Exception
 *           If an error occurs during process.
 */
protected void downloadArchive(final HttpServletRequest request, final HttpServletResponse response, final ServletExecutionContext context) throws Exception {

	// Retrieves the file id.
	final String id = getParameter(request, RequestParameter.ID, false);

	if (LOG.isDebugEnabled()) {
		LOG.debug("Downloads archive with id '{}'.", id);
	}

	try {

		download(id, backupArchiveManager.open(id), response);

	} catch (final NoSuchFileException e) {
		if (LOG.isInfoEnabled()) {
			LOG.info("No archive found for id '" + id + "'.", e);
		}
		throw new StatusServletException(Response.SC_NOT_FOUND, e);
	}
}
 
Example 33
Project: sigmah   File: FileServlet.java   View source code 6 votes vote down vote up
protected void uploadAvatar(final HttpServletRequest request, final HttpServletResponse response, final ServletExecutionContext context) throws Exception {
	final int contentLength = request.getContentLength();

	if (contentLength == 0) {
		LOG.error("Empty file.");
		throw new StatusServletException(Response.SC_NO_CONTENT);
	}

	if (contentLength > FileUploadUtils.MAX_UPLOAD_FILE_SIZE) {
		LOG.error("File's size is too big to be uploaded (size: {}, maximum : {}).", contentLength, FileUploadUtils.MAX_UPLOAD_FILE_SIZE);
		throw new StatusServletException(Response.SC_REQUEST_ENTITY_TOO_LARGE);
	}

	final String fileName = generateUniqueName();

	// --
	// Writing the file.
	// --

	final MultipartRequest multipartRequest = new MultipartRequest(request);
	processUpload(multipartRequest, response, fileName, false, FileUploadUtils.MAX_AVATAR_SIZE);

	response.setStatus(Response.SC_OK);
	response.setContentType(FileType.TXT.getContentType());
	response.getWriter().write(fileName);
}
 
Example 34
Project: sigmah   File: MultipartRequest.java   View source code 6 votes vote down vote up
public void parse(MultipartRequestCallback callback) throws IOException, FileUploadException, StatusServletException {
	if (!ServletFileUpload.isMultipartContent(request)) {
		LOGGER.error("Request content is not multipart.");
		throw new StatusServletException(Response.SC_PRECONDITION_FAILED);
	}
	
	final FileItemIterator iterator = new ServletFileUpload(new DiskFileItemFactory()).getItemIterator(request);
	while (iterator.hasNext()) {
		// Gets the first HTTP request element.
		final FileItemStream item = iterator.next();

		if (item.isFormField()) {
			final String value = Streams.asString(item.openStream(), "UTF-8");
			properties.put(item.getFieldName(), value);
			
		} else if(callback != null) {
			callback.onInputStream(item.openStream(), item.getFieldName(), item.getContentType());
		}
	}
}
 
Example 35
Project: ineform   File: RestDataConnectorComplexTest.java   View source code 6 votes vote down vote up
private void prepareRequestBuilder(
    RequestBuilder requestBuilder,
    String responseText,
    int statusCode) throws Exception {
    final Response response = mock(Response.class);
    when(response.getStatusCode()).thenReturn(statusCode);
    when(response.getText()).thenReturn(responseText);

    when(requestBuilder.sendRequest(anyString(), any(RequestCallback.class)))
        .thenAnswer(new Answer<Request>() {

            @Override
            public Request answer(InvocationOnMock invocation) throws Throwable {
                ((RequestCallback) invocation.getArguments()[1])
                    .onResponseReceived(null, response);
                return null;
            }
        });
}
 
Example 36
Project: preferanser   File: ErrorHandlingRestyGwtRequestListener.java   View source code 6 votes vote down vote up
@Override public void afterClientErrorHandled(Method method, Request request, Response response) {
    String errorMessage;
    switch (response.getStatusCode()) {
        case 0:
            return; // Ignore
        case 401: // Unauthorized
            placeManager.revealDefaultPlace();
            errorMessage = "Для просмотра данной страницы необходимо войти в систему.";
            break;
        case 404: // Not found
            errorMessage = "Объект не найден.";
            break;
        default:
            errorMessage = "HTTP response error: " + response.getText();
            Window.alert("Обработка запроса завершилась ошибкой. " +
                "Подробная информация об ошибке доступна в консоли браузера. " +
                "Пожалуйста, обновите текущую страницу или начните с главной.");
    }

    log.severe(errorMessage);
}
 
Example 37
Project: geomajas-project-client-gwt2   File: AbstractWfsServiceTest.java   View source code 6 votes vote down vote up
protected void prepareResponse(String resource) throws Exception {
	capabilitiesXml = IOUtils.toString(this.getClass().getResourceAsStream(resource), "UTF-8");
	DOMParser parser = new DOMParser();
	parser.parse(new InputSource(new StringReader(capabilitiesXml)));
	capabilitiesDoc = w3cToGoogle(parser.getDocument());
	final Response response = mock(Response.class);
	when(response.getStatusCode()).thenReturn(200);
	when(response.getText()).thenReturn(capabilitiesXml);

	when(requestBuilder.sendRequest(anyString(), any(RequestCallback.class))).thenAnswer(new Answer<Request>() {

		@Override
		public Request answer(InvocationOnMock invocation) throws Throwable {
			((RequestCallback) invocation.getArguments()[1]).onResponseReceived(null, response);
			return null;
		}
	});
}
 
Example 38
Project: geomajas-project-client-gwt2   File: AbstractWmsServiceTest.java   View source code 6 votes vote down vote up
protected void prepareResponse(String resource) throws Exception {
	capabilitiesXml = IOUtils.toString(this.getClass().getResourceAsStream(resource), "UTF-8");
	DOMParser parser = new DOMParser();
	parser.parse(new InputSource(new StringReader(capabilitiesXml)));
	capabilitiesDoc = w3cToGoogle(parser.getDocument());
	final Response response = mock(Response.class);
	when(response.getStatusCode()).thenReturn(200);
	when(response.getText()).thenReturn(capabilitiesXml);

	when(requestBuilder.sendRequest(anyString(), any(RequestCallback.class))).thenAnswer(new Answer<Request>() {

		@Override
		public Request answer(InvocationOnMock invocation) throws Throwable {
			((RequestCallback) invocation.getArguments()[1]).onResponseReceived(null, response);
			return null;
		}
	});
}
 
Example 39
Project: droopy   File: Main.java   View source code 6 votes vote down vote up
public final void onResponseReceived(final Request request, final Response response) {
  final String text = response.getText();
  if (text.isEmpty()) {
    final int code = response.getStatusCode();
    final String errmsg;
    if (code == 0) {  // Happens when a cross-domain request fails to connect.
      errmsg = ("Failed to connect to " + server + ", check that the server"
                + " is up and that you can connect to it.");
    } else {
      errmsg = ("Empty response from server: code=" + code
                + " status=" + response.getStatusText());
    }
    onError(request, new RuntimeException(errmsg));
  } else {
    JSONValue value;
    try {
      value = JSONParser.parseStrict(text);
    } catch (JSONException e) {
      onError(request, e);
      return;
    }
    onSuccess(value);
  }
}
 
Example 40
Project: gwt-upload   File: Uploader.java   View source code 6 votes vote down vote up
public void onResponseReceived(Request request, Response response) {
  hasSession = true;
  try {
    String s = Utils.getXmlNodeValue(XMLParser.parse(response.getText()), TAG_BLOBSTORE);
    blobstore = "true".equalsIgnoreCase(s);
    // with blobstore status does not make sense
    if (blobstore) {
      updateStatusTimer.setInterval(5000);
    }
    uploadForm.submit();
  } catch (Exception e) {
    String message = e.getMessage().contains("error:") 
        ? i18nStrs.uploaderServerUnavailable() + " (3) " + getServletPath() + "\n\n" + i18nStrs.uploaderServerError() + "\nAction: " + getServletPath() + "\nException: " + e.getMessage() + response.getText()
        : i18nStrs.submitError();
    cancelUpload( message);
  }
}