Example usage for java.lang Throwable getLocalizedMessage

List of usage examples for java.lang Throwable getLocalizedMessage

Introduction

In this page you can find the example usage for java.lang Throwable getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:com.alkacon.opencms.formgenerator.CmsForm.java

/**
 * Resolves the value of a dynamic field.<p>
 * //  w  ww. j  a  v a 2s  .c o  m
 * @param field the field to resolve the value for
 * 
 * @return the value of the given dynamic field
 */
protected String getDynamicFieldValue(CmsDynamicField field) {

    if (field.getResolvedValue() == null) {
        try {
            I_CmsDynamicFieldResolver resolver = (I_CmsDynamicFieldResolver) Class
                    .forName(getDynamicFieldClass()).newInstance();
            field.setResolvedValue(resolver.resolveValue(field, this));
        } catch (Throwable e) {
            field.setResolvedValue(e.getLocalizedMessage());
        }
    }
    return field.getResolvedValue();
}

From source file:com.amalto.core.delegator.IXtentisWSDelegator.java

/**
 * @param wsPutItem The record to be added/updated in MDM.
 * @return The PK of the record created/updated.
 * @throws java.rmi.RemoteException In case of server exception.
 *//*from  w  ww  . j av  a 2  s  .co m*/
@Override
public WSItemPK putItem(WSPutItem wsPutItem) throws RemoteException {
    try {
        WSDataClusterPK dataClusterPK = wsPutItem.getWsDataClusterPK();
        WSDataModelPK dataModelPK = wsPutItem.getWsDataModelPK();
        String dataClusterName = dataClusterPK.getPk();
        String dataModelName = dataModelPK.getPk();
        SaverSession session = SaverSession.newSession();
        DocumentSaver saver;
        try {
            saver = SaverHelper.saveItem(wsPutItem, session, dataClusterName, dataModelName);
        } catch (Exception e) {
            try {
                session.abort();
            } catch (Exception e1) {
                LOGGER.error("Could not abort save session.", e1); //$NON-NLS-1$
            }
            throw new RuntimeException(e);
        }
        // Cause items being saved to be committed to database.
        session.end();
        String[] savedId = saver.getSavedId();
        String savedConceptName = saver.getSavedConceptName();
        return new WSItemPK(dataClusterPK, savedConceptName, savedId);
    } catch (Exception e) {
        LOGGER.error("Error during save.", e); //$NON-NLS-1$
        // TMDM-5594: Original cause was somehow lost during serialization,implementing a workaround here
        Throwable cause = e.getCause();
        if (cause == null) {
            throw new RemoteException(e.getLocalizedMessage(), e);
        } else {
            throw new RemoteException((cause.getCause() == null ? cause.getLocalizedMessage()
                    : cause.getCause().getLocalizedMessage()), e);
        }
    }
}

From source file:cl.gisred.android.LectorInspActivity.java

