Example usage for java.lang UnsupportedOperationException getMessage

List of usage examples for java.lang UnsupportedOperationException getMessage

Introduction

In this page you can find the example usage for java.lang UnsupportedOperationException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.vuze.android.remote.fragment.TorrentListFragment.java

private void setupActionModeCallback() {
    mActionModeCallbackV7 = new Callback() {

        // Called when the action mode is created; startActionMode() was called
        @Override//from w  ww .  j a  va 2s.c o m
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {

            if (AndroidUtils.DEBUG_MENU) {
                Log.d(TAG, "onCreateActionMode");
            }

            if (mode == null && torrentListAdapter.getCheckedItemCount() == 0
                    && torrentListAdapter.getSelectedPosition() < 0) {
                return false;
            }

            Menu origMenu = menu;
            if (tb != null) {
                menu = tb.getMenu();
            }
            if (mode != null) {
                mActionMode = (mode instanceof ActionModeWrapperV7) ? mode
                        : new ActionModeWrapperV7(mode, tb, getActivity());

                mActionMode.setTitle(R.string.context_torrent_title);
            }
            ActionBarToolbarSplitter.buildActionBar(getActivity(), this, R.menu.menu_context_torrent_details,
                    menu, tb);

            TorrentDetailsFragment frag = (TorrentDetailsFragment) getActivity().getSupportFragmentManager()
                    .findFragmentById(R.id.frag_torrent_details);
            if (frag != null) {
                frag.onCreateActionMode(mode, menu);
            }

            if (sideListArea == null) {
                SubMenu subMenu = origMenu.addSubMenu(R.string.menu_global_actions);
                subMenu.setIcon(R.drawable.ic_menu_white_24dp);
                MenuItemCompat.setShowAsAction(subMenu.getItem(), MenuItemCompat.SHOW_AS_ACTION_NEVER);

                try {
                    // Place "Global" actions on top bar in collapsed menu
                    MenuInflater mi = mode == null ? getActivity().getMenuInflater() : mode.getMenuInflater();
                    mi.inflate(R.menu.menu_torrent_list, subMenu);
                    onPrepareOptionsMenu(subMenu);
                } catch (UnsupportedOperationException e) {
                    Log.e(TAG, e.getMessage());
                    menu.removeItem(subMenu.getItem().getItemId());
                }
            }

            if (AndroidUtils.usesNavigationControl()) {
                MenuItem add = origMenu.add(R.string.select_multiple_items);
                add.setCheckable(true);
                add.setChecked(torrentListAdapter.isMultiCheckMode());
                add.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        boolean turnOn = !torrentListAdapter.isMultiCheckModeAllowed();

                        torrentListAdapter.setMultiCheckModeAllowed(turnOn);
                        if (turnOn) {
                            torrentListAdapter.setMultiCheckMode(turnOn);
                            torrentListAdapter.setItemChecked(torrentListAdapter.getSelectedPosition(), true);
                        }
                        return true;
                    }
                });
            }

            return true;
        }

        // Called each time the action mode is shown. Always called after
        // onCreateActionMode, but
        // may be called multiple times if the mode is invalidated.
        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {

            if (AndroidUtils.DEBUG_MENU) {
                Log.d(TAG, "MULTI:onPrepareActionMode " + mode);
            }
            if (tb != null) {
                menu = tb.getMenu();
            }

            // Must be called first, because our drawer sets all menu items
            // visible.. :(
            getActivity().onPrepareOptionsMenu(menu);

            prepareContextMenu(menu);

            TorrentDetailsFragment frag = (TorrentDetailsFragment) getActivity().getSupportFragmentManager()
                    .findFragmentById(R.id.frag_torrent_details);
            if (frag != null) {
                frag.onPrepareActionMode(mode, menu);
            }

            AndroidUtils.fixupMenuAlpha(menu);

            return true;
        }

        // Called when the user selects a contextual menu item
        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            if (AndroidUtils.DEBUG_MENU) {
                Log.d(TAG, "onActionItemClicked " + item.getTitle());
            }

            if (TorrentListFragment.this.handleFragmentMenuItems(item.getItemId())) {
                return true;
            }
            if (getActivity().onOptionsItemSelected(item)) {
                return true;
            }
            TorrentDetailsFragment frag = (TorrentDetailsFragment) getActivity().getSupportFragmentManager()
                    .findFragmentById(R.id.frag_torrent_details);
            if (frag != null) {
                if (frag.onActionItemClicked(mode, item)) {
                    return true;
                }
            }
            return false;
        }

        // Called when the user exits the action mode
        @Override
        public void onDestroyActionMode(ActionMode mode) {
            if (AndroidUtils.DEBUG_MENU) {
                Log.d(TAG, "onDestroyActionMode. BeingReplaced?" + actionModeBeingReplaced);
            }

            mActionMode = null;

            if (!actionModeBeingReplaced) {
                listview.post(new Runnable() {
                    @Override
                    public void run() {
                        torrentListAdapter.setMultiCheckMode(false);
                        torrentListAdapter.clearChecked();
                        updateCheckedIDs();
                    }
                });

                listview.post(new Runnable() {
                    @Override
                    public void run() {
                        if (mCallback != null) {
                            mCallback.actionModeBeingReplacedDone();
                        }
                    }
                });

                listview.setLongClickable(true);
                listview.requestLayout();
                AndroidUtils.invalidateOptionsMenuHC(getActivity(), mActionMode);
            }
        }
    };
}

