Example usage for com.google.gwt.http.client RequestBuilder setHeader

List of usage examples for com.google.gwt.http.client RequestBuilder setHeader

Introduction

In this page you can find the example usage for com.google.gwt.http.client RequestBuilder setHeader.

Prototype

public void setHeader(String header, String value) 

Source Link

Document

Sets a request header with the given name and value.

Usage

From source file:org.palaso.languageforge.client.lex.jsonrpc.JsonRpc.java

License:Apache License

/**
 * Executes a json-rpc request.//www .j  a v a2  s.  c o  m
 * 
 * @param <R>
 * 
 * @param <R>
 * 
 * @param url
 *            The location of the service
 * @param username
 *            The username for basic authentification
 * @param password
 *            The password for basic authentification
 * @param method
 *            The method name
 * @param params
 *            An array of objects containing the parameters
 * @param callback
 *            A callbackhandler like in gwt's rpc.
 */

// NOTE We will use the Action to 3encode our request and decode the
// response
// of *the object* (DTO)
// NOTE This class will add the rpc elements which wrap the request and
// repsonse.
public <A extends Action<R>, R> void execute(final A action, final AsyncCallback<R> callback) {

    RequestCallback handler = new RequestCallback() {
        public void onResponseReceived(Request request, Response response) {
            try {
                if (response.getStatusCode() != 200) {
                    String errMsg = "";
                    if (response.getStatusCode() == 0) {
                        errMsg = "Error: Can not connect to server, this may be a problem of network or server down.";
                    } else {
                        errMsg = "Error: Unexpected server or network error ["
                                + String.valueOf(response.getStatusCode()) + "]: " + response.getStatusText();
                    }
                    RuntimeException runtimeException = new RuntimeException(errMsg);
                    callback.onFailure(runtimeException);
                    return;
                }

                String resp = response.getText();

                if (resp.equals("")) {
                    RuntimeException runtimeException = new RuntimeException(
                            "Error: Received empty result from server, this could be a server fail.");
                    callback.onFailure(runtimeException);
                }

                JsonRpcResponse<R> reply = action.decodeResponse(resp);

                if (reply == null) { // This implies a decode error. Perhaps
                                     // it would be better if the action
                                     // doing the decode threw a more
                                     // precise exception
                    RuntimeException runtimeException = new RuntimeException(
                            "Error: Received data can not decoded, data: " + response.getText());
                    callback.onFailure(runtimeException);
                }

                if (reply.getResponseModel().isErrorResponse()) {
                    RuntimeException runtimeException = new RuntimeException(
                            "Error: Server failed with message: " + reply.getResponseModel().getError());
                    callback.onFailure(runtimeException);
                } else if (reply.getResponseModel().isSuccessfulResponse()) {
                    R result = (R) reply.getResponseModel().getResult();
                    callback.onSuccess(result);
                } else {
                    RuntimeException runtimeException = new RuntimeException(
                            "Error: Received data has syntax error: " + response.getText());
                    callback.onFailure(runtimeException);
                }
            } catch (RuntimeException e) {
                callback.onFailure(e);
            } finally {
                decreaseRequestCounter(action.isBackgroundRequest());
            }
        }

        public void onError(Request request, Throwable exception) {
            try {
                if (exception instanceof RequestTimeoutException) {
                    RuntimeException runtimeException = new RuntimeException(
                            "Error: Connection timeout, server didn't respose.");
                    callback.onFailure(runtimeException);
                } else {
                    RuntimeException runtimeException = new RuntimeException(
                            "Error: A unknown error happened when try to send request to server");
                    callback.onFailure(runtimeException);
                }
            } catch (RuntimeException e) {
                callback.onFailure(e);
            } finally {
                decreaseRequestCounter(action.isBackgroundRequest());
            }
        }

    };

    increaseRequestCounter(action.isBackgroundRequest());

    // The request builder. Currently we only attempt a request once.
    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, action.getFullServiceUrl());
    if (requestTimeout > 0)
        builder.setTimeoutMillis(requestTimeout);
    builder.setHeader("Content-Type", "application/json; charset=UTF-8");

    String body = action.getRequestModelAsJsonString(requestSerial++);

    if (body == null)
        builder.setHeader("Content-Length", "0");
    // builder.setHeader("Content-Length", Integer.toString(body.length()));
    if (requestCookie != null)
        if (Cookies.getCookie(requestCookie) != null)
            builder.setHeader("X-Cookie", Cookies.getCookie(requestCookie));

    try {
        builder.sendRequest(body, handler);
    } catch (RequestException exception) {
        handler.onError(null, exception);
    }
}

