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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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);
  }
}
 
Example 41
Project: sig-seguimiento-vehiculos   File: GitHubGetFileListRequest.java   Source Code and License 5 votes vote down vote up
public void send(String userName, String repository, String path) {
	autoMessageBox = new ProgressBarDialog(false,
			UIMessages.INSTANCE.processing());
	autoMessageBox.show();		
			
	RestClient.setJacksonMarshallingActive(true);
	RestClient.create(GitHubFileListService.class, URL_BASE + "repos/", getRemoteCallback(),
			getErrorCallback(), Response.SC_OK).getFileList(userName, repository, path);
}
 
Example 42
Project: sig-seguimiento-vehiculos   File: GitHubGetRepositoryListRequest.java   Source Code and License 5 votes vote down vote up
public void send(String userName) {
	autoMessageBox = new ProgressBarDialog(false,
			UIMessages.INSTANCE.processing());
	autoMessageBox.show();		
			
	RestClient.setJacksonMarshallingActive(true);
	RestClient.create(GitHubRepositoryService.class, URL_BASE, getRemoteCallback(),
			getErrorCallback(), Response.SC_OK).getRepositories(userName);
}
 
Example 43
Project: sig-seguimiento-vehiculos   File: GitHubGetFileRequest.java   Source Code and License 5 votes vote down vote up
public void send(GitHubParameter gitHubParameter) {
	autoMessageBox = new ProgressBarDialog(false,
			UIMessages.INSTANCE.processing());
	autoMessageBox.show();		
	final String fileName = gitHubParameter.getFileName() + "."
			+ gitHubParameter.getExtension();		
	final String userName = gitHubParameter.getUserName();		
	final String repository = gitHubParameter.getRepository();
	final String path = gitHubParameter.getPath();
			
	RestClient.setJacksonMarshallingActive(true);
	RestClient.create(GitHubFileService.class, URL_BASE, getRemoteCallback(),
			getErrorCallback(), Response.SC_OK).getFile(userName,
			repository, path, fileName);
}
 
Example 44
Project: sig-seguimiento-vehiculos   File: JoinDataTool.java   Source Code and License 5 votes vote down vote up
private void lodaDataFromURL(final String url) {
	final String urlBase = GWT.getHostPageBaseURL() + "gwtOpenLayersProxy";
	try {
		autoMessageBox.show();
		RestClient.create(URLFileRestService.class, urlBase,
				new RemoteCallback<String>() {
					@Override
					public void callback(String response) {
						parseCsvData(response);
						autoMessageBox.hide();
					}
				}, new RestErrorCallback() {
					@Override
					public boolean error(Request message,
							Throwable throwable) {
						autoMessageBox.hide();

						showAlert("Error"
								+ UIMessages.INSTANCE.unexpectedError());
						return false;
					}
				}, Response.SC_OK).getContent(url);
	} catch (Exception e) {
		autoMessageBox.hide();
		showAlert("Error loading data..." + e.getMessage());
	}
}
 
Example 45
Project: sig-seguimiento-vehiculos   File: URLVectorLayerDef.java   Source Code and License 5 votes vote down vote up
protected void createLayerFromURL() {
	final ProgressBarDialog autoMessageBox = new ProgressBarDialog(false,
			UIMessages.INSTANCE.processing());
	try {
		autoMessageBox.show();
		RestClient.create(URLFileRestService.class, URL_BASE,
				new RemoteCallback<String>() {
					@Override
					public void callback(String response) {
						final VectorLayerConfig layerConfig = getVectorLayerConfig();
						layerConfig.setGeoDataString(response);
						VectorLayer layer = VectorLayerFactory
								.createVectorLayerFromGeoData(layerConfig);
						LayerLoader.load(layer);
						autoMessageBox.hide();
					}
				}, new RestErrorCallback() {
					@Override
					public boolean error(Request message,
							Throwable throwable) {
						autoMessageBox.hide();

						showDialog("Error",
								UIMessages.INSTANCE.unexpectedError());
						return false;
					}
				}, Response.SC_OK).getContent(getUrl());
	} catch (Exception e) {
		autoMessageBox.hide();
		showDialog(
				UIMessages.INSTANCE.errorLoadingLayer(getVectorLayerConfig()
						.getLayerName()),
				UIMessages.INSTANCE.unexpectedError());
	}
}
 