From source file:org.eclipse.january.dataset.MathsTest.java

@Test
public void testRemainder() {
    Dataset a, b, c = null, d = null;/* w  w  w . j av a2  s.  c  o  m*/
    Complex zv = new Complex(-3.5, 0);
    final double dv = zv.getReal();
    long start;
    int n;
    int eCount = 0;

    for (String dn : classes.keySet()) {
        final int dtype = classes.get(dn);
        Random.seed(12735L);

        for (String en : classes.keySet()) {
            final int etype = classes.get(en);

            TestUtils.verbosePrintf("%s by %s, ", dn, en);

            n = 32;
            for (int i = 0; i < SITER; i++) {
                if (dtype < Dataset.ARRAYINT8) {
                    a = Random.randn(n).imultiply(100);
                    a = a.cast(dtype);
                } else {
                    Dataset[] aa = new Dataset[ISIZEA];
                    for (int j = 0; j < ISIZEA; j++) {
                        aa[j] = Random.randn(n).imultiply(100);
                    }
                    a = DatasetUtils.cast(aa, dtype);
                }
                if (etype < Dataset.ARRAYINT8) {
                    b = Random.randn(n).imultiply(100);
                    b = b.cast(etype);
                } else {
                    Dataset[] ab = new Dataset[ISIZEB];
                    for (int j = 0; j < ISIZEB; j++) {
                        ab[j] = Random.randn(n).imultiply(100);
                    }
                    b = DatasetUtils.cast(ab, etype);
                }

                start = -System.nanoTime();
                try {
                    c = Maths.remainder(a, b);
                } catch (IllegalArgumentException e) {
                    TestUtils.verbosePrintf("Could not perform this operation: ", e.getMessage());
                    eCount++;
                    continue;
                } catch (UnsupportedOperationException ue) {
                    TestUtils.verbosePrintf("Could not perform this operation: ", ue.getMessage());
                    continue;
                }
                start += System.nanoTime();
                double ntime = ((double) start) / c.getSize();

                d = DatasetFactory.zeros(c);
                start = -System.nanoTime();
                IndexIterator ita = a.getIterator();
                IndexIterator itb = b.getIterator();
                int j = 0;
                if (dtype < Dataset.ARRAYINT8 && etype < Dataset.ARRAYINT8) {
                    while (ita.hasNext() && itb.hasNext()) {
                        d.setObjectAbs(j++, ((Number) a.getObjectAbs(ita.index)).doubleValue()
                                % ((Number) b.getObjectAbs(itb.index)).doubleValue());
                    }
                } else {
                    final double[] answer = new double[MAXISIZE];
                    final int is = d.getElementsPerItem();

                    if (a.getElementsPerItem() < is) {
                        while (ita.hasNext() && itb.hasNext()) {
                            final double xa = a.getElementDoubleAbs(ita.index);
                            for (int k = 0; k < ISIZEB; k++) {
                                answer[k] = xa % b.getElementDoubleAbs(itb.index + k);
                            }
                            d.setObjectAbs(j, answer);
                            j += is;
                        }
                    } else if (b.getElementsPerItem() < is) {
                        while (ita.hasNext() && itb.hasNext()) {
                            final double xb = b.getElementDoubleAbs(itb.index);
                            for (int k = 0; k < ISIZEA; k++) {
                                answer[k] = a.getElementDoubleAbs(ita.index + k) % xb;
                            }
                            d.setObjectAbs(j, answer);
                            j += is;
                        }
                    } else {
                        while (ita.hasNext() && itb.hasNext()) {
                            for (int k = 0; k < is; k++) {
                                answer[k] = a.getElementDoubleAbs(ita.index + k)
                                        % b.getElementDoubleAbs(itb.index + k);
                            }
                            d.setObjectAbs(j, answer);
                            j += is;
                        }
                    }
                }
                if (d == null)
                    break;
                start += System.nanoTime();
                double otime = ((double) start) / d.getSize();

                TestUtils.verbosePrintf("Time taken by rem for %s: %s; %s (%.1f%%)\n", n, otime, ntime,
                        100. * (otime - ntime) / otime);
                checkDatasets(a, b, c, d);

                n *= SSTEP;
            }
        }

        Random.seed(12735L);
        n = 32;
        TestUtils.verbosePrintf("%s by constant, ", dn);
        for (int i = 0; i < SITER; i++) {
            if (dtype < Dataset.ARRAYINT8) {
                a = Random.randn(n);
                a.imultiply(100);
                a = a.cast(dtype);
            } else {
                Dataset[] aa = new Dataset[ISIZEA];
                for (int j = 0; j < ISIZEA; j++) {
                    aa[j] = Random.randn(n).imultiply(100);
                }
                a = DatasetUtils.cast(aa, dtype);
            }

            start = -System.nanoTime();
            try {
                c = Maths.remainder(a, dv);
            } catch (IllegalArgumentException e) {
                TestUtils.verbosePrintf("Could not perform this operation: ", e.getMessage());
                eCount++;
                continue;
            } catch (UnsupportedOperationException ue) {
                TestUtils.verbosePrintf("Could not perform this operation: ", ue.getMessage());
                continue;
            }
            start += System.nanoTime();
            double ntime = ((double) start) / c.getSize();

            d = DatasetFactory.zeros(c);
            start = -System.nanoTime();
            IndexIterator ita = a.getIterator();
            int j = 0;
            if (dtype < Dataset.ARRAYINT8) {
                while (ita.hasNext()) {
                    d.setObjectAbs(j++, ((Number) a.getObjectAbs(ita.index)).doubleValue() % dv);
                }
            } else {
                final double[] answer = new double[ISIZEA];
                while (ita.hasNext()) {
                    for (int k = 0; k < ISIZEA; k++) {
                        answer[k] = a.getElementDoubleAbs(ita.index + k) % dv;
                    }
                    d.setObjectAbs(j, answer);
                    j += ISIZEA;
                }
            }
            start += System.nanoTime();
            double otime = ((double) start) / d.getSize();

            TestUtils.verbosePrintf("Time taken by rem for %s: %s; %s (%.1f%%)\n", n, otime, ntime,
                    100. * (otime - ntime) / otime);
            checkDatasets(a, dv, c, d);

            n *= SSTEP;
        }

        Random.seed(12735L);
        n = 32;
        TestUtils.verbosePrintf("constant by %s, ", dn);
        for (int i = 0; i < SITER; i++) {
            if (dtype < Dataset.ARRAYINT8) {
                a = Random.randn(n);
                a.imultiply(100);
                a = a.cast(dtype);
            } else {
                Dataset[] aa = new Dataset[ISIZEA];
                for (int j = 0; j < ISIZEA; j++) {
                    aa[j] = Random.randn(n).imultiply(100);
                }
                a = DatasetUtils.cast(aa, dtype);
            }

            start = -System.nanoTime();
            try {
                c = Maths.remainder(dv, a);
            } catch (IllegalArgumentException e) {
                TestUtils.verbosePrintf("Could not perform this operation: ", e.getMessage());
                eCount++;
                continue;
            } catch (UnsupportedOperationException ue) {
                TestUtils.verbosePrintf("Could not perform this operation: ", ue.getMessage());
                continue;
            }
            start += System.nanoTime();
            double ntime = ((double) start) / c.getSize();

            d = DatasetFactory.zeros(c);
            start = -System.nanoTime();
            IndexIterator ita = a.getIterator();
            int j = 0;
            if (dtype < Dataset.ARRAYINT8) {
                while (ita.hasNext()) {
                    d.setObjectAbs(j++, dv % ((Number) a.getObjectAbs(ita.index)).doubleValue());
                }
            } else {
                final double[] answer = new double[ISIZEA];
                while (ita.hasNext()) {
                    for (int k = 0; k < ISIZEA; k++) {
                        answer[k] = dv % a.getElementDoubleAbs(ita.index + k);
                    }
                    d.setObjectAbs(j, answer);
                    j += ISIZEA;
                }
            }
            start += System.nanoTime();
            double otime = ((double) start) / d.getSize();

            TestUtils.verbosePrintf("Time taken by rem for %s: %s; %s (%.1f%%)\n", n, otime, ntime,
                    100. * (otime - ntime) / otime);
            checkDatasets(dv, a, c, d);

            n *= SSTEP;
        }
    }

    if (eCount > 0) {
        TestUtils.verbosePrintf("Number of exceptions caught: %d\n", eCount);
    }
}