From source file:org.pentaho.gwt.widgets.client.filechooser.FileChooser.java

License:Open Source License

public void fetchRepository(final IDialogCallback completedCallback) throws RequestException {
    RequestBuilder builder = null;
    builder = new RequestBuilder(RequestBuilder.GET, getFullyQualifiedURL()
            + "api/repo/files/:/tree?showHidden=" + showHiddenFiles + "&depth=-1&filter=*"); //$NON-NLS-1$
    builder.setHeader("accept", "application/json"); //$NON-NLS-1$ //$NON-NLS-2$
    RequestCallback callback = new RequestCallback() {

        public void onError(Request request, Throwable exception) {
            Window.alert(exception.toString());
        }//w  w w  . ja v  a  2s  .  com

        public void onResponseReceived(Request request, Response response) {
            if (response.getStatusCode() == Response.SC_OK) {
                String jsonData = response.getText();
                JsonToRepositoryFileTreeConverter converter = new JsonToRepositoryFileTreeConverter(jsonData);
                repositoryTree = TreeBuilder.buildSolutionTree(converter.getTree(), showHiddenFiles,
                        showLocalizedFileNames, fileFilter);
                selectedTreeItem = repositoryTree.getItem(0);
                initUI();
                if (completedCallback != null) {
                    completedCallback.okPressed();
                }
            } else {
                Window.alert("Solution Repository not found."); //$NON-NLS-1$
            }
        }

    };
    builder.sendRequest(null, callback);
}

From source file:org.pentaho.gwt.widgets.client.utils.i18n.ResourceBundle.java

License:Open Source License