Example 46
Project: sig-seguimiento-vehiculos   File: RouteVehicleTool.java   Source Code and License 5 votes vote down vote up
private void getRequestRegisteredPoint(final VehicleJSO vehicle, final String startDate, final String endDate) {
	autoMessageBox.setProgressStatusMessage(UISgfMessages.INSTANCE.getGPSData());
	
	RestClient.create(SGFRegisteredPointService.class, SGFServiceInfo.getURL(),
			new RemoteCallback<String>() {

				@Override
				public void callback(String pointRegisterListResponseJson) {	
					
					
					PointRegisterListResponseJSO pointRegisterResponse = JsonUtils
							.safeEval(pointRegisterListResponseJson);
					PointRegisterJSO[] pointRegisters = pointRegisterResponse
							.getPointRegisterListEmbededJSO().getPointRegister();
					List<PointRegisterJSO> points = Arrays.asList(pointRegisters);
					
					if(points.isEmpty()) {
						messageDialogBuilder.createInfo(UIMessages.INSTANCE.edtAlertDialogTitle(),  UISgfMessages.INSTANCE.gpsDataNotFound()).show();
						return;
					}
					
					createRouteLayer(vehicle, startDate, points);
					autoMessageBox.hide();

				}
			},

			new RestErrorCallback() {
				
				@Override
				public boolean error(Request message, Throwable throwable) {
					autoMessageBox.hide();
					messageDialogBuilder.createInfo(UISgfMessages.INSTANCE.errorDetected(),  throwable.getMessage()).show();
					
					return false;
				}
			}, Response.SC_OK).getRegisteredPoints(session.getToken(), vehicle.getId(), startDate, endDate, REGISTERED_POINTS_TO_LOAD, "date,desc");			
}
 
Example 47
Project: sig-seguimiento-vehiculos   File: VehicleTool.java   Source Code and License 5 votes vote down vote up
private void loadVehicles(String token, int companyId) {
	autoMessageBox = new ProgressBarDialog(false,
			UIMessages.INSTANCE.processing());
	autoMessageBox.show();

	RestClient.create(SGFVehicleService.class, SGFServiceInfo.getURL(),
			new RemoteCallback<String>() {

				@Override
				public void callback(String vehicleListResponseJson) {
					VehicleListResponseJSO vehicleListResponse = JsonUtils
							.safeEval(vehicleListResponseJson);
					List<VehicleJSO> vehicles = Arrays
							.asList(vehicleListResponse
									.getVehicleListEmbededJSO()
									.getVehicles());

					vehicleDialog.setVehicle(vehicles);
					autoMessageBox.hide();
					vehicleDialog.show();

				}
			},

			new RestErrorCallback() {

				@Override
				public boolean error(Request message, Throwable throwable) {
					autoMessageBox.hide();
					messageDialogBuilder.createInfo(
							UISgfMessages.INSTANCE.errorDetected(),
							throwable.getMessage()).show();

					return false;
				}
			}, Response.SC_OK).get(token, companyId, 100, "id");
}
 
Example 48
Project: sig-seguimiento-vehiculos   File: GitHubUpdateFileExporter.java   Source Code and License 5 votes vote down vote up
private void send() {
	autoMessageBox = new ProgressBarDialog(false,
			UIMessages.INSTANCE.processing());
	autoMessageBox.show();
	final String fileName = gitHubParameter.getFileName() + "."
			+ gitHubParameter.getExtension();		
	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 GitHubUpdateFileRequest content = new GitHubUpdateFileRequest();
	content.setContent(Base64.encode(gitHubParameter.getContent()));
	content.setMessage(message);
	if (gitHubParameter.getSha() != null
			&& !gitHubParameter.getSha().isEmpty()) {
		content.setSha(gitHubParameter.getSha());

		RestClient.setJacksonMarshallingActive(true);
		RestClient.create(GitHubFileService.class, URL_BASE,
				getRemoteCallback(), getErrorCallback(), Response.SC_OK)
				.updateFile(userName, repository, path, fileName,
						authorizationHeaderValue, content);
	} else {
		messageDialogBuilder.createError(UIMessages.INSTANCE.warning(),
				UIMessages.INSTANCE.gitHubModifyWarning())
				.show();
		autoMessageBox.hide();
	}
}
 