From source file:org.forgerock.openidm.provisioner.openicf.impl.OpenICFProvisionerService.java

/**
 * Gets a brief status report about the current status of this service instance.
 * <p>//from w  ww  .  java 2  s  . c om
 * An example response when the configuration is enabled
 * {@code {
 * "name" : "ldap",
 * "enabled" : true,
 * "config" : "config/provisioner.openicf/ldap"
 * "objectTypes":
 * [
 *  "group",
 *  "account"
 * ],
 * "connectorRef" :
 *  {
 *      "connectorName": "org.identityconnectors.ldap.LdapConnector",
 *      "bundleName": "org.forgerock.openicf.connectors.ldap-connector",
 *      "bundleVersion": "[1.1.0.1,1.1.2.0)"
 *  } ,
 * "ok" : true
 * }}
 *
 * An example response when the configuration is disabled
 * {@code {
 * "name": "ldap",
 * "enabled": false,
 * "config": "config/provisioner.openicf/ldap",
 * "objectTypes":
 * [
 *  "group",
 *  "account"
 * ],
 * "connectorRef":
 * {
 *      "connectorName": "org.identityconnectors.ldap.LdapConnector",
 *      "bundleName": "org.forgerock.openicf.connectors.ldap-connector",
 *      "bundleVersion": "[1.4.0.0,2.0.0.0)"
 * },
 * "error": "connector not available",
 * "ok": false
 * }}
 *
 * @param context the Context of the request requesting the status
 * @return a Map of the current status of a connector
 */