private void initCallbacks() {
    baseCallback = new RequestCallback() {
        public void onError(Request request, Throwable exception) {
            Window.alert("baseCallback: " + exception.getMessage()); //$NON-NLS-1$
            fireBundleLoadCallback();/*from w ww  . j  av  a  2  s  .c  o  m*/
        }

        public void onResponseReceived(Request request, Response response) {
            String propertiesFileText = response.getText();

            // build a simple map of key/value pairs from the properties file
            if (response.getStatusCode() == Response.SC_OK) {
                bundle = PropertiesUtil.buildProperties(propertiesFileText, bundle);
                if (response instanceof FakeResponse == false) {
                    // this is a real bundle load
                    bundleCache.put(currentAttemptUrl, propertiesFileText);
                }
            } else {
                // put empty bundle in cache (not found, but we want to remember it was not found)
                bundleCache.put(currentAttemptUrl, ""); //$NON-NLS-1$
            }

            // if we are not attempting to fetch any localized bundles
            // then fire our callback and then return, we're done
            if (!attemptLocalizedFetches) {
                fireBundleLoadCallback();
                return;
            }

            // now fetch the the lang/country variants
            if (localeName.equalsIgnoreCase("default")) { //$NON-NLS-1$
                // process only bundleName.properties
                fireBundleLoadCallback();
                return;
            } else {
                StringTokenizer st = new StringTokenizer(localeName, '_');
                if (st.countTokens() > 0) {
                    String lang = st.tokenAt(0);
                    // 2. fetch bundleName_lang.properties
                    // 3. fetch bundleName_lang_country.properties
                    currentAttemptUrl = path + bundleName + "_" + lang + PROPERTIES_EXTENSION + getUrlExtras(); //$NON-NLS-1$

                    // IE caches the file and causes an issue with the request

                    if (!isSupportedLanguage(lang) || bundleCache.containsKey(currentAttemptUrl)) {
                        langCallback.onResponseReceived(null,
                                new FakeResponse(bundleCache.get(currentAttemptUrl)));
                    } else {
                        RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET,
                                currentAttemptUrl);

                        // Caching causing some strange behavior with IE6.
                        // TODO: Investigate caching issue.
                        requestBuilder.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$  //$NON-NLS-2$

                        try {
                            requestBuilder.sendRequest(null, langCallback);
                        } catch (RequestException e) {
                            Window.alert("lang: " + e.getMessage()); //$NON-NLS-1$
                            fireBundleLoadCallback();
                        }
                    }
                } else if (st.countTokens() == 0) {
                    // already fetched
                    fireBundleLoadCallback();
                    return;
                }
            }
        }
    };
    langCallback = new RequestCallback() {
        public void onError(Request request, Throwable exception) {
            Window.alert("langCallback: " + exception.getMessage()); //$NON-NLS-1$
            fireBundleLoadCallback();
        }

        public void onResponseReceived(Request request, Response response) {
            String propertiesFileText = response.getText();
            // build a simple map of key/value pairs from the properties file
            if (response.getStatusCode() == Response.SC_OK) {
                bundle = PropertiesUtil.buildProperties(propertiesFileText, bundle);
                if (response instanceof FakeResponse == false) {
                    // this is a real bundle load
                    bundleCache.put(currentAttemptUrl, propertiesFileText);
                }
            } else {
                // put empty bundle in cache (not found, but we want to remember it was not found)
                bundleCache.put(currentAttemptUrl, ""); //$NON-NLS-1$
            }

            StringTokenizer st = new StringTokenizer(localeName, '_');
            if (st.countTokens() == 2) {
                // 3. fetch bundleName_lang_country.properties

                // need to match case-insensitive on country
                if (!isSupportedLanguage(localeName)) {
                    // try to switch the case on the trailing characters
                    if (isSupportedLanguage(st.tokenAt(0) + "_" + st.tokenAt(1).toUpperCase())) {
                        localeName = st.tokenAt(0) + "_" + st.tokenAt(1).toUpperCase();
                    }
                }

                currentAttemptUrl = path + bundleName + "_" + localeName + PROPERTIES_EXTENSION //$NON-NLS-1$
                        + getUrlExtras();
                if (!isSupportedLanguage(localeName) || bundleCache.containsKey(currentAttemptUrl)) {
                    langCountryCallback.onResponseReceived(null,
                            new FakeResponse(bundleCache.get(currentAttemptUrl)));
                } else {
                    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, currentAttemptUrl);
                    try {
                        requestBuilder.sendRequest(null, langCountryCallback);
                    } catch (RequestException e) {
                        Window.alert("langCountry: " + e.getMessage()); //$NON-NLS-1$
                        fireBundleLoadCallback();
                    }
                }
            } else {
                // already fetched
                fireBundleLoadCallback();
                return;
            }
        }
    };
    langCountryCallback = new RequestCallback() {
        public void onError(Request request, Throwable exception) {
            Window.alert("langCountryCallback: " + exception.getMessage()); //$NON-NLS-1$
            fireBundleLoadCallback();
        }

        public void onResponseReceived(Request request, Response response) {
            String propertiesFileText = response.getText();
            // build a simple map of key/value pairs from the properties file
            if (response.getStatusCode() == Response.SC_OK) {
                bundle = PropertiesUtil.buildProperties(propertiesFileText, bundle);
                if (response instanceof FakeResponse == false) {
                    // this is a real bundle load
                    bundleCache.put(currentAttemptUrl, propertiesFileText);
                }
            } else {
                // put empty bundle in cache (not found, but we want to remember it was not found)
                bundleCache.put(currentAttemptUrl, ""); //$NON-NLS-1$
            }
            fireBundleLoadCallback();
        }
    };
}

From source file:org.pentaho.gwt.widgets.client.utils.MessageBundle.java

License:Open Source License