Example 49
Project: sig-seguimiento-vehiculos   File: GitHubCreateFileExporter.java   Source Code and License 5 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 50
Project: optashift-employee-rostering   File: FailureShownRestCallback.java   Source Code and License 5 votes vote down vote up
@Override
public void onError(Response response) {
    String message = "Error calling REST method with status (" + response.getStatusCode() + ": " + response.getStatusText() + ") and text (" +
        response.getText() + ").";
    ErrorPopup.show(message);
    throw new IllegalStateException(message);
}
 
Example 51
Project: appinventor-extensions   File: OdeAsyncCallback.java   Source Code and License 5 votes vote down vote up
@Override
public void onFailure(Throwable caught) {
  if (caught instanceof IncompatibleRemoteServiceException) {
    ErrorReporter.reportError("App Inventor has just been upgraded, you will need to press the reload button in your browser window");
    return;
  }
  if (caught instanceof InvalidSessionException) {
    Ode.getInstance().invalidSessionDialog();
    return;
  }
  if (caught instanceof ChecksumedFileException) {
    Ode.getInstance().corruptionDialog();
    return;
  }
  if (caught instanceof BlocksTruncatedException) {
    OdeLog.log("Caught BlocksTruncatedException");
    ErrorReporter.reportError("Caught BlocksTruncatedException");
    return;
  }
  // SC_PRECONDITION_FAILED if our session has expired or login cookie
  // has become invalid
  if ((caught instanceof StatusCodeException) &&
    ((StatusCodeException)caught).getStatusCode() == Response.SC_PRECONDITION_FAILED) {
    Ode.getInstance().sessionDead();
    return;
  }
  String errorMessage =
      (failureMessage == null) ? caught.getMessage() : failureMessage;
  ErrorReporter.reportError(errorMessage);
  OdeLog.elog("Got exception: " + caught.getMessage());
  Throwable cause = caught.getCause();
  if (cause != null) {
    OdeLog.elog("Caused by: " + cause.getMessage());
  }
}
 
Example 52
Project: LAS   File: LASAnnotationsPanel.java   Source Code and License 5 votes vote down vote up
@Override
public void onResponseReceived(Request request, Response response) {

	String text = response.getText();
	setAnnotationsHTML(text);
	eventBus.fireEventFromSource(new ResizeEvent(), LASAnnotationsPanel.this);

}
 
Example 53
Project: LAS   File: CruiseIconWidget.java   Source Code and License 5 votes vote down vote up
@Override
public void onResponseReceived(Request request, Response response) {
	String doc = response.getText();
	if ( doc != null && !doc.equals("") && doc.contains("<?xml") ) {
	    load(doc);
	}
          setCheckedIcons(checkedIcons);
}
 
Example 54
Project: LAS   File: InventoryMap.java   Source Code and License 5 votes vote down vote up
@Override
public void onResponseReceived(Request request, Response response) {
	String text = response.getText();
	HTML html = new HTML(HtmlSanitizerUtil.sanitizeHtml(text));
	navbarheader.clear();
	navbarheader.add(html);
}
 
Example 55
Project: LAS   File: InventoryMap.java   Source Code and License 5 votes vote down vote up
@Override
public void onResponseReceived(Request request, Response response) {
	String text = response.getText();
	HTML html = new HTML(HtmlSanitizerUtil.sanitizeHtml(text));
	navbarfooter.clear();
	navbarfooter.add(html);
}
 
Example 56
Project: LAS   File: LASResponseEvent.java   Source Code and License 5 votes vote down vote up
public LASResponseEvent(Request request, Response response,
		String callerObjectName, String callbackObjectName) {
	this.request = request;
	this.response = response;
	this.callerObjectName = callerObjectName;
       this.callbackObjectName = callbackObjectName;
       this.setResponseReceived(true);
}
 