public Map<String, Object> getStatus(Context context) {
    Map<String, Object> result = new LinkedHashMap<String, Object>();
    JsonValue jv = new JsonValue(result);
    boolean ok = false;

    jv.put("name", systemIdentifier.getName());
    jv.put("enabled", jsonConfiguration.get("enabled").defaultTo(Boolean.TRUE).asBoolean());
    jv.put("config", "config/provisioner.openicf/" + factoryPid);
    jv.put("objectTypes", ConnectorUtil.getObjectTypes(jsonConfiguration).keySet());
    ConnectorReference connectorReference = ConnectorUtil.getConnectorReference(jsonConfiguration);
    if (connectorReference != null) {
        jv.put(ConnectorUtil.OPENICF_CONNECTOR_REF,
                ConnectorUtil.getConnectorKey(connectorReference.getConnectorKey()));
        ConnectorInfo connectorInfo = connectorInfoProvider.findConnectorInfo(connectorReference);
        if (connectorInfo != null) {
            jv.put("displayName", connectorInfo.getConnectorDisplayName());
        }
    }

    try {
        ConnectorFacade connectorFacade = getConnectorFacade();
        if (connectorFacade == null) {
            jv.put("error", "connector not available");
        } else {
            connectorFacade.test();
            ok = true;
        }
    } catch (UnsupportedOperationException e) {
        jv.put("error", "TEST UnsupportedOperation");
    } catch (InvalidCredentialException e) {
        jv.put("error", "Connection Error");
    } catch (Exception e) {
        jv.put("error", e.getMessage());
    }

    jv.put("ok", ok);
    return result;
}

From source file:org.geotools.imageio.GeoSpatialImageReaderTest.java