@Deprecated
private void initCallbacks() {
    baseCallback = new RequestCallback() {
        public void onError(Request request, Throwable exception) {
            Window.alert("baseCallback " + MSGS.error() + ":" + exception.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
            fireBundleLoadCallback();/*from   w  w  w . j av a  2s .c o m*/
        }

        public void onResponseReceived(Request request, Response response) {
            String propertiesFileText = response.getText();

            // build a simple map of key/value pairs from the properties file
            if (response.getStatusCode() == Response.SC_OK) {
                bundle = PropertiesUtil.buildProperties(propertiesFileText, bundle);
                if (response instanceof FakeResponse == false) {
                    // this is a real bundle load
                    bundleCache.put(currentAttemptUrl, propertiesFileText);
                }
            } else {
                // put empty bundle in cache (not found, but we want to remember it was not found)
                bundleCache.put(currentAttemptUrl, ""); //$NON-NLS-1$
            }

            // now fetch the the lang/country variants
            if (localeName.equalsIgnoreCase("default")) { //$NON-NLS-1$
                // process only bundleName.properties
                fireBundleLoadCallback();
                return;
            } else {
                StringTokenizer st = new StringTokenizer(localeName, '_');
                if (st.countTokens() > 0) {
                    String lang = st.tokenAt(0);
                    // 2. fetch bundleName_lang.properties
                    // 3. fetch bundleName_lang_country.properties
                    currentAttemptUrl = path + bundleName + "_" + lang + PROPERTIES_EXTENSION + getUrlExtras(); //$NON-NLS-1$

                    // IE caches the file and causes an issue with the request

                    if (bundleCache.containsKey(currentAttemptUrl)) {
                        langCallback.onResponseReceived(null,
                                new FakeResponse(bundleCache.get(currentAttemptUrl)));
                    } else {
                        RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET,
                                currentAttemptUrl);

                        // Caching causing some strange behavior with IE6.
                        // TODO: Investigate caching issue.
                        requestBuilder.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$

                        try {
                            requestBuilder.sendRequest(null, langCallback);
                        } catch (RequestException e) {
                            Window.alert("lang " + MSGS.error() + ":" + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
                            fireBundleLoadCallback();
                        }
                    }
                } else if (st.countTokens() == 0) {
                    // already fetched
                    fireBundleLoadCallback();
                    return;
                }
            }
        }
    };
    langCallback = new RequestCallback() {
        public void onError(Request request, Throwable exception) {
            Window.alert("langCallback " + MSGS.error() + ":" + exception.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
            fireBundleLoadCallback();
        }

        public void onResponseReceived(Request request, Response response) {
            String propertiesFileText = response.getText();
            // build a simple map of key/value pairs from the properties file
            if (response.getStatusCode() == Response.SC_OK) {
                bundle = PropertiesUtil.buildProperties(propertiesFileText, bundle);
                if (response instanceof FakeResponse == false) {
                    // this is a real bundle load
                    bundleCache.put(currentAttemptUrl, propertiesFileText);
                }
            } else {
                // put empty bundle in cache (not found, but we want to remember it was not found)
                bundleCache.put(currentAttemptUrl, ""); //$NON-NLS-1$
            }

            StringTokenizer st = new StringTokenizer(localeName, '_');
            if (st.countTokens() == 2) {
                // 3. fetch bundleName_lang_country.properties
                currentAttemptUrl = path + bundleName + "_" + localeName + PROPERTIES_EXTENSION //$NON-NLS-1$
                        + getUrlExtras();
                if (bundleCache.containsKey(currentAttemptUrl)) {
                    langCountryCallback.onResponseReceived(null,
                            new FakeResponse(bundleCache.get(currentAttemptUrl)));
                } else {
                    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, currentAttemptUrl);
                    try {
                        requestBuilder.sendRequest(null, langCountryCallback);
                    } catch (RequestException e) {
                        Window.alert("langCountry " + MSGS.error() + ":" + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
                        fireBundleLoadCallback();
                    }
                }
            } else {
                // already fetched
                fireBundleLoadCallback();
                return;
            }
        }
    };
    langCountryCallback = new RequestCallback() {
        public void onError(Request request, Throwable exception) {
            Window.alert("langCountryCallback " + MSGS.error() + ":" + exception.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
            fireBundleLoadCallback();
        }

        public void onResponseReceived(Request request, Response response) {
            String propertiesFileText = response.getText();
            // build a simple map of key/value pairs from the properties file
            if (response.getStatusCode() == Response.SC_OK) {
                bundle = PropertiesUtil.buildProperties(propertiesFileText, bundle);
                if (response instanceof FakeResponse == false) {
                    // this is a real bundle load
                    bundleCache.put(currentAttemptUrl, propertiesFileText);
                }
            } else {
                // put empty bundle in cache (not found, but we want to remember it was not found)
                bundleCache.put(currentAttemptUrl, ""); //$NON-NLS-1$
            }
            fireBundleLoadCallback();
        }
    };
}

From source file:org.pentaho.gwt.widgets.login.client.AuthenticatedGwtServiceUtil.java

License:Open Source License

/**
 * invokeCommand method tries to execute the service and incase of SC_UNAUTHORIZED error the login dialog is presented
 * where the user can enter their credentials. Once you are successfully logged in, the requested services is
 * performed again/*from w w w.ja  v  a  2 s.  c o m*/
 * 
 * @param command
 * @param theirCallback
 */
public static void invokeCommand(final IAuthenticatedGwtCommand command, final AsyncCallback theirCallback) {
    command.execute(new AsyncCallback() {

        public void onFailure(final Throwable caught) {
            // The request has failed. We need to check if the request failed due to authentication
            // We will simply to a get of an image and if it responds back with Response.SC_UNAUTHORIZED
            // We will display a login page to the user otherwise we will return the error back to the
            // user
            String[] pathArray = Window.Location.getPath().split("/");
            String webAppPath = "/" + pathArray[1] + "/";
            RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,
                    webAppPath + "mantle/images/spacer.gif"); //$NON-NLS-1$
            builder.setHeader("Content-Type", "application/xml");
            RequestCallback callback = new RequestCallback() {

                public void onError(Request request, Throwable exception) {
                    theirCallback.onFailure(caught);
                }

                public void onResponseReceived(Request request, Response response) {
                    if (Response.SC_UNAUTHORIZED == response.getStatusCode()) {
                        doLogin(command, theirCallback);
                    } else {
                        theirCallback.onFailure(caught);
                    }
                }
            };

            try {
                builder.sendRequest("", callback); //$NON-NLS-1$ //$NON-NLS-2$
            } catch (RequestException e) {
                e.printStackTrace();
            }
        }

        public void onSuccess(Object result) {
            theirCallback.onSuccess(result);
        }
    });
}

From source file:org.pentaho.mantle.client.admin.ContentCleanerPanel.java

License:Open Source License

public void activate() {
    clear();//from   w w w.ja v  a  2  s.c o m
    String moduleBaseURL = GWT.getModuleBaseURL();
    String moduleName = GWT.getModuleName();
    String contextURL = moduleBaseURL.substring(0, moduleBaseURL.lastIndexOf(moduleName));

    RequestBuilder scheduleFileRequestBuilder = new RequestBuilder(RequestBuilder.GET,
            contextURL + "api/scheduler/getContentCleanerJob?cb=" + System.currentTimeMillis());
    scheduleFileRequestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
    scheduleFileRequestBuilder.setHeader("Content-Type", "application/json"); //$NON-NLS-1$//$NON-NLS-2$
    scheduleFileRequestBuilder.setHeader("accept", "application/json"); //$NON-NLS-1$//$NON-NLS-2$

    try {
        scheduleFileRequestBuilder.sendRequest("", new RequestCallback() {
            public void onError(Request request, Throwable exception) {
            }

            public void onResponseReceived(Request request, Response response) {
                final TextBox nowTextBox = new TextBox();
                nowTextBox.setWidth("24px");
                nowTextBox.getElement().getStyle().setPadding(5, Unit.PX);
                nowTextBox.getElement().getStyle().setMarginLeft(5, Unit.PX);
                nowTextBox.getElement().getStyle().setMarginRight(5, Unit.PX);
                final TextBox scheduleTextBox = new TextBox();
                scheduleTextBox.setVisibleLength(4);

                JsJob tmpJsJob = parseJsonJob(JsonUtils.escapeJsonForEval(response.getText()));

                boolean fakeJob = false;
                if (tmpJsJob == null) {
                    tmpJsJob = createJsJob();
                    fakeJob = true;
                }
                final JsJob jsJob = tmpJsJob;

                if (jsJob != null) {
                    scheduleTextBox.setValue("" + (Long.parseLong(jsJob.getJobParamValue("age")) / 86400L));
                } else {
                    scheduleTextBox.setText("180");
                }
                scheduleTextBox.addChangeHandler(new ChangeHandler() {
                    public void onChange(ChangeEvent event) {
                        if (jsJob != null) {
                            JsArray<JsJobParam> params = jsJob.getJobParams();
                            for (int i = 0; i < params.length(); i++) {
                                if (params.get(i).getName().equals("age")) {
                                    params.get(i).setValue(
                                            "" + (Long.parseLong(scheduleTextBox.getText()) * 86400L));
                                    break;
                                }
                            }
                        }
                    }
                });

                Label settingsLabel = new Label(Messages.getString("settings"));
                settingsLabel.setStyleName("pentaho-fieldgroup-major");
                add(settingsLabel, DockPanel.NORTH);

                VerticalPanel nowPanelWrapper = new VerticalPanel();
                Label deleteNowLabel = new Label(Messages.getString("deleteGeneratedFilesNow"));
                deleteNowLabel.getElement().getStyle().setPaddingTop(15, Unit.PX);
                deleteNowLabel.setStyleName("pentaho-fieldgroup-minor");
                nowPanelWrapper.add(deleteNowLabel);

                HorizontalPanel nowLabelPanel = new HorizontalPanel();
                nowLabelPanel.getElement().getStyle().setPaddingTop(10, Unit.PX);
                nowLabelPanel.getElement().getStyle().setPaddingBottom(10, Unit.PX);

                Label deleteGeneratedFilesOlderThan = new Label(
                        Messages.getString("deleteGeneratedFilesOlderThan"));
                deleteGeneratedFilesOlderThan.getElement().getStyle().setPaddingTop(7, Unit.PX);
                nowLabelPanel.add(deleteGeneratedFilesOlderThan);

                nowLabelPanel.add(nowTextBox);
                nowTextBox.setText("180");
                Label days = new Label(Messages.getString("daysDot"));
                days.getElement().getStyle().setPaddingTop(7, Unit.PX);
                nowLabelPanel.add(days);
                Button deleteNowButton = new Button(Messages.getString("deleteNow"));
                deleteNowButton.setStylePrimaryName("pentaho-button");
                deleteNowButton.addStyleName("first");
                deleteNowButton.addClickHandler(new ClickHandler() {
                    public void onClick(ClickEvent event) {
                        MessageDialogBox warning = new MessageDialogBox(Messages.getString("deleteNow"),
                                Messages.getString("confirmDeleteGeneratedContentNow"), false, false, true,
                                Messages.getString("yes"), null, Messages.getString("no"));
                        warning.setCallback(new IDialogCallback() {
                            @Override
                            public void okPressed() {
                                deleteContentNow(Long.parseLong(nowTextBox.getValue()) * 86400L);
                            }

                            @Override
                            public void cancelPressed() {
                            }
                        });
                        warning.center();
                    }
                });
                nowPanelWrapper.add(nowLabelPanel);
                nowPanelWrapper.add(deleteNowButton);
                add(nowPanelWrapper, DockPanel.NORTH);

                // scheduled
                VerticalPanel scheduledPanel = new VerticalPanel();
                Label deleteScheduleLabel = new Label(Messages.getString("scheduleDeletionOfGeneratedFiles"));
                deleteScheduleLabel.setStyleName("pentaho-fieldgroup-minor");
                deleteScheduleLabel.getElement().getStyle().setPaddingTop(15, Unit.PX);
                scheduledPanel.add(deleteScheduleLabel);

                Label descLabel;
                if (!fakeJob) {
                    String desc = jsJob.getJobTrigger().getDescription();
                    descLabel = new Label(desc);
                    scheduledPanel.add(descLabel);
                } else {
                    descLabel = new Label(Messages.getString("generatedFilesAreNotScheduledToBeDeleted"));
                    scheduledPanel.add(descLabel);
                }
                descLabel.getElement().getStyle().setPaddingTop(10, Unit.PX);
                descLabel.getElement().getStyle().setPaddingBottom(10, Unit.PX);

                Button editScheduleButton = new Button(Messages.getString("edit"));
                if (fakeJob) {
                    editScheduleButton.setText(Messages.getString("scheduleDeletion"));
                }
                Button deleteScheduleButton = new Button(Messages.getString("cancelSchedule"));
                deleteScheduleButton.setStylePrimaryName("pentaho-button");
                deleteScheduleButton.addStyleName("last");
                deleteScheduleButton.addClickHandler(new ClickHandler() {
                    public void onClick(ClickEvent event) {
                        deleteContentCleaner(jsJob);
                    }
                });
                editScheduleButton.setStylePrimaryName("pentaho-button");
                editScheduleButton.addStyleName("first");
                editScheduleButton.addClickHandler(new ClickHandler() {
                    public void onClick(ClickEvent event) {
                        IDialogCallback callback = new IDialogCallback() {
                            public void okPressed() {
                                deleteContentCleaner(jsJob);
                            }

                            public void cancelPressed() {
                            }
                        };

                        HorizontalPanel scheduleLabelPanel = new HorizontalPanel();
                        scheduleLabelPanel
                                .add(new Label(Messages.getString("deleteGeneratedFilesOlderThan"), false));
                        scheduleLabelPanel.add(scheduleTextBox);
                        scheduleLabelPanel
                                .add(new Label(Messages.getString("daysUsingTheFollowingRules"), false));
                        ScheduleRecurrenceDialog editSchedule = new ScheduleRecurrenceDialog(null, jsJob,
                                callback, false, false, AbstractWizardDialog.ScheduleDialogType.SCHEDULER);
                        editSchedule.setShowSuccessDialog(false);
                        editSchedule.addCustomPanel(scheduleLabelPanel, DockPanel.NORTH);
                        editSchedule.center();
                    }
                });
                HorizontalPanel scheduleButtonPanel = new HorizontalPanel();
                scheduleButtonPanel.add(editScheduleButton);
                if (!fakeJob) {
                    scheduleButtonPanel.add(deleteScheduleButton);
                }
                scheduledPanel.add(scheduleButtonPanel);
                add(scheduledPanel, DockPanel.NORTH);

                VerticalPanel fillPanel = new VerticalPanel();
                add(fillPanel, DockPanel.NORTH);
                fillPanel.getElement().getParentElement().getStyle().setHeight(100, Unit.PCT);
            }
        });
    } catch (RequestException re) {
        //ignored
    }

}

From source file:org.pentaho.mantle.client.admin.ContentCleanerPanel.java

License:Open Source License

/**
 * @param age/*from  www .  j a v  a  2 s. com*/
 *          in milliseconds
 */
public void deleteContentNow(long age) {

    showLoadingIndicator();

    String date = DateTimeFormat.getFormat(PredefinedFormat.ISO_8601).format(new Date());
    String json = "{\"jobName\": \"Content Cleaner\", \"actionClass\": \"org.pentaho.platform.admin.GeneratedContentCleaner\","
            + " \"jobParameters\":[ { \"name\": \"age\", \"stringValue\": \"" + age
            + "\", \"type\": \"string\" }], \"simpleJobTrigger\": { \"endTime\": null, \"repeatCount\": \"0\", "
            + "\"repeatInterval\": \"0\", \"startTime\": \"" + date + "\", \"uiPassParam\": \"RUN_ONCE\"} }";

    RequestBuilder scheduleFileRequestBuilder = new RequestBuilder(RequestBuilder.POST,
            GWT.getHostPageBaseURL() + "api/scheduler/job");
    scheduleFileRequestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
    scheduleFileRequestBuilder.setHeader("Content-Type", "application/json"); //$NON-NLS-1$//$NON-NLS-2$
    try {
        scheduleFileRequestBuilder.sendRequest(json, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
            }

            public void onResponseReceived(Request request, Response response) {
                String jobId = response.getText();
                final RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET,
                        GWT.getHostPageBaseURL() + "api/scheduler/jobinfo?jobId="
                                + URL.encodeQueryString(jobId));
                requestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
                requestBuilder.setHeader("Content-Type", "application/json"); //$NON-NLS-1$//$NON-NLS-2$
                requestBuilder.setHeader("accept", "application/json"); //$NON-NLS-1$//$NON-NLS-2$

                // create a timer to check if the job has finished
                Timer t = new Timer() {
                    public void run() {
                        try {
                            requestBuilder.sendRequest(null, new RequestCallback() {

                                @Override
                                public void onResponseReceived(Request request, Response response) {
                                    // if we're receiving a correct job info, then the job is still executing.
                                    // once the job is finished, it is removed from scheduler and we should receive a 404 code.
                                    if (response.getStatusCode() != Response.SC_OK) {
                                        hideLoadingIndicator();
                                        cancel();
                                    }
                                }

                                @Override
                                public void onError(Request request, Throwable throwable) {
                                    hideLoadingIndicator();
                                    cancel();
                                }
                            });
                        } catch (RequestException e) {
                            hideLoadingIndicator();
                            cancel();
                        }
                    }
                };
                t.scheduleRepeating(1000);
            }
        });
    } catch (RequestException re) {
        hideLoadingIndicator();
    }
}