private void cerrarDialogCrear(boolean bSave, @Nullable View viewDialog) {
    final AtomicReference<String> resp = new AtomicReference<>("");

    if (bSave) {/*from  www. ja  v a2s .  co  m*/
        if (!validarVista(viewDialog)) {
            DialogoConfirmacion oDialog = new DialogoConfirmacion();
            oDialog.show(getFragmentManager(), "tagAlert");
            return;
        } else {
            switch (idResLayoutSelect) {
            case R.layout.dialog_poste:
                oLyAddGraphs = LyAddPoste;
                break;
            case R.layout.dialog_direccion:
                oLyAddGraphs = LyAddDireccion;
                break;
            case R.layout.dialog_cliente:
                oLyAddGraphs = LyAddCliente;
                break;
            case R.layout.dialog_cliente_cnr:
                oLyAddGraphs = LyAddClienteCnr;
                break;
            }

            if (oLyAddGraphs != null) {
                View oView = getLayoutValidate(viewDialog);
                Util oUtil = new Util(oUbicacion);

                ArrayList<Map<String, Object>> oAttrToSave = oUtil.getAttrAddByView(oView, idResLayoutSelect,
                        empresa);

                Map<String, Object> attributes = oAttrToSave.get(0);
                Graphic newFeatureGraphic = new Graphic(oUbicacion, null, attributes);
                Graphic[] adds = { newFeatureGraphic };

                if (idResLayoutSelect == R.layout.dialog_cliente_cnr
                        || idResLayoutSelect == R.layout.dialog_cliente) {
                    addsUnion = Util.addAttrUnionPoint(oAttrToSave, oUbicacion);
                }

                oLyAddGraphs.applyEdits(adds, null, null, new CallbackListener<FeatureEditResult[][]>() {

                    @Override
                    public void onCallback(FeatureEditResult[][] featureEditResults) {
                        if (featureEditResults[0] != null) {
                            if (featureEditResults[0][0] != null && featureEditResults[0][0].isSuccess()) {

                                resp.set(
                                        "Guardado Correctamente Id: " + featureEditResults[0][0].getObjectId());

                                if (idResLayoutSelect == R.layout.dialog_cliente_cnr
                                        || idResLayoutSelect == R.layout.dialog_cliente)
                                    LyAddUnion.applyEdits(addsUnion, null, null, callBackUnion());

                                runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        Util.showConfirmation(LectorInspActivity.this, resp.get());
                                    }
                                });
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        resp.set("Error al grabar: " + throwable.getLocalizedMessage());
                        Log.w("onError", resp.get());

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(LectorInspActivity.this, resp.get(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                });
            }
        }
    } else {
        resp.set("Cancelado");
        Toast.makeText(LectorInspActivity.this, resp.get(), Toast.LENGTH_LONG).show();
    }

    bMapTap = false;

    if (mBusquedaLayer != null && myMapView.getLayerByID(mBusquedaLayer.getID()) != null)
        myMapView.removeLayer(mBusquedaLayer);

    if (mUbicacionLayer != null && myMapView.getLayerByID(mUbicacionLayer.getID()) != null)
        myMapView.removeLayer(mUbicacionLayer);

    if (mSeleccionLayer != null && myMapView.getLayerByID(mSeleccionLayer.getID()) != null)
        myMapView.removeLayer(mSeleccionLayer);

    oUbicacion = null;
    if (bVerCapas)
        toogleCapas(fabVerCapas);
    //setLayerAddToggle(false);
    if (bIngCliente)
        menuMultipleActions.setVisibility(View.VISIBLE);
    fabShowDialog.setVisibility(View.GONE);
    dialogCrear.dismiss();
    if (oLyAddGraphs != null)
        oLyAddGraphs.setVisible(true);
}

From source file:org.polymap.core.project.operations.NewLayerOperation.java

public IStatus doExecute(final IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
    try {/* w w  w. j a va 2s  . c  o m*/
        monitor.beginTask(getLabel(), 5);
        ProjectRepository repo = ProjectRepository.instance();
        layer = repo.newEntity(ILayer.class, null);

        // default ACL
        for (Principal principal : Polymap.instance().getPrincipals()) {
            layer.addPermission(principal.getName(), AclPermission.ALL);
        }

        layer.setLabel(geores.getTitle());
        layer.setOrderKey(100);
        layer.setOpacity(100);
        layer.setGeoResource(geores);
        layer.setVisible(true);

        map.addLayer(layer);

        // find highest order
        int highestOrder = 100;
        for (ILayer cursor : layer.getMap().getLayers()) {
            highestOrder = Math.max(highestOrder, cursor.getOrderKey());
        }
        layer.setOrderKey(highestOrder + 1);

        // Shapefile CRS in checked in ShapeCRSOperationConcern

        // transformed layerBBox
        ReferencedEnvelope layerBBox = SetLayerBoundsOperation.obtainBoundsFromResources(layer, map.getCRS(),
                monitor);
        if (layerBBox != null && !layerBBox.isNull() && layerBBox.getMaxX() < Double.POSITIVE_INFINITY) {
            monitor.subTask(Messages.get("NewLayerOperation_transforming"));
            if (!layerBBox.getCoordinateReferenceSystem().equals(map.getCRS())) {
                try {
                    layerBBox = layerBBox.transform(map.getCRS(), true);
                } catch (Throwable e) {
                    log.warn("", e);
                }
            }
            log.debug("transformed: " + layerBBox);
            monitor.worked(1);
        }

        // no max extent -> set 
        monitor.subTask(Messages.get("NewLayerOperation_checkingMaxExtent"));
        if (map.getMaxExtent() == null) {
            if (layerBBox != null && !layerBBox.isNull() && !layerBBox.isEmpty()) {
                log.info("### Map: maxExtent= " + layerBBox);
                map.setMaxExtent(layerBBox);
                // XXX set map status
            } else {
                Display display = (Display) info.getAdapter(Display.class);
                display.syncExec(new Runnable() {
                    public void run() {
                        Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
                        MessageBox box = new MessageBox(shell, SWT.OK);
                        box.setText("No layer bounds.");
                        box.setMessage(
                                "Layer has no bounding box.\n Max extent of the map could not be set.\nThis may lead to unspecified map behaviour.");
                        box.open();
                    }
                });
            }
        }
        // check if max extent contains layer
        else {
            try {
                if (!layerBBox.isNull() && layerBBox.getMaxX() < Double.POSITIVE_INFINITY
                        && !map.getMaxExtent().contains((BoundingBox) layerBBox)) {
                    ReferencedEnvelope bbox = new ReferencedEnvelope(layerBBox);
                    bbox.expandToInclude(map.getMaxExtent());
                    final ReferencedEnvelope newMaxExtent = bbox;

                    Display display = (Display) info.getAdapter(Display.class);
                    display.syncExec(new Runnable() {
                        public void run() {
                            Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
                            MessageBox box = new MessageBox(shell, SWT.YES | SWT.NO);
                            box.setText(Messages.get("NewLayerOperation_BBoxDialog_title"));
                            box.setMessage(Messages.get("NewLayerOperation_BBoxDialog_msg"));
                            int answer = box.open();
                            if (answer == SWT.YES) {
                                map.setMaxExtent(newMaxExtent);
                            }
                        }
                    });
                }
            } catch (Exception e) {
                log.warn(e.getLocalizedMessage(), e);
            }
        }
        monitor.worked(1);
    } catch (Throwable e) {
        throw new ExecutionException(e.getMessage(), e);
    }
    return Status.OK_STATUS;
}

From source file:cl.gisred.android.CatastroActivity.java

private void cerrarFormCrear(boolean bSave, View v) {
    if (bSave) {//from ww  w.j  av a  2  s.  co  m

        final AtomicReference<String> resp = new AtomicReference<>("");

        if (!validarForm(v)) {
            DialogoConfirmacion oDialog = new DialogoConfirmacion();
            oDialog.show(getFragmentManager(), "tagAlert");
            return;
        } else {
            View vAction = getLayoutValidate(v);
            Map<String, Object> objectMap = new HashMap<>();
            for (View view : vAction.getTouchables()) {

                if (view.getClass().getGenericSuperclass().equals(EditText.class)) {
                    EditText oText = (EditText) view;

                    if (oText.getId() == R.id.txtProducto) {
                        String oVal = (oText.getText().toString().isEmpty()) ? "0" : oText.getText().toString();
                        objectMap.put("producto", oVal);
                    }
                    if (oText.getId() == R.id.txtPoste)
                        objectMap.put("poste", oText.getText().toString());
                    if (oText.getId() == R.id.txtDireccion)
                        objectMap.put("direccion", oText.getText().toString());

                } else if (view.getClass().getGenericSuperclass().equals(Spinner.class)) {
                    Spinner oSpinner = (Spinner) view;
                    String sValue = oSpinner.getSelectedItem().toString();

                    if (oSpinner.getId() == R.id.spinnerEstado)
                        objectMap.put("estado", sValue);
                    else if (oSpinner.getId() == R.id.spinnerTipoEdif)
                        objectMap.put("tipo_edificacion", sValue);
                }
            }

            Graphic newFeatureGraphic = new Graphic(oUbicacion, null, objectMap);
            Graphic[] adds = { newFeatureGraphic };
            LyAddCatastro.applyEdits(adds, null, null, new CallbackListener<FeatureEditResult[][]>() {
                @Override
                public void onCallback(FeatureEditResult[][] featureEditResults) {
                    if (featureEditResults[0] != null) {
                        if (featureEditResults[0][0] != null && featureEditResults[0][0].isSuccess()) {

                            resp.set("Guardado Correctamente Id: " + featureEditResults[0][0].getObjectId());

                            runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    Util.showConfirmation(CatastroActivity.this, resp.get());
                                }
                            });
                        }
                    }
                }

                @Override
                public void onError(Throwable throwable) {
                    resp.set("Error al ingresar: " + throwable.getLocalizedMessage());
                    Log.w("onError", resp.get());

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(CatastroActivity.this, resp.get(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        }
    }

    bMapTap = false;
    oUbicacion = null;

    if (mBusquedaLayer != null && myMapView.getLayerByID(mBusquedaLayer.getID()) != null)
        myMapView.removeLayer(mBusquedaLayer);

    if (mUbicacionLayer != null && myMapView.getLayerByID(mUbicacionLayer.getID()) != null)
        myMapView.removeLayer(mUbicacionLayer);

    if (mSeleccionLayer != null && myMapView.getLayerByID(mSeleccionLayer.getID()) != null)
        myMapView.removeLayer(mSeleccionLayer);

    if (bVerCapas)
        toogleCapas(fabVerCapas);

    menuMultipleActions.setVisibility(View.VISIBLE);
    menuCatastroActions.setVisibility(View.VISIBLE);
    fabShowForm.setVisibility(View.GONE);
    formCrear.dismiss();

    if (LyAddCatastro != null)
        LyAddCatastro.setVisible(true);
}

From source file:cl.gisred.android.CatastroActivity.java

private void cerrarDialogCrear(boolean bSave, @Nullable View viewDialog) {
    final AtomicReference<String> resp = new AtomicReference<>("");

    if (bSave) {/*from  ww w  .j  a  va 2s  . c  o  m*/
        if (!validarVista(viewDialog)) {
            DialogoConfirmacion oDialog = new DialogoConfirmacion();
            oDialog.show(getFragmentManager(), "tagAlert");
            return;
        } else {
            switch (idResLayoutSelect) {
            case R.layout.dialog_poste:
                oLyAddGraphs = LyAddPoste;
                break;
            case R.layout.dialog_direccion:
                oLyAddGraphs = LyAddDireccion;
                break;
            case R.layout.dialog_cliente:
                oLyAddGraphs = LyAddCliente;
                break;
            case R.layout.dialog_cliente_cnr:
                oLyAddGraphs = LyAddClienteCnr;
                break;
            }

            if (oLyAddGraphs != null) {
                View oView = getLayoutValidate(viewDialog);
                Util oUtil = new Util(oUbicacion);

                ArrayList<Map<String, Object>> oAttrToSave = oUtil.getAttrAddByView(oView, idResLayoutSelect,
                        empresa);

                Map<String, Object> attributes = oAttrToSave.get(0);
                Graphic newFeatureGraphic = new Graphic(oUbicacion, null, attributes);
                Graphic[] adds = { newFeatureGraphic };

                if (idResLayoutSelect == R.layout.dialog_cliente_cnr
                        || idResLayoutSelect == R.layout.dialog_cliente) {
                    addsUnion = Util.addAttrUnionPoint(oAttrToSave, oUbicacion);
                }

                oLyAddGraphs.applyEdits(adds, null, null, new CallbackListener<FeatureEditResult[][]>() {

                    @Override
                    public void onCallback(FeatureEditResult[][] featureEditResults) {
                        if (featureEditResults[0] != null) {
                            if (featureEditResults[0][0] != null && featureEditResults[0][0].isSuccess()) {

                                resp.set(
                                        "Guardado Correctamente Id: " + featureEditResults[0][0].getObjectId());

                                if (idResLayoutSelect == R.layout.dialog_cliente_cnr
                                        || idResLayoutSelect == R.layout.dialog_cliente)
                                    LyAddUnion.applyEdits(addsUnion, null, null, callBackUnion());

                                runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        Util.showConfirmation(CatastroActivity.this, resp.get());
                                    }
                                });
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        resp.set("Error al grabar: " + throwable.getLocalizedMessage());
                        Log.w("onError", resp.get());

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(CatastroActivity.this, resp.get(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                });
            }
        }
    } else {
        resp.set("Cancelado");
        Toast.makeText(CatastroActivity.this, resp.get(), Toast.LENGTH_LONG).show();
    }

    bMapTap = false;

    if (mBusquedaLayer != null && myMapView.getLayerByID(mBusquedaLayer.getID()) != null)
        myMapView.removeLayer(mBusquedaLayer);

    if (mUbicacionLayer != null && myMapView.getLayerByID(mUbicacionLayer.getID()) != null)
        myMapView.removeLayer(mUbicacionLayer);

    if (mSeleccionLayer != null && myMapView.getLayerByID(mSeleccionLayer.getID()) != null)
        myMapView.removeLayer(mSeleccionLayer);

    oUbicacion = null;
    if (bVerCapas)
        toogleCapas(fabVerCapas);
    //setLayerAddToggle(false);
    menuMultipleActions.setVisibility(View.VISIBLE);
    menuCatastroActions.setVisibility(View.VISIBLE);
    fabShowDialog.setVisibility(View.GONE);
    dialogCrear.dismiss();
    if (oLyAddGraphs != null)
        oLyAddGraphs.setVisible(true);
}

From source file:cl.gisred.android.MapsActivity.java

private void cerrarDialogCrear(boolean bSave, @Nullable View viewDialog) {
    final AtomicReference<String> resp = new AtomicReference<>("");

    if (bSave) {// w  w w  .j  av a 2s.co m
        if (!validarVista(viewDialog)) {
            DialogoConfirmacion oDialog = new DialogoConfirmacion();
            oDialog.show(getFragmentManager(), "tagAlert");
            return;
        } else {
            switch (idResLayoutSelect) {
            case R.layout.dialog_poste:
                oLyAddGraphs = LyAddPoste;
                break;
            case R.layout.dialog_direccion:
                oLyAddGraphs = LyAddDireccion;
                break;
            case R.layout.dialog_cliente:
                oLyAddGraphs = LyAddCliente;
                break;
            case R.layout.dialog_cliente_cnr:
                oLyAddGraphs = LyAddClienteCnr;
                break;
            }

            if (oLyAddGraphs != null) {
                View oView = getLayoutValidate(viewDialog);
                Util oUtil = new Util(oUbicacion);

                ArrayList<Map<String, Object>> oAttrToSave = oUtil.getAttrAddByView(oView, idResLayoutSelect,
                        empresa);

                Map<String, Object> attributes = oAttrToSave.get(0);
                Graphic newFeatureGraphic = new Graphic(oUbicacion, null, attributes);
                Graphic[] adds = { newFeatureGraphic };

                if (idResLayoutSelect == R.layout.dialog_cliente_cnr
                        || idResLayoutSelect == R.layout.dialog_cliente) {
                    addsUnion = Util.addAttrUnionPoint(oAttrToSave, oUbicacion);
                }

                oLyAddGraphs.applyEdits(adds, null, null, new CallbackListener<FeatureEditResult[][]>() {

                    @Override
                    public void onCallback(FeatureEditResult[][] featureEditResults) {
                        if (featureEditResults[0] != null) {
                            if (featureEditResults[0][0] != null && featureEditResults[0][0].isSuccess()) {

                                resp.set(
                                        "Guardado Correctamente Id: " + featureEditResults[0][0].getObjectId());

                                if (idResLayoutSelect == R.layout.dialog_cliente_cnr
                                        || idResLayoutSelect == R.layout.dialog_cliente)
                                    LyAddUnion.applyEdits(addsUnion, null, null, callBackUnion());

                                runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        Util.showConfirmation(MapsActivity.this, resp.get());
                                    }
                                });
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        resp.set("Error al grabar: " + throwable.getLocalizedMessage());
                        Log.w("onError", resp.get());

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(MapsActivity.this, resp.get(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                });
            }
        }
    } else {
        resp.set("Cancelado");
        Toast.makeText(MapsActivity.this, resp.get(), Toast.LENGTH_LONG).show();
    }

    bMapTap = false;

    if (mBusquedaLayer != null && myMapView.getLayerByID(mBusquedaLayer.getID()) != null)
        myMapView.removeLayer(mBusquedaLayer);

    if (mUbicacionLayer != null && myMapView.getLayerByID(mUbicacionLayer.getID()) != null)
        myMapView.removeLayer(mUbicacionLayer);

    if (mSeleccionLayer != null && myMapView.getLayerByID(mSeleccionLayer.getID()) != null)
        myMapView.removeLayer(mSeleccionLayer);

    oUbicacion = null;
    if (bVerCapas)
        toogleCapas(fabVerCapas);
    //setLayerAddToggle(false);
    menuMultipleActions.setVisibility(View.VISIBLE);
    fabShowDialog.setVisibility(View.GONE);
    dialogCrear.dismiss();
    if (oLyAddGraphs != null)
        oLyAddGraphs.setVisible(true);
}

From source file:org.opencms.importexport.CmsImportVersion7.java

/**
 * Creates a new additional information entry for the current user.<p>
 * /*from   w w  w  .  jav a 2 s  .  c  o m*/
 * @param infoName the name of the additional information entry
 * @param infoType the type of the additional information entry
 * @param infoValue the value of the additional information entry
 */
public void importUserInfo(String infoName, String infoType, String infoValue) {

    if (m_userInfos == null) {
        m_userInfos = new HashMap();
    }
    try {
        m_userInfos.put(infoName, CmsDataTypeUtil.dataImport(infoValue, infoType));
    } catch (Throwable e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
}

From source file:org.opencms.db.generic.CmsProjectDriver.java

/**
 * @see org.opencms.db.I_CmsProjectDriver#log(org.opencms.db.CmsDbContext, java.util.List)
 *//*from  w  ww.  j av  a2s.  c  o  m*/
public void log(CmsDbContext dbc, List<CmsLogEntry> logEntries) throws CmsDbSqlException {

    Connection conn = null;
    PreparedStatement stmt = null;

    try {
        conn = m_sqlManager.getConnection(dbc);
        stmt = m_sqlManager.getPreparedStatement(conn, "C_LOG_CREATE_5");

        for (CmsLogEntry logEntry : logEntries) {
            stmt.setString(1, logEntry.getUserId().toString());
            stmt.setLong(2, logEntry.getDate());
            stmt.setString(3, logEntry.getStructureId() == null ? null : logEntry.getStructureId().toString());
            stmt.setInt(4, logEntry.getType().getId());
            stmt.setString(5, CmsStringUtil.arrayAsString(logEntry.getData(), "|"));
            try {
                stmt.executeUpdate();
            } catch (SQLException e) {
                // ignore, most likely a duplicate entry
                LOG.debug(Messages.get()
                        .container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)).key(), e);
            }
        }
    } catch (SQLException e) {
        throw new CmsDbSqlException(
                Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e);
    } finally {
        try {
            m_sqlManager.closeAll(dbc, conn, stmt, null);
        } catch (Throwable t) {
            // this could happen during shutdown
            LOG.debug(t.getLocalizedMessage(), t);
        }
    }
}

From source file:org.apache.usergrid.android.sdk.UGClient.java

/**
 *  Forms and initiates a raw synchronous http request and processes the response.
 *
 *  @param  httpMethod the HTTP method in the format: 
 *      HTTP_METHOD_<method_name> (e.g. HTTP_METHOD_POST)
 *  @param  params the URL parameters to append to the request URL
 *  @param  data the body of the request
 *  @param  segments  additional URL path segments to append to the request URL 
 *  @return  ApiResponse object//from w  w w  .j a v a  2  s  .  c  o  m
 */
public ApiResponse doHttpRequest(String httpMethod, Map<String, Object> params, Object data,
        String... segments) {

    ApiResponse response = null;
    OutputStream out = null;
    InputStream in = null;
    HttpURLConnection conn = null;

    String urlAsString = path(apiUrl, segments);

    try {
        String contentType = "application/json";
        if (httpMethod.equals(HTTP_METHOD_POST) && isEmpty(data) && !isEmpty(params)) {
            data = encodeParams(params);
            contentType = "application/x-www-form-urlencoded";
        } else {
            urlAsString = addQueryParams(urlAsString, params);
        }

        //logTrace("Invoking " + httpMethod + " to '" + urlAsString + "'");

        URL url = new URL(urlAsString);
        conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod(httpMethod);
        conn.setRequestProperty("Content-Type", contentType);
        conn.setUseCaches(false);

        if ((accessToken != null) && (accessToken.length() > 0)) {
            String authStr = "Bearer " + accessToken;
            conn.setRequestProperty("Authorization", authStr);
        }

        conn.setDoInput(true);

        if (httpMethod.equals(HTTP_METHOD_POST) || httpMethod.equals(HTTP_METHOD_PUT)) {
            if (isEmpty(data)) {
                data = JsonNodeFactory.instance.objectNode();
            }

            String dataAsString = null;

            if ((data != null) && (!(data instanceof String))) {
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
                dataAsString = objectMapper.writeValueAsString(data);
            } else {
                dataAsString = (String) data;
            }

            //logTrace("Posting/putting data: '" + dataAsString + "'");

            byte[] dataAsBytes = dataAsString.getBytes();

            conn.setRequestProperty("Content-Length", Integer.toString(dataAsBytes.length));
            conn.setDoOutput(true);

            out = conn.getOutputStream();
            out.write(dataAsBytes);
            out.flush();
            out.close();
            out = null;
        }

        in = conn.getInputStream();
        if (in != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder sb = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append('\n');
            }

            String responseAsString = sb.toString();

            //logTrace("response from server: '" + responseAsString + "'");
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            response = (ApiResponse) objectMapper.readValue(responseAsString, ApiResponse.class);
            response.setRawResponse(responseAsString);

            response.setUGClient(this);
        } else {
            response = null;
            logTrace("no response body from server");
        }

        //final int responseCode = conn.getResponseCode();
        //logTrace("responseCode from server = " + responseCode);
    } catch (Exception e) {
        logError("Error " + httpMethod + " to '" + urlAsString + "'");
        if (e != null) {
            e.printStackTrace();
            logError(e.getLocalizedMessage());
        }
        response = null;
    } catch (Throwable t) {
        logError("Error " + httpMethod + " to '" + urlAsString + "'");
        if (t != null) {
            t.printStackTrace();
            logError(t.getLocalizedMessage());
        }
        response = null;
    } finally {
        try {
            if (out != null) {
                out.close();
            }

            if (in != null) {
                in.close();
            }

            if (conn != null) {
                conn.disconnect();
            }
        } catch (Exception ignored) {
        }
    }

    return response;
}