@Test
public void testReader() throws IOException {
    // Reader creation
    GeoSpatialImageReader reader = new TestGeospatialImageReader();

    reader.setInput(file);//from   w w w . ja  v a2s .c  o  m

    // Test exceptions
    // Ensure that UnsupportedOperationException is thrown
    boolean notThrown = false;
    try {
        reader.getImageMetadata(0);
        notThrown = true;
    } catch (UnsupportedOperationException e) {
    } catch (IOException e) {
        notThrown = true;
    }
    assertFalse(notThrown);
    // Reset the boolean
    notThrown = false;

    try {
        reader.getStreamMetadata();
        notThrown = true;
    } catch (UnsupportedOperationException e) {
    } catch (IOException e) {
        notThrown = true;
    }
    assertFalse(notThrown);

    // Reader Catalog
    CoverageSlicesCatalog sliceCat = reader.getCatalog();
    assertNotNull(sliceCat);

    final Transaction t = new DefaultTransaction(Long.toString(System.nanoTime()));
    try {
        String[] typeNames = sliceCat.getTypeNames();
        assertNull(typeNames);

        // create new schema 1
        final String schemaDef1 = "the_geom:Polygon,coverage:String,imageindex:Integer";
        sliceCat.createType("1", schemaDef1);
        typeNames = sliceCat.getTypeNames();
        assertNotNull(typeNames);
        assertEquals(1, typeNames.length);

        // add features to it
        SimpleFeatureType schema = DataUtilities.createType("1", schemaDef1);
        SimpleFeature feat = DataUtilities.template(schema);
        feat.setAttribute("coverage", "a");
        feat.setAttribute("imageindex", Integer.valueOf(0));
        ReferencedEnvelope referencedEnvelope = new ReferencedEnvelope(-180, 180, -90, 90,
                DefaultGeographicCRS.WGS84);
        feat.setAttribute("the_geom", GEOM_FACTORY.toGeometry(referencedEnvelope));
        sliceCat.addGranule("1", feat, t);
        t.commit();

        // Check if present

        Query q = new Query("1");
        q.setFilter(Filter.INCLUDE);
        // Get ImageIndexes
        List<Integer> indexes = reader.getImageIndex(q);
        assertNotNull(indexes);
        assertTrue(!indexes.isEmpty());
    } catch (Exception e) {
        t.rollback();
    } finally {
        if (sliceCat != null) {
            sliceCat.dispose();
        }

        t.close();

        FileUtils.deleteDirectory(parentLocation);
    }

    String auxiliaryFilesPath = "file:/path";
    reader.setAuxiliaryFilesPath(auxiliaryFilesPath);
    assertTrue(reader.getAuxiliaryFilesPath().equalsIgnoreCase(auxiliaryFilesPath));

    // Disposal
    reader.dispose();
    try {
        reader.finalize();
    } catch (Throwable e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }

}

From source file:com.evolveum.midpoint.provisioning.impl.opendj.TestOpenDj.java

@Test
public void test702ConfiguredCapabilityNoCreate() throws Exception {
    final String TEST_NAME = "test702ConfiguredCapabilityNoCreate";

    Task task = createTask(TEST_NAME);//  ww  w  .j  a va 2  s.  co  m
    OperationResult result = task.getResult();

    addResourceFromFile(new File(TEST_DIR, "/resource-opendj-no-create.xml"),
            IntegrationTestTools.CONNECTOR_LDAP_TYPE, true, result);

    try {
        PrismObject<ShadowType> shadow = parseObjectType(ACCOUNT_WILL_FILE, ShadowType.class).asPrismObject();
        provisioningService.addObject(shadow, null, null, task, result);
        AssertJUnit.fail("Expected unsupported operation exception, but haven't got one.");
    } catch (UnsupportedOperationException ex) {
        LOGGER.info("exception: {}", ex.getMessage(), ex);
        // this is expected..
    }
}

From source file:com.evolveum.midpoint.provisioning.ucf.impl.connid.ConnectorInstanceConnIdImpl.java

private void retrieveResourceSchema(List<QName> generateObjectClasses, OperationResult parentResult)
        throws CommunicationException, ConfigurationException, GenericFrameworkException {
    // Connector operation cannot create result for itself, so we need to
    // create result for it
    OperationResult icfResult = parentResult.createSubresult(ConnectorFacade.class.getName() + ".schema");
    icfResult.addContext("connector", connIdConnectorFacade.getClass());

    org.identityconnectors.framework.common.objects.Schema icfSchema = null;
    try {/*  w w w  . j av  a 2  s.c  om*/

        // Fetch the schema from the connector (which actually gets that
        // from the resource).
        InternalMonitor.recordConnectorOperation("schema");
        // TODO have context present
        //recordIcfOperationStart(reporter, ProvisioningOperation.ICF_GET_SCHEMA, null);
        icfSchema = connIdConnectorFacade.schema();
        //recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_GET_SCHEMA, null);

        icfResult.recordSuccess();
    } catch (UnsupportedOperationException ex) {
        //recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_GET_SCHEMA, null, ex);
        // The connector does no support schema() operation.
        icfResult.recordStatus(OperationResultStatus.NOT_APPLICABLE, ex.getMessage());
        resetResourceSchema();
        return;
    } catch (Throwable ex) {
        //recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_GET_SCHEMA, null, ex);
        // conditions.
        // Therefore this kind of heavy artillery is necessary.
        // ICF interface does not specify exceptions or other error
        // TODO maybe we can try to catch at least some specific exceptions
        Throwable midpointEx = processConnIdException(ex, this, icfResult);

        // Do some kind of acrobatics to do proper throwing of checked
        // exception
        if (midpointEx instanceof CommunicationException) {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw (CommunicationException) midpointEx;
        } else if (midpointEx instanceof ConfigurationException) {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw (ConfigurationException) midpointEx;
        } else if (midpointEx instanceof GenericFrameworkException) {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw (GenericFrameworkException) midpointEx;
        } else if (midpointEx instanceof RuntimeException) {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw (RuntimeException) midpointEx;
        } else if (midpointEx instanceof Error) {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw (Error) midpointEx;
        } else {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw new SystemException(
                    "Got unexpected exception: " + ex.getClass().getName() + ": " + ex.getMessage(), ex);
        }
    }

    if (icfSchema == null) {
        icfResult.recordStatus(OperationResultStatus.NOT_APPLICABLE, "Null schema returned");
        resetResourceSchema();
        return;
    }

    parseResourceSchema(icfSchema, generateObjectClasses);
}

