Example usage for java.util Locale ROOT

List of usage examples for java.util Locale ROOT

Introduction

In this page you can find the example usage for java.util Locale ROOT.

Prototype

Locale ROOT

To view the source code for java.util Locale ROOT.

Click Source Link

Document

Useful constant for the root locale.

Usage

From source file:org.elasticsearch.integration.IndexPrivilegeTests.java

private void assertUserExecutes(String user, String action, String index, boolean userIsAllowed)
        throws Exception {
    Map<String, String> refreshParams = Collections.emptyMap();//singletonMap("refresh", "true");

    switch (action) {
    case "all":
        if (userIsAllowed) {
            assertUserIsAllowed(user, "crud", index);
            assertUserIsAllowed(user, "manage", index);
        } else {//from  w  ww  . j  ava  2s  . c  om
            assertUserIsDenied(user, "crud", index);
            assertUserIsDenied(user, "manage", index);
        }
        break;

    case "create_index":
        if (userIsAllowed) {
            assertAccessIsAllowed(user, "PUT", "/" + index);
        } else {
            assertAccessIsDenied(user, "PUT", "/" + index);
        }
        break;

    case "manage":
        if (userIsAllowed) {
            assertAccessIsAllowed(user, "DELETE", "/" + index);
            assertUserIsAllowed(user, "create_index", index);
            // wait until index ready, but as admin
            assertNoTimeout(client().admin().cluster().prepareHealth(index).setWaitForGreenStatus().get());
            assertAccessIsAllowed(user, "POST", "/" + index + "/_refresh");
            assertAccessIsAllowed(user, "GET", "/" + index + "/_analyze", "{ \"text\" : \"test\" }");
            assertAccessIsAllowed(user, "POST", "/" + index + "/_flush");
            assertAccessIsAllowed(user, "POST", "/" + index + "/_forcemerge");
            assertAccessIsAllowed(user, "POST", "/" + index + "/_upgrade", null);
            assertAccessIsAllowed(user, "POST", "/" + index + "/_close");
            assertAccessIsAllowed(user, "POST", "/" + index + "/_open");
            assertAccessIsAllowed(user, "POST", "/" + index + "/_cache/clear");
            // indexing a document to have the mapping available, and wait for green state to make sure index is created
            assertAccessIsAllowed("admin", "PUT", "/" + index + "/foo/1", jsonDoc, refreshParams);
            assertNoTimeout(client().admin().cluster().prepareHealth(index).setWaitForGreenStatus().get());
            assertAccessIsAllowed(user, "GET", "/" + index + "/_mapping/foo/field/name");
            assertAccessIsAllowed(user, "GET", "/" + index + "/_settings");
        } else {
            assertAccessIsDenied(user, "DELETE", "/" + index);
            assertUserIsDenied(user, "create_index", index);
            assertAccessIsDenied(user, "POST", "/" + index + "/_refresh");
            assertAccessIsDenied(user, "GET", "/" + index + "/_analyze", "{ \"text\" : \"test\" }");
            assertAccessIsDenied(user, "POST", "/" + index + "/_flush");
            assertAccessIsDenied(user, "POST", "/" + index + "/_forcemerge");
            assertAccessIsDenied(user, "POST", "/" + index + "/_upgrade", null);
            assertAccessIsDenied(user, "POST", "/" + index + "/_close");
            assertAccessIsDenied(user, "POST", "/" + index + "/_open");
            assertAccessIsDenied(user, "POST", "/" + index + "/_cache/clear");
            assertAccessIsDenied(user, "GET", "/" + index + "/_mapping/foo/field/name");
            assertAccessIsDenied(user, "GET", "/" + index + "/_settings");
        }
        break;

    case "monitor":
        if (userIsAllowed) {
            assertAccessIsAllowed(user, "GET", "/" + index + "/_stats");
            assertAccessIsAllowed(user, "GET", "/" + index + "/_segments");
            assertAccessIsAllowed(user, "GET", "/" + index + "/_recovery");
        } else {
            assertAccessIsDenied(user, "GET", "/" + index + "/_stats");
            assertAccessIsDenied(user, "GET", "/" + index + "/_segments");
            assertAccessIsDenied(user, "GET", "/" + index + "/_recovery");
        }
        break;

    case "data_access":
        if (userIsAllowed) {
            assertUserIsAllowed(user, "crud", index);
        } else {
            assertUserIsDenied(user, "crud", index);
        }
        break;

    case "crud":
        if (userIsAllowed) {
            assertUserIsAllowed(user, "read", index);
            assertUserIsAllowed(user, "index", index);
        } else {
            assertUserIsDenied(user, "read", index);
            assertUserIsDenied(user, "index", index);
        }
        break;

    case "read":
        if (userIsAllowed) {
            // admin refresh before executing
            assertAccessIsAllowed("admin", "GET", "/" + index + "/_refresh");
            assertAccessIsAllowed(user, "GET", "/" + index + "/_count");
            assertAccessIsAllowed("admin", "GET", "/" + index + "/_search");
            assertAccessIsAllowed("admin", "GET", "/" + index + "/foo/1");
            assertAccessIsAllowed(user, "GET", "/" + index + "/foo/1/_explain",
                    "{ \"query\" : { \"match_all\" : {} } }");
            assertAccessIsAllowed(user, "GET", "/" + index + "/foo/1/_termvector");
            assertUserIsAllowed(user, "search", index);
        } else {
            assertAccessIsDenied(user, "GET", "/" + index + "/_count");
            assertAccessIsDenied(user, "GET", "/" + index + "/_search");
            assertAccessIsDenied(user, "GET", "/" + index + "/foo/1/_explain",
                    "{ \"query\" : { \"match_all\" : {} } }");
            assertAccessIsDenied(user, "GET", "/" + index + "/foo/1/_termvector");
            assertUserIsDenied(user, "search", index);
        }
        break;

    case "search":
        if (userIsAllowed) {
            assertAccessIsAllowed(user, "GET", "/" + index + "/_search");
        } else {
            assertAccessIsDenied(user, "GET", "/" + index + "/_search");
        }
        break;

    case "get":
        if (userIsAllowed) {
            assertAccessIsAllowed(user, "GET", "/" + index + "/foo/1");
        } else {
            assertAccessIsDenied(user, "GET", "/" + index + "/foo/1");
        }
        break;

    case "index":
        if (userIsAllowed) {
            assertAccessIsAllowed(user, "PUT", "/" + index + "/foo/321", "{ \"foo\" : \"bar\" }");
            assertAccessIsAllowed(user, "POST", "/" + index + "/foo/321/_update",
                    "{ \"doc\" : { \"foo\" : \"baz\" } }");
        } else {
            assertAccessIsDenied(user, "PUT", "/" + index + "/foo/321", "{ \"foo\" : \"bar\" }");
            assertAccessIsDenied(user, "POST", "/" + index + "/foo/321/_update",
                    "{ \"doc\" : { \"foo\" : \"baz\" } }");
        }
        break;

    case "delete":
        String jsonDoc = "{ \"name\" : \"docToDelete\"}";
        assertAccessIsAllowed("admin", "PUT", "/" + index + "/foo/docToDelete", jsonDoc, refreshParams);
        assertAccessIsAllowed("admin", "PUT", "/" + index + "/foo/docToDelete2", jsonDoc, refreshParams);
        if (userIsAllowed) {
            assertAccessIsAllowed(user, "DELETE", "/" + index + "/foo/docToDelete");
        } else {
            assertAccessIsDenied(user, "DELETE", "/" + index + "/foo/docToDelete");
        }
        break;

    case "write":
        if (userIsAllowed) {
            assertUserIsAllowed(user, "index", index);
            assertUserIsAllowed(user, "delete", index);
        } else {
            assertUserIsDenied(user, "index", index);
            assertUserIsDenied(user, "delete", index);
        }
        break;

    default:
        fail(String.format(Locale.ROOT, "Unknown action %s to execute", action));
    }

}

