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

The following examples show how to use com.google.gwt.http.client.Response. These examples are extracted from open source projects. 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 Project: flow   Source File: DefaultConnectionStateHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void heartbeatInvalidStatusCode(XMLHttpRequest xhr) {
    int statusCode = xhr.getStatus();
    Console.warn("Heartbeat request returned " + statusCode);

    if (statusCode == Response.SC_GONE) {
        // Session expired
        registry.getSystemErrorHandler().handleSessionExpiredError(null);
        stopApplication();
    } else if (statusCode == Response.SC_NOT_FOUND) {
        // UI closed, do nothing as the UI will react to this
        // Should not trigger reconnect dialog as this will prevent user
        // input
    } else {
        handleRecoverableError(Type.HEARTBEAT, null);
    }
}
 
Example 2
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
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
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
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
@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
Source Project: appinventor-extensions   Source File: OdeAsyncCallback.java    License: Apache License 2.0 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 8
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 9
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 10
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 11
Source Project: geowe-core   Source File: JoinDataTool.java    License: GNU General Public License v3.0 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 12
Source Project: geowe-core   Source File: URLVectorLayerDef.java    License: GNU General Public License v3.0 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 13
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 14
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 15
Source Project: errai-tutorial   Source File: ContactListPage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This is an Errai UI native event handler. The element for which this handler is regsitered is in this class's HTML
 * template file and has the {@code modal-delete} CSS class.
 * <p>
 * The parameter is a JS interop wrapper for a native DOM {@link MouseEvent}. The {@code MouseEvent} interface like many
 * DOM event interfaces is used for multiple browser event types (i.e. "click", "dblclick", "mouseover", etc.). In order
 * to only listen for "click" events we use the {@link ForEvent} annotation.
 * <p>
 * This method removes a {@link Contact} from the displayed table and makes an HTTP request to delete the contact from
 * persistent storage on the server.
 */
@EventHandler("modal-delete")
public void onModalDeleteClick(final @ForEvent("click") MouseEvent event) {
  if (binder.getModel().contains(editor.getValue())) {
    final Contact deleted = editor.getValue();
    contactService.call((final Response response) -> {
      if (response.getStatusCode() >= 200 && response.getStatusCode() < 300) {
        binder.getModel().remove(deleted);
      }
    }).delete(editor.getValue().getId());
    editor.setValue(new Contact());

    modal.classList.remove("displayed");
  }
}
 
Example 16
Source Project: errai-tutorial   Source File: ContactListPage.java    License: Apache License 2.0 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((final Response 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 17
Source Project: core   Source File: LogStore.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private void doStreamLogFile(final String fileName, final Dispatcher.Channel channel) {
    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, encode(streamUrl(fileName)));
    requestBuilder.setHeader("Accept", "text/plain");
    requestBuilder.setHeader("Content-Type", "text/plain");
    String bearerToken = DMRHandler.getBearerToken();
    if (bearerToken != null)
        requestBuilder.setHeader("Authorization", "Bearer " + bearerToken);
        
    requestBuilder.setIncludeCredentials(true);
    try {
        // store the request in order to cancel it later
        pendingStreamingRequest = new PendingStreamingRequest(fileName,
                requestBuilder.sendRequest(null, new RequestCallback() {
                    @Override
                    public void onResponseReceived(Request request, Response response) {
                        if (response.getStatusCode() >= 400) {
                            channel.nack(new IllegalStateException("Failed to stream log file " +
                                    fileName + ": " + response.getStatusCode() + " - " +
                                    response.getStatusText()));
                        } else {
                            LogFile newLogFile = new LogFile(fileName, response.getText());
                            newLogFile.setFollow(false);
                            states.put(fileName, newLogFile);
                            activate(newLogFile);
                            channel.ack();
                        }
                    }

                    @Override
                    public void onError(Request request, Throwable exception) {
                        channel.nack(exception);
                    }
                }), channel);
    } catch (RequestException e) {
        channel.nack(e);
    }
}
 
Example 18
Source Project: appinventor-extensions   Source File: BuildCommand.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void execute(final ProjectNode node) {
  final Ode ode = Ode.getInstance();
  final MessagesOutput messagesOutput = MessagesOutput.getMessagesOutput();
  messagesOutput.clear();
  messagesOutput.addMessages(MESSAGES.buildRequestedMessage(node.getName(),
      DateTimeFormat.getMediumDateTimeFormat().format(new Date())));

  OdeAsyncCallback<RpcResult> callback =
      new OdeAsyncCallback<RpcResult>(
          // failure message
          MESSAGES.buildError()) {
    @Override
    public void onSuccess(RpcResult result) {
      messagesOutput.addMessages(result.getOutput());
      messagesOutput.addMessages(result.getError());
      Tracking.trackEvent(Tracking.PROJECT_EVENT, Tracking.PROJECT_SUBACTION_BUILD_YA,
                          node.getName(), getElapsedMillis());
      if (result.succeeded()) {
        executeNextCommand(node);
      } else {
        // The result is the HTTP response code from the build server.
        int responseCode = result.getResult();
        switch (responseCode) {
          case Response.SC_SERVICE_UNAVAILABLE:
            // SC_SERVICE_UNAVAILABLE (response code 503), means that the build server is too busy
            // at this time to accept this build request.
            // We use ErrorReporter.reportInfo so that the message has yellow background instead of
            // red background.
            ErrorReporter.reportInfo(MESSAGES.buildServerBusyError());
            break;
          case Response.SC_CONFLICT:
            // SC_CONFLICT (response code 409), means that the build server is running a
            // different version of the App Inventor code.
            // We use ErrorReporter.reportInfo so that the message has yellow background instead
            // of red background.
            ErrorReporter.reportInfo(MESSAGES.buildServerDifferentVersion());
            break;
          default:
            String errorMsg = result.getError();
            // This is not an internal App Inventor bug. The error is reported as info so that
            // the red background is not shown.
            ErrorReporter.reportInfo(MESSAGES.buildFailedError() +
                (errorMsg.isEmpty() ? "" : " " + errorMsg));
            break;
        }
        executionFailedOrCanceled();
      }
    }

    @Override
    public void onFailure(Throwable caught) {
      super.onFailure(caught);
      executionFailedOrCanceled();
    }
  };

  String nonce = ode.generateNonce();
  ode.getProjectService().build(node.getProjectId(), nonce, target, secondBuildserver, callback);
}