From source file:com.evolveum.midpoint.provisioning.ucf.impl.ConnectorInstanceIcfImpl.java

private void retrieveResourceSchema(List<QName> generateObjectClasses, OperationResult parentResult)
        throws CommunicationException, ConfigurationException, GenericFrameworkException {
    // Connector operation cannot create result for itself, so we need to
    // create result for it
    OperationResult icfResult = parentResult.createSubresult(ConnectorFacade.class.getName() + ".schema");
    icfResult.addContext("connector", icfConnectorFacade.getClass());

    org.identityconnectors.framework.common.objects.Schema icfSchema = null;
    try {//  w  w w  .j a  va 2 s .c  o  m

        // Fetch the schema from the connector (which actually gets that
        // from the resource).
        InternalMonitor.recordConnectorOperation("schema");
        // TODO have context present
        //recordIcfOperationStart(reporter, ProvisioningOperation.ICF_GET_SCHEMA, null);
        icfSchema = icfConnectorFacade.schema();
        //recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_GET_SCHEMA, null);

        icfResult.recordSuccess();
    } catch (UnsupportedOperationException ex) {
        //recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_GET_SCHEMA, null, ex);
        // The connector does no support schema() operation.
        icfResult.recordStatus(OperationResultStatus.NOT_APPLICABLE, ex.getMessage());
        resetResourceSchema();
        return;
    } catch (Throwable ex) {
        //recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_GET_SCHEMA, null, ex);
        // conditions.
        // Therefore this kind of heavy artillery is necessary.
        // ICF interface does not specify exceptions or other error
        // TODO maybe we can try to catch at least some specific exceptions
        Throwable midpointEx = processIcfException(ex, this, icfResult);

        // Do some kind of acrobatics to do proper throwing of checked
        // exception
        if (midpointEx instanceof CommunicationException) {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw (CommunicationException) midpointEx;
        } else if (midpointEx instanceof ConfigurationException) {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw (ConfigurationException) midpointEx;
        } else if (midpointEx instanceof GenericFrameworkException) {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw (GenericFrameworkException) midpointEx;
        } else if (midpointEx instanceof RuntimeException) {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw (RuntimeException) midpointEx;
        } else if (midpointEx instanceof Error) {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw (Error) midpointEx;
        } else {
            icfResult.recordFatalError(midpointEx.getMessage(), midpointEx);
            throw new SystemException(
                    "Got unexpected exception: " + ex.getClass().getName() + ": " + ex.getMessage(), ex);
        }
    }

    if (icfSchema == null) {
        icfResult.recordStatus(OperationResultStatus.NOT_APPLICABLE, "Null schema returned");
        resetResourceSchema();
        return;
    }

    parseResourceSchema(icfSchema, generateObjectClasses);
}

From source file:org.lockss.servlet.ServeContent.java

/**
 * Handle request for content that belongs to one of our AUs, whether or not
 * we have content for that URL.  If this request contains a version param,
 * serve it from cache with a Memento-Datetime header and no
 * link-rewriting.  For requests without a version param, rewrite links,
 * and serve from publisher if publisher provides it and the daemon options
 * allow it; otherwise, try to serve from cache.
 *
 * @throws IOException for IO errors// w  ww .j av  a 2s .  c o m
 */