From source file:com.gargoylesoftware.htmlunit.activex.javascript.msxml.XMLHTTPRequest.java

private boolean isPreflightAuthorized(final WebResponse preflightResponse) {
    final String originHeader = preflightResponse.getResponseHeaderValue(HEADER_ACCESS_CONTROL_ALLOW_ORIGIN);
    if (!ALLOW_ORIGIN_ALL.equals(originHeader)
            && !webRequest_.getAdditionalHeaders().get(HEADER_ORIGIN).equals(originHeader)) {
        return false;
    }//from w  w w.ja  v a  2s  . co  m
    String headersHeader = preflightResponse.getResponseHeaderValue(HEADER_ACCESS_CONTROL_ALLOW_HEADERS);
    if (headersHeader == null) {
        headersHeader = "";
    } else {
        headersHeader = headersHeader.toLowerCase(Locale.ROOT);
    }
    for (final Entry<String, String> header : webRequest_.getAdditionalHeaders().entrySet()) {
        final String key = header.getKey().toLowerCase(Locale.ROOT);
        if (isPreflightHeader(key, header.getValue()) && !headersHeader.contains(key)) {
            return false;
        }
    }
    return true;
}

From source file:es.emergya.ui.plugins.admin.AdminLayers.java

protected SummaryAction getSummaryAction(final CapaInformacion capaInformacion) {
    SummaryAction action = new SummaryAction(capaInformacion) {

        private static final long serialVersionUID = -3691171434904452485L;

        @Override/*from   www  .j a va  2s  .co  m*/
        protected JFrame getSummaryDialog() {

            if (capaInformacion != null) {
                d = getDialog(capaInformacion, null, "", null, "image/png");
                return d;
            } else {
                JDialog primera = getJDialog();
                primera.setResizable(false);
                primera.setVisible(true);
                primera.setAlwaysOnTop(true);
            }
            return null;
        }

        private JDialog getJDialog() {
            final JDialog dialog = new JDialog();
            dialog.setTitle(i18n.getString("admin.capas.nueva.titleBar"));
            dialog.setIconImage(getBasicWindow().getIconImage());

            dialog.setLayout(new BorderLayout());

            JPanel centro = new JPanel(new FlowLayout());
            centro.setOpaque(false);
            JLabel label = new JLabel(i18n.getString("admin.capas.nueva.url"));
            final JTextField url = new JTextField(50);
            final JLabel icono = new JLabel(LogicConstants.getIcon("48x48_transparente"));
            label.setLabelFor(url);
            centro.add(label);
            centro.add(url);
            centro.add(icono);
            dialog.add(centro, BorderLayout.CENTER);

            JPanel pie = new JPanel(new FlowLayout(FlowLayout.TRAILING));
            pie.setOpaque(false);
            final JButton siguiente = new JButton(i18n.getString("admin.capas.nueva.boton.siguiente"),
                    LogicConstants.getIcon("button_next"));
            JButton cancelar = new JButton(i18n.getString("admin.capas.nueva.boton.cancelar"),
                    LogicConstants.getIcon("button_cancel"));
            final SiguienteActionListener siguienteActionListener = new SiguienteActionListener(url, dialog,
                    icono, siguiente);
            url.addActionListener(siguienteActionListener);

            siguiente.addActionListener(siguienteActionListener);

            cancelar.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    dialog.dispose();
                }
            });
            pie.add(siguiente);
            pie.add(cancelar);
            dialog.add(pie, BorderLayout.SOUTH);

            dialog.getContentPane().setBackground(Color.WHITE);

            dialog.pack();
            dialog.setLocationRelativeTo(null);
            return dialog;
        }

        private JFrame getDialog(final CapaInformacion c, final Capa[] left_items, final String service,
                final Map<String, Boolean> transparentes, final String png) {

            if (left_items != null && left_items.length == 0) {
                JOptionPane.showMessageDialog(AdminLayers.this,
                        i18n.getString("admin.capas.nueva.error.noCapasEnServicio"));
            } else {

                final String label_cabecera = i18n.getString("admin.capas.nueva.nombreCapa");
                final String label_pie = i18n.getString("admin.capas.nueva.infoAdicional");
                final String centered_label = i18n.getString("admin.capas.nueva.origenDatos");
                final String left_label = i18n.getString("admin.capas.nueva.subcapasDisponibles");
                final String right_label;
                if (left_items != null) {
                    right_label = i18n.getString("admin.capas.nueva.capasSeleccionadas");
                } else {
                    right_label = i18n.getString("admin.capas.ficha.capasSeleccionadas");
                }
                final String tituloVentana, cabecera;
                if (c.getNombre() == null) {
                    tituloVentana = i18n.getString("admin.capas.nueva.titulo.nuevaCapa");
                    cabecera = i18n.getString("admin.capas.nueva.cabecera.nuevaCapa");
                } else {
                    tituloVentana = i18n.getString("admin.capas.nueva.titulo.ficha");
                    cabecera = i18n.getString("admin.capas.nueva.cabecera.ficha");
                }

                final Capa[] right_items = c.getCapas().toArray(new Capa[0]);
                final AdminPanel.SaveOrUpdateAction<CapaInformacion> guardar = layers.new SaveOrUpdateAction<CapaInformacion>(
                        c) {

                    private static final long serialVersionUID = 7447770296943341404L;

                    @Override
                    public void actionPerformed(ActionEvent e) {

                        if (isNew && CapaConsultas.alreadyExists(textfieldCabecera.getText())) {
                            JOptionPane.showMessageDialog(super.frame,
                                    i18n.getString("admin.capas.nueva.error.nombreCapaYaExiste"));

                        } else if (textfieldCabecera.getText().isEmpty()) {
                            JOptionPane.showMessageDialog(super.frame,
                                    i18n.getString("admin.capas.nueva.error.nombreCapaEnBlanco"));

                        } else if (((DefaultListModel) right.getModel()).size() == 0) {
                            JOptionPane.showMessageDialog(super.frame,
                                    i18n.getString("admin.capas.nueva.error.noCapasSeleccionadas"));

                        } else if (cambios) {
                            int i = JOptionPane.showConfirmDialog(super.frame,
                                    i18n.getString("admin.capas.nueva.confirmar.guardar.titulo"),
                                    i18n.getString("admin.capas.nueva.confirmar.boton.guardar"),
                                    JOptionPane.YES_NO_CANCEL_OPTION);

                            if (i == JOptionPane.YES_OPTION) {

                                if (original == null) {
                                    original = new CapaInformacion();

                                }
                                original.setInfoAdicional(textfieldPie.getText());
                                original.setNombre(textfieldCabecera.getText());
                                original.setHabilitada(habilitado.isSelected());
                                original.setOpcional(comboTipoCapa.getSelectedIndex() != 0);

                                boolean transparente = true;

                                HashSet<Capa> capas = new HashSet<Capa>();
                                List<Capa> capasEnOrdenSeleccionado = new ArrayList<Capa>();
                                int indice = 0;
                                for (Object c : ((DefaultListModel) right.getModel()).toArray()) {
                                    if (c instanceof Capa) {
                                        transparente = transparente && (transparentes != null
                                                && transparentes.get(((Capa) c).getNombre()) != null
                                                && transparentes.get(((Capa) c).getNombre()));
                                        capas.add((Capa) c);
                                        capasEnOrdenSeleccionado.add((Capa) c);
                                        ((Capa) c).setCapaInformacion(original);
                                        ((Capa) c).setOrden(indice++);
                                        // ((Capa)
                                        // c).setNombre(c.toString());
                                    }

                                }
                                original.setCapas(capas);

                                if (original.getId() == null) {
                                    String url = nombre.getText();

                                    if (url.indexOf("?") > -1) {
                                        if (!url.endsWith("?")) {
                                            url += "&";

                                        }
                                    } else {
                                        url += "?";

                                    }
                                    url += "VERSION=" + version + "&REQUEST=GetMap&FORMAT=" + png + "&SERVICE="
                                            + service + "&WIDTH={2}&HEIGHT={3}&BBOX={1}&SRS={0}";
                                    // if (transparente)
                                    url += "&TRANSPARENT=TRUE";
                                    url += "&LAYERS=";

                                    String estilos = "";
                                    final String coma = "%2C";
                                    if (capasEnOrdenSeleccionado.size() > 0) {
                                        for (Capa c : capasEnOrdenSeleccionado) {
                                            url += c.getTitulo().replaceAll(" ", "+") + coma;
                                            estilos += c.getEstilo() + coma;
                                        }
                                        estilos = estilos.substring(0, estilos.length() - coma.length());

                                        estilos = estilos.replaceAll(" ", "+");

                                        url = url.substring(0, url.length() - coma.length());
                                    }
                                    url += "&STYLES=" + estilos;
                                    original.setUrl_visible(original.getUrl());
                                    original.setUrl(url);
                                }
                                CapaInformacionAdmin.saveOrUpdate(original);

                                cambios = false;

                                layers.setTableData(getAll(new CapaInformacion()));

                                closeFrame();
                            } else if (i == JOptionPane.NO_OPTION) {
                                closeFrame();

                            }
                        } else {
                            closeFrame();

                        }
                    }
                };
                JFrame segunda = generateUrlDialog(label_cabecera, label_pie, centered_label, tituloVentana,
                        left_items, right_items, left_label, right_label, guardar,
                        LogicConstants.getIcon("tittleficha_icon_capa"), cabecera, c.getHabilitada(),
                        c.getOpcional(), c.getUrl_visible());
                segunda.setResizable(false);

                if (c != null) {
                    textfieldCabecera.setText(c.getNombre());
                    textfieldPie.setText(c.getInfoAdicional());
                    nombre.setText(c.getUrl_visible());
                    nombre.setEditable(false);
                    if (c.getHabilitada() == null) {
                        c.setHabilitada(false);

                    }
                    habilitado.setSelected(c.getHabilitada());
                    if (c.isOpcional() != null && c.isOpcional()) {
                        comboTipoCapa.setSelectedIndex(1);
                    } else {
                        comboTipoCapa.setSelectedIndex(0);
                    }
                }

                if (c.getId() == null) {
                    habilitado.setSelected(true);
                    comboTipoCapa.setSelectedIndex(1);
                }

                habilitado.setEnabled(true);
                if (c == null || c.getId() == null) {
                    textfieldCabecera.setEditable(true);
                } else {
                    textfieldCabecera.setEditable(false);
                }

                cambios = false;

                segunda.pack();
                segunda.setLocationRelativeTo(null);
                segunda.setVisible(true);
                return segunda;
            }
            return null;
        }

        class SiguienteActionListener implements ActionListener {

            private final JTextField url;
            private final JDialog dialog;
            private final JLabel icono;
            private final JButton siguiente;

            public SiguienteActionListener(JTextField url, JDialog dialog, JLabel icono, JButton siguiente) {
                this.url = url;
                this.dialog = dialog;
                this.icono = icono;
                this.siguiente = siguiente;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                final CapaInformacion ci = new CapaInformacion();
                ci.setUrl(url.getText());
                ci.setCapas(new HashSet<Capa>());
                SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {

                    private List<Capa> res = new LinkedList<Capa>();
                    private String service = "WMS";
                    private String png = null;
                    private Map<String, Boolean> transparentes = new HashMap<String, Boolean>();
                    private ArrayList<String> errorStack = new ArrayList<String>();
                    private Boolean goOn = true;

                    @SuppressWarnings(value = "unchecked")
                    @Override
                    protected Object doInBackground() throws Exception {
                        try {
                            final String url2 = ci.getUrl();
                            WMSClient client = new WMSClient(url2);
                            client.connect(new ICancellable() {

                                @Override
                                public boolean isCanceled() {
                                    return false;
                                }

                                @Override
                                public Object getID() {
                                    return System.currentTimeMillis();
                                }
                            });

                            version = client.getVersion();

                            for (final String s : client.getLayerNames()) {
                                WMSLayer layer = client.getLayer(s);
                                // this.service =
                                // client.getServiceName();
                                final Vector allSrs = layer.getAllSrs();
                                boolean epsg = (allSrs != null) ? allSrs.contains("EPSG:4326") : false;
                                final Vector formats = client.getFormats();
                                if (formats.contains("image/png")) {
                                    png = "image/png";
                                } else if (formats.contains("IMAGE/PNG")) {
                                    png = "IMAGE/PNG";
                                } else if (formats.contains("png")) {
                                    png = "png";
                                } else if (formats.contains("PNG")) {
                                    png = "PNG";
                                }
                                boolean image = png != null;
                                if (png == null) {
                                    png = "IMAGE/PNG";
                                }
                                if (epsg && image) {
                                    boolean hasTransparency = layer.hasTransparency();
                                    this.transparentes.put(s, hasTransparency);
                                    Capa capa = new Capa();
                                    capa.setCapaInformacion(ci);
                                    if (layer.getStyles().size() > 0) {
                                        capa.setEstilo(((WMSStyle) layer.getStyles().get(0)).getName());
                                    }
                                    capa.setNombre(layer.getTitle());
                                    capa.setTitulo(s);
                                    res.add(capa);
                                    if (!hasTransparency) {
                                        errorStack.add(i18n.getString(Locale.ROOT,
                                                "admin.capas.nueva.error.capaNoTransparente",
                                                layer.getTitle()));
                                    }
                                } else {
                                    String error = "";
                                    // if (opaque)
                                    // error += "<li>Es opaca</li>";
                                    if (!image) {
                                        error += i18n.getString("admin.capas.nueva.error.formatoPNG");
                                    }
                                    if (!epsg) {
                                        error += i18n.getString("admin.capas.nueva.error.projeccion");
                                    }
                                    final String cadena = i18n.getString(Locale.ROOT,
                                            "admin.capas.nueva.error.errorCapa", new Object[] { s, error });
                                    errorStack.add(cadena);
                                }
                            }
                        } catch (final Throwable t) {
                            log.error("Error al parsear el WMS", t);
                            goOn = false;
                            icono.setIcon(LogicConstants.getIcon("48x48_transparente"));

                            JOptionPane.showMessageDialog(dialog,
                                    i18n.getString("admin.capas.nueva.error.errorParseoWMS"));

                            siguiente.setEnabled(true);
                        }
                        return null;
                    }

                    @Override
                    protected void done() {
                        super.done();
                        if (goOn) {

                            dialog.dispose();
                            ci.setUrl_visible(ci.getUrl());
                            final JFrame frame = getDialog(ci, res.toArray(new Capa[0]), service, transparentes,
                                    png);
                            if (!errorStack.isEmpty()) {
                                String error = "<html>";
                                for (final String s : errorStack) {
                                    error += s + "<br/>";
                                }
                                error += "</html>";
                                final String errorString = error;
                                SwingUtilities.invokeLater(new Runnable() {

                                    @Override
                                    public void run() {
                                        JOptionPane.showMessageDialog(frame, errorString);
                                    }
                                });
                            }
                        }
                    }
                };
                sw.execute();
                icono.setIcon(LogicConstants.getIcon("anim_conectando"));
                icono.repaint();
                siguiente.setEnabled(false);
            }
        }
    };

    return action;
}