From source file:org.pentaho.mantle.client.admin.ContentCleanerPanel.java

License:Open Source License

private void deleteContentCleaner(JsJob jsJob) {
    if (jsJob == null || StringUtils.isEmpty(jsJob.getJobId())) {
        activate();/*w ww  .  j  av  a 2  s.co m*/
        return;
    }
    final String url = GWT.getHostPageBaseURL() + "api/scheduler/removeJob"; //$NON-NLS-1$
    RequestBuilder builder = new RequestBuilder(RequestBuilder.DELETE, url);
    builder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
    builder.setHeader("Content-Type", "application/json"); //$NON-NLS-1$//$NON-NLS-2$

    JSONObject startJobRequest = new JSONObject();
    startJobRequest.put("jobId", new JSONString(jsJob.getJobId())); //$NON-NLS-1$

    try {
        builder.sendRequest(startJobRequest.toString(), new RequestCallback() {

            public void onError(Request request, Throwable exception) {
                // showError(exception);
                activate();
            }

            public void onResponseReceived(Request request, Response response) {
                activate();
            }
        });
    } catch (RequestException re) {
        Window.alert(re.getMessage());
    }
}

From source file:org.pentaho.mantle.client.admin.EmailAdminPanelController.java

License:Open Source License

private void setEmailConfig() {
    String serviceUrl = GWT.getHostPageBaseURL() + "api/emailconfig/setEmailConfig";
    RequestBuilder executableTypesRequestBuilder = new RequestBuilder(RequestBuilder.PUT, serviceUrl);
    try {// w  w  w  . j  a  v a2s  .  c  o  m
        executableTypesRequestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
        executableTypesRequestBuilder.setHeader("Content-Type", "application/json");
        executableTypesRequestBuilder.sendRequest(emailConfig.getJSONString(), new RequestCallback() {
            public void onError(Request request, Throwable exception) {
            }

            public void onResponseReceived(Request request, Response response) {
                setDirty(false);
            }
        });
    } catch (RequestException e) {
        //ignored
    }
}