protected void handleAuRequest() throws IOException {
    String host = UrlUtil.getHost(url);
    boolean isInCache = isInCache();
    boolean isHostDown = proxyMgr.isHostDown(host);
    PublisherContacted pubContacted = CounterReportsRequestRecorder.PublisherContacted.FALSE;

    if (isNeverProxyForAu(au) || isMementoRequest()) {
        if (isInCache) {
            serveFromCache();
            logAccess("200 from cache");
            // Record the necessary information required for COUNTER reports.
            recordRequest(url, pubContacted, 200);
        } else {
            /*
             * We don't want to redirect to the publisher, so pass KnownDown below
             * in order to ensure that. It's true that we might be lying, because
             * the publisher might be up.
             */
            handleMissingUrlRequest(url, PubState.KnownDown);
        }
        return;
    }

    LockssUrlConnectionPool connPool = proxyMgr.getNormalConnectionPool();

    if (!isInCache && isHostDown) {
        switch (proxyMgr.getHostDownAction()) {
        case ProxyManager.HOST_DOWN_NO_CACHE_ACTION_504:
            handleMissingUrlRequest(url, PubState.RecentlyDown);
            return;
        case ProxyManager.HOST_DOWN_NO_CACHE_ACTION_QUICK:
            connPool = proxyMgr.getQuickConnectionPool();
            break;
        default:
        case ProxyManager.HOST_DOWN_NO_CACHE_ACTION_NORMAL:
            connPool = proxyMgr.getNormalConnectionPool();
            break;
        }
    }

    // Send request to publisher
    LockssUrlConnection conn = null;
    PubState pstate = PubState.Unknown;
    try {
        conn = openLockssUrlConnection(connPool);

        // set proxy for connection if specified
        AuProxyInfo info = AuUtil.getAuProxyInfo(au);
        String proxyHost = info.getHost();
        int proxyPort = info.getPort();
        if (!StringUtil.isNullString(proxyHost) && (proxyPort > 0)) {
            try {
                conn.setProxy(info.getHost(), info.getPort());
            } catch (UnsupportedOperationException ex) {
                log.warning("Unsupported connection request proxy: " + proxyHost + ":" + proxyPort);
            }
        }
        conn.execute();
        pubContacted = CounterReportsRequestRecorder.PublisherContacted.TRUE;
    } catch (IOException ex) {
        if (log.isDebug3())
            log.debug3("conn.execute", ex);

        // mark host down if connection timed out
        if (ex instanceof LockssUrlConnection.ConnectionTimeoutException) {
            proxyMgr.setHostDown(host, isInCache);
        } else {
            pubContacted = CounterReportsRequestRecorder.PublisherContacted.TRUE;
        }
        pstate = PubState.KnownDown;

        // tear down connection
        IOUtil.safeRelease(conn);
        conn = null;
    }

    int response = 0;
    try {
        if (conn != null) {
            response = conn.getResponseCode();
            if (log.isDebug2())
                log.debug2("response: " + response + " " + conn.getResponseMessage());
            if (response == HttpResponse.__200_OK) {
                // If publisher responds with content, serve it to user
                // XXX Should check for a login page here
                try {
                    serveFromPublisher(conn);
                    logAccess(present(isInCache, "200 from publisher"));
                    // Record the necessary information required for COUNTER reports.
                    recordRequest(url, pubContacted, response);
                    return;
                } catch (CacheException.PermissionException ex) {
                    logAccess("login exception: " + ex.getMessage());
                    pstate = PubState.NoContent;
                }
            } else {
                pstate = PubState.NoContent;
            }
        }
    } finally {
        // ensure connection is closed
        IOUtil.safeRelease(conn);
    }

    // Either failed to open connection or got non-200 response.
    if (isInCache) {
        serveFromCache();
        logAccess("present, 200 from cache");
        // Record the necessary information required for COUNTER reports.
        recordRequest(url, pubContacted, response);
    } else {
        log.debug2("No content for: " + url);
        // return 404 with index
        handleMissingUrlRequest(url, pstate);
    }
}

From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImpl.java