From source file:com.gargoylesoftware.htmlunit.util.EncodingSniffer.java

/**
 * Attempts to sniff an encoding from the specified HTTP headers.
 *
 * @param headers the HTTP headers to examine
 * @return the encoding sniffed from the specified HTTP headers, or {@code null} if the encoding
 *         could not be determined/*from w w  w  .ja va 2  s. c  o m*/
 */
static String sniffEncodingFromHttpHeaders(final List<NameValuePair> headers) {
    String encoding = null;
    for (final NameValuePair pair : headers) {
        final String name = pair.getName();
        if ("content-type".equalsIgnoreCase(name)) {
            final String value = pair.getValue();
            encoding = extractEncodingFromContentType(value);
            if (encoding != null) {
                encoding = encoding.toUpperCase(Locale.ROOT);
                break;
            }
        }
    }
    if (encoding != null && LOG.isDebugEnabled()) {
        LOG.debug("Encoding found in HTTP headers: '" + encoding + "'.");
    }
    return encoding;
}

From source file:org.elasticsearch.client.RestClient.java

private static HttpRequestBase createHttpRequest(String method, URI uri, HttpEntity entity) {
    switch (method.toUpperCase(Locale.ROOT)) {
    case HttpDeleteWithEntity.METHOD_NAME:
        return addRequestBody(new HttpDeleteWithEntity(uri), entity);
    case HttpGetWithEntity.METHOD_NAME:
        return addRequestBody(new HttpGetWithEntity(uri), entity);
    case HttpHead.METHOD_NAME:
        return addRequestBody(new HttpHead(uri), entity);
    case HttpOptions.METHOD_NAME:
        return addRequestBody(new HttpOptions(uri), entity);
    case HttpPatch.METHOD_NAME:
        return addRequestBody(new HttpPatch(uri), entity);
    case HttpPost.METHOD_NAME:
        HttpPost httpPost = new HttpPost(uri);
        addRequestBody(httpPost, entity);
        return httpPost;
    case HttpPut.METHOD_NAME:
        return addRequestBody(new HttpPut(uri), entity);
    case HttpTrace.METHOD_NAME:
        return addRequestBody(new HttpTrace(uri), entity);
    default://from   w  w w . j  a va  2s  . co  m
        throw new UnsupportedOperationException("http method not supported: " + method);
    }
}