From source file:org.pentaho.mantle.client.admin.EmailAdminPanelController.java

License:Open Source License

private void getEmailConfig() {
    String serviceUrl = GWT.getHostPageBaseURL() + "api/emailconfig/getEmailConfig?cb="
            + System.currentTimeMillis();
    RequestBuilder executableTypesRequestBuilder = new RequestBuilder(RequestBuilder.GET, serviceUrl);
    executableTypesRequestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
    executableTypesRequestBuilder.setHeader("accept", "application/json");
    try {//from w w w  .  ja  v a  2  s .  com
        executableTypesRequestBuilder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
            }

            public void onResponseReceived(Request request, Response response) {
                emailConfig = JsEmailConfiguration.parseJsonString(response.getText());
                authenticationCheckBox.setValue(Boolean.parseBoolean(emailConfig.isAuthenticate() + ""));
                authenticationPanel.setVisible(Boolean.parseBoolean(emailConfig.isAuthenticate() + ""));
                smtpHostTextBox.setValue(emailConfig.getSmtpHost());
                portTextBox.setValue(emailConfig.getSmtpPort() + "");
                useStartTLSCheckBox.setValue(Boolean.parseBoolean(emailConfig.isUseStartTls() + ""));
                useSSLCheckBox.setValue(Boolean.parseBoolean(emailConfig.isUseSsl() + ""));
                fromAddressTextBox.setValue(emailConfig.getDefaultFrom());
                fromNameTextBox.setValue(emailConfig.getFromName());
                userNameTextBox.setValue(emailConfig.getUserId());

                // If password is non-empty.. disable the text-box
                String password = emailConfig.getPassword();
                passwordTextBox.setValue(password);

                String protocol = emailConfig.getSmtpProtocol();
                protocolsListBox.setSelectedIndex(-1);
                if (!StringUtils.isEmpty(protocol)) {
                    for (int i = 0; i < protocolsListBox.getItemCount(); ++i) {
                        if (protocol.equalsIgnoreCase(protocolsListBox.getItemText(i))) {
                            protocolsListBox.setSelectedIndex(i);
                            break;
                        }
                    }
                }
            }
        });
    } catch (RequestException e) {
        //ignored
    }
}