protected void processAggregatorRequest(HttpServletRequest req, HttpServletResponse resp) {
    final String sourceMethod = "processAggregatorRequest"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[] { req, resp });
    }//w  w w  .j  a v a 2s  . c o  m
    req.setAttribute(AGGREGATOR_REQATTRNAME, this);
    ConcurrentMap<String, Object> concurrentMap = new ConcurrentHashMap<String, Object>();
    req.setAttribute(CONCURRENTMAP_REQATTRNAME, concurrentMap);

    try {
        // Validate config last-modified if development mode is enabled
        if (getOptions().isDevelopmentMode()) {
            long lastModified = -1;
            URI configUri = getConfig().getConfigUri();
            if (configUri != null) {
                try {
                    // try to get platform URI from IResource in case uri specifies
                    // aggregator specific scheme like namedbundleresource
                    configUri = newResource(configUri).getURI();
                } catch (UnsupportedOperationException e) {
                    // Not fatal.  Just use uri as specified.
                }
                lastModified = configUri.toURL().openConnection().getLastModified();
            }
            if (lastModified > getConfig().lastModified()) {
                if (reloadConfig()) {
                    // If the config has been modified, then dependencies will be revalidated
                    // asynchronously.  Rather than forcing the current request to wait, return
                    // a response that will display an alert informing the user of what is
                    // happening and asking them to reload the page.
                    String content = "alert('" + //$NON-NLS-1$
                            StringUtil.escapeForJavaScript(Messages.ConfigModified) + "');"; //$NON-NLS-1$
                    resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
                    CopyUtil.copy(new StringReader(content), resp.getOutputStream());
                    return;
                }
            }
        }

        getTransport().decorateRequest(req);
        notifyRequestListeners(RequestNotifierAction.start, req, resp);

        ILayer layer = getLayer(req);
        long modifiedSince = req.getDateHeader("If-Modified-Since"); //$NON-NLS-1$
        long lastModified = (Math.max(getCacheManager().getCache().getCreated(), layer.getLastModified(req))
                / 1000) * 1000;
        if (modifiedSince >= lastModified) {
            if (log.isLoggable(Level.FINER)) {
                log.finer("Returning Not Modified response for layer in servlet" + //$NON-NLS-1$
                        getName() + ":" //$NON-NLS-1$
                        + req.getAttribute(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME).toString());
            }
            resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        } else {
            // Get the InputStream for the response.  This call sets the Content-Type,
            // Content-Length and Content-Encoding headers in the response.
            InputStream in = layer.getInputStream(req, resp);
            // if any of the readers included an error response, then don't cache the layer.
            if (req.getAttribute(ILayer.NOCACHE_RESPONSE_REQATTRNAME) != null) {
                resp.addHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
            } else {
                resp.setDateHeader("Last-Modified", lastModified); //$NON-NLS-1$
                int expires = getConfig().getExpires();
                resp.addHeader("Cache-Control", //$NON-NLS-1$
                        "public" + (expires > 0 ? (", max-age=" + expires) : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                );
            }
            CopyUtil.copy(in, resp.getOutputStream());
        }
        notifyRequestListeners(RequestNotifierAction.end, req, resp);
    } catch (DependencyVerificationException e) {
        // clear the cache now even though it will be cleared when validateDeps has
        // finished (asynchronously) so that any new requests will be forced to wait
        // until dependencies have been validated.
        getCacheManager().clearCache();
        getDependencies().validateDeps(false);

        resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
        if (getOptions().isDevelopmentMode()) {
            String msg = StringUtil.escapeForJavaScript(MessageFormat.format(Messages.DepVerificationFailed,
                    new Object[] { e.getMessage(), "aggregator " + //$NON-NLS-1$
                            "validatedeps " + //$NON-NLS-1$
                            getName() + " clean", //$NON-NLS-1$
                            getWorkingDirectory().toString().replace("\\", "\\\\") //$NON-NLS-1$ //$NON-NLS-2$
                    }));
            String content = "alert('" + msg + "');"; //$NON-NLS-1$ //$NON-NLS-2$
            try {
                CopyUtil.copy(new StringReader(content), resp.getOutputStream());
            } catch (IOException e1) {
                if (log.isLoggable(Level.SEVERE)) {
                    log.log(Level.SEVERE, e1.getMessage(), e1);
                }
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } catch (ProcessingDependenciesException e) {
        resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
        if (getOptions().isDevelopmentMode()) {
            String content = "alert('" + StringUtil.escapeForJavaScript(Messages.Busy) + "');"; //$NON-NLS-1$ //$NON-NLS-2$
            try {
                CopyUtil.copy(new StringReader(content), resp.getOutputStream());
            } catch (IOException e1) {
                if (log.isLoggable(Level.SEVERE)) {
                    log.log(Level.SEVERE, e1.getMessage(), e1);
                }
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } catch (BadRequestException e) {
        exceptionResponse(req, resp, e, HttpServletResponse.SC_BAD_REQUEST);
    } catch (NotFoundException e) {
        exceptionResponse(req, resp, e, HttpServletResponse.SC_NOT_FOUND);
    } catch (Exception e) {
        exceptionResponse(req, resp, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        concurrentMap.clear();
    }
    if (isTraceLogging) {
        log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
    }
}