From source file:com.gargoylesoftware.htmlunit.activex.javascript.msxml.XMLHTTPRequest.java

/**
 * @param name header name (MUST be lower-case for performance reasons)
 * @param value header value/*from  w  w w .ja va 2s . c o m*/
 */
private boolean isPreflightHeader(final String name, final String value) {
    if ("content-type".equals(name)) {
        final String lcValue = value.toLowerCase(Locale.ROOT);
        if (FormEncodingType.URL_ENCODED.getName().equals(lcValue)
                || FormEncodingType.MULTIPART.getName().equals(lcValue) || "text/plain".equals(lcValue)
                || lcValue.startsWith("text/plain;charset=")) {
            return false;
        }
        return true;
    }
    if ("accept".equals(name) || "accept-language".equals(name) || "content-language".equals(name)
            || "referer".equals(name) || "accept-encoding".equals(name) || "origin".equals(name)) {
        return false;
    }
    return true;
}

From source file:org.elasticsearch.xpack.ml.integration.MlJobIT.java

public void testMultiIndexDelete() throws Exception {
    String jobId = "multi-index-delete-job";
    String indexName = AnomalyDetectorsIndexFields.RESULTS_INDEX_PREFIX
            + AnomalyDetectorsIndexFields.RESULTS_INDEX_DEFAULT;
    createFarequoteJob(jobId);/* ww w  . j  a v a  2  s.  c o  m*/

    Response response = client().performRequest("put", indexName + "-001");
    assertEquals(200, response.getStatusLine().getStatusCode());

    response = client().performRequest("put", indexName + "-002");
    assertEquals(200, response.getStatusLine().getStatusCode());

    response = client().performRequest("get", "_cat/indices");
    assertEquals(200, response.getStatusLine().getStatusCode());
    String responseAsString = responseEntityToString(response);
    assertThat(responseAsString, containsString(indexName));
    assertThat(responseAsString, containsString(indexName + "-001"));
    assertThat(responseAsString, containsString(indexName + "-002"));

    // Add some documents to each index to make sure the DBQ clears them out
    String recordResult = String.format(Locale.ROOT,
            "{\"job_id\":\"%s\", \"timestamp\": \"%s\", \"bucket_span\":%d, \"result_type\":\"record\"}", jobId,
            123, 1);
    client().performRequest("put", indexName + "/doc/" + 123, Collections.singletonMap("refresh", "true"),
            new StringEntity(recordResult, ContentType.APPLICATION_JSON));
    client().performRequest("put", indexName + "-001/doc/" + 123, Collections.singletonMap("refresh", "true"),
            new StringEntity(recordResult, ContentType.APPLICATION_JSON));
    client().performRequest("put", indexName + "-002/doc/" + 123, Collections.singletonMap("refresh", "true"),
            new StringEntity(recordResult, ContentType.APPLICATION_JSON));

    // Also index a few through the alias for the first job
    client().performRequest("put", indexName + "/doc/" + 456, Collections.singletonMap("refresh", "true"),
            new StringEntity(recordResult, ContentType.APPLICATION_JSON));

    client().performRequest("post", "_refresh");

    // check for the documents
    response = client().performRequest("get", indexName + "/_count");
    assertEquals(200, response.getStatusLine().getStatusCode());
    responseAsString = responseEntityToString(response);
    assertThat(responseAsString, containsString("\"count\":2"));

    response = client().performRequest("get", indexName + "-001/_count");
    assertEquals(200, response.getStatusLine().getStatusCode());
    responseAsString = responseEntityToString(response);
    assertThat(responseAsString, containsString("\"count\":1"));

    response = client().performRequest("get", indexName + "-002/_count");
    assertEquals(200, response.getStatusLine().getStatusCode());
    responseAsString = responseEntityToString(response);
    assertThat(responseAsString, containsString("\"count\":1"));

    // Delete
    response = client().performRequest("delete", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

    client().performRequest("post", "_refresh");

    // check that the indices still exist but are empty
    response = client().performRequest("get", "_cat/indices");
    assertEquals(200, response.getStatusLine().getStatusCode());
    responseAsString = responseEntityToString(response);
    assertThat(responseAsString, containsString(indexName));
    assertThat(responseAsString, containsString(indexName + "-001"));
    assertThat(responseAsString, containsString(indexName + "-002"));

    response = client().performRequest("get", indexName + "/_count");
    assertEquals(200, response.getStatusLine().getStatusCode());
    responseAsString = responseEntityToString(response);
    assertThat(responseAsString, containsString("\"count\":0"));

    response = client().performRequest("get", indexName + "-001/_count");
    assertEquals(200, response.getStatusLine().getStatusCode());
    responseAsString = responseEntityToString(response);
    assertThat(responseAsString, containsString("\"count\":0"));

    response = client().performRequest("get", indexName + "-002/_count");
    assertEquals(200, response.getStatusLine().getStatusCode());
    responseAsString = responseEntityToString(response);
    assertThat(responseAsString, containsString("\"count\":0"));

    expectThrows(ResponseException.class, () -> client().performRequest("get",
            MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_stats"));
}

From source file:org.matsim.contrib.parking.parkingchoice.lib.GeneralLib.java

public static Matrix<String> readStringMatrix(String fileName, String delim, StringMatrixFilter filter) {
    Matrix<String> matrix = new Matrix<String>();

    try {//  www .j  a  va  2 s .  c  o m

        // FileReader fr = new FileReader(fileName);

        FileInputStream fis = new FileInputStream(fileName);
        InputStreamReader isr = new InputStreamReader(fis, "ISO-8859-1");

        BufferedReader br = null;
        if (fileName.toLowerCase(Locale.ROOT).endsWith(".gz")) {
            br = IOUtils.getBufferedReader(fileName);
        } else {
            br = new BufferedReader(isr);
        }

        String line;
        StringTokenizer tokenizer;
        line = br.readLine();
        while (line != null) {
            ArrayList<String> row = new ArrayList<String>();

            if (delim == null) {
                tokenizer = new StringTokenizer(line);

                while (tokenizer.hasMoreTokens()) {
                    row.add(tokenizer.nextToken());
                }
            } else {
                String[] split = line.split(delim, -1);

                for (String s : split) {
                    row.add(s);
                }
            }

            if (filter != null && filter.removeLine(line)) {

            } else {
                matrix.addRow(row);
            }

            line = br.readLine();
        }
    } catch (Exception e) {
        e.printStackTrace();

        throw new Error("Error reading the file: " + fileName);
    }

    return matrix;
}

From source file:com.gargoylesoftware.htmlunit.activex.javascript.msxml.XMLHTTPRequest.java

/**
 * Not all request headers can be set from JavaScript.
 * @see <a href="http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method">W3C doc</a>
 * @param name the header name//from  w w w  .j  a v  a2  s.  c o  m
 * @return {@code true} if the header can be set from JavaScript
 */
static boolean isAuthorizedHeader(final String name) {
    final String nameLowerCase = name.toLowerCase(Locale.ROOT);
    if (PROHIBITED_HEADERS_.contains(nameLowerCase)) {
        return false;
    } else if (nameLowerCase.startsWith("proxy-") || nameLowerCase.startsWith("sec-")) {
        return false;
    }
    return true;
}