Example 57
Project: LAS   File: MultiCallback.java   Source Code and License 5 votes vote down vote up
@Override
public void onResponseReceived(Request request, Response response) {
	controller.done(this);
	for (ArrayList<String> callbackPair : callbackPairs) {
		LASResponseEvent lasResponseEvent = new LASResponseEvent(request,
				response, callbackPair.get(0), callbackPair.get(1));
		logger.info("MultiCallback is firing lasResponseEvent:"
				+ lasResponseEvent + "for callbackPair:" + callbackPair
				+ " with response:" + response);
		eventBus.fireEventFromSource(lasResponseEvent, this);
	}
}
 
Example 58
Project: cuba   File: CubaXhrConnection.java   Source Code and License 5 votes vote down vote up
@Override
protected XhrResponseHandler createResponseHandler() {
    return new XhrResponseHandler() {
        protected int serverTimeOnClient;

        @Override
        public void onResponseReceived(Request request, Response response) {
            int statusCode = response.getStatusCode();
            if (statusCode == 200) {
                serverTimeOnClient = (int) Util.round(Profiler.getRelativeTimeMillis() - requestStartTime, 0);
            }
            super.onResponseReceived(request, response);
        }

        @Override
        protected void beforeHandlingMessage(ValueMap json) {
            super.beforeHandlingMessage(json);
            ScreenClientProfiler profiler = ScreenClientProfiler.getInstance();
            String profilerMarker = ScreenClientProfiler.getProfilerMarkerFromJson(json);
            if (profilerMarker != null) {
                int serverTimeOnServer = ScreenClientProfiler.getServerTimeFromJson(json);
                if (serverTimeOnServer > 0) {
                    profiler.registerServerTime(profilerMarker, serverTimeOnServer);
                    profiler.registerNetworkTime(profilerMarker, serverTimeOnClient - serverTimeOnServer);
                } else {
                    profiler.registerServerTime(profilerMarker, serverTimeOnClient);
                }
                profiler.registerEventTs(profilerMarker, ScreenClientProfiler.getEventTsFromJson(json));
            }
        }
    };
}
 
Example 59
Project: errai-crud   File: ContactListPage.java   Source Code and License 5 votes vote down vote up
private void createNewContactFromEditor() {
  final Contact editorModel = editor.getValue();
  // Adding this model to the list will create and display a new, bound ContactDisplay in the table.
  binder.getModel().add(editorModel);
  contactService.call((ResponseCallback) response -> {
    // Set the id if we successfully create this contact.
    if (response.getStatusCode() == Response.SC_CREATED) {
      final String createdUri = response.getHeader("Location");
      final String idString = createdUri.substring(createdUri.lastIndexOf('/')+1);
      final long id = Long.parseLong(idString);
      editorModel.setId(id);
    }
  }).create(new ContactOperation(editorModel, bus.getSessionId()));
}
 
Example 60
Project: gwt-syncproxy   File: RemoteServiceServletTest.java   Source Code and License 5 votes vote down vote up
/**
 * Modified by P.Prith to handle the {@link GWT#getModuleBaseURL()}
 * dependency
 */
public void testAlternateStatusCode() {
	RemoteServiceServletTestServiceAsync service = getAsyncService();
	((ServiceDefTarget) service).setServiceEntryPoint(getModuleBaseURL()
			+ "servlettest/404");

	delayTestFinishForRpc();

	service.test(new AsyncCallback<Void>() {

		@Override
		public void onFailure(Throwable caught) {
			if (caught instanceof StatusCodeException) {
				assertEquals(Response.SC_NOT_FOUND,
						((StatusCodeException) caught).getStatusCode());
				assertEquals("Not Found",
						((StatusCodeException) caught).getStatusText());
				finishTest();
			} else {
				TestSetValidator.rethrowException(caught);
			}
		}

		@Override
		public void onSuccess(Void result) {
			fail("Should not have succeeded");
		}
	});
}