List of usage examples for java.lang RuntimeException getCause
public synchronized Throwable getCause()
From source file:org.apache.hadoop.hbase.client.crosssite.CrossSiteHTable.java
private HTableInterface createHTable(String clusterName, String clusterAddress) throws IOException { Configuration clusterConf = getCrossSiteConf(this.configuration, clusterAddress); HTableInterface table = null;//from w w w .j a v a 2s . co m try { table = this.hTableFactory.createHTableInterface(clusterConf, Bytes.toBytes(CrossSiteUtil.getClusterTableName(tableNameAsString, clusterName))); } catch (RuntimeException e) { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } else { throw new IOException(e); } } table.setWriteBufferSize(this.writeBufferSize); table.setAutoFlush(autoFlush, clearBufferOnFail); if (table instanceof HTable && operationTimeout != 1) { ((HTable) table).setOperationTimeout(operationTimeout); } return table; }
From source file:org.dswarm.graph.resources.GDMResource.java
/** * multipart/mixed payload contains two body parts:<br/> * - first body part is the metadata (i.e. a JSON object with mandatory and obligatory properties for processing the * content):<br/>/* www.j ava 2s .c om*/ * - "data_model_URI" (mandatory)<br/> * - "content_schema" (obligatory)<br/> * - "deprecate_missing_records" (obligatory)<br/> * - "record_class_uri" (mandatory for "deprecate_missing_records")<br/> * - second body part is the content (i.e. the real data) * * @param multiPart * @param database * @return * @throws DMPGraphException * @throws IOException */ @POST @Path("/put") @Consumes("multipart/mixed") public Response writeGDM(final MultiPart multiPart, @Context final GraphDatabaseService database, @Context final HttpHeaders requestHeaders) throws DMPGraphException, IOException { LOG.debug("try to process GDM statements and write them into graph db"); final String headers = readHeaders(requestHeaders); GDMResource.LOG.debug("try to process GDM statements and write them into graph db with\n{}", headers); final List<BodyPart> bodyParts = getBodyParts(multiPart); final ObjectNode metadata = getMetadata(bodyParts); final InputStream content = getContent(bodyParts); final Optional<String> optionalDataModelURI = getMetadataPart(DMPStatics.DATA_MODEL_URI_IDENTIFIER, metadata, true); final String dataModelURI = optionalDataModelURI.get(); final Optional<Boolean> optionalEnableVersioning = getEnableVersioningFlag(metadata); final boolean enableVersioning; if (optionalEnableVersioning.isPresent()) { enableVersioning = optionalEnableVersioning.get(); } else { enableVersioning = true; } final AtomicInteger counter = new AtomicInteger(0); final Tuple<Observable<Resource>, BufferedInputStream> modelTuple = getModel(content); final ConnectableObservable<Resource> model = modelTuple.v1() .doOnSubscribe(() -> LOG.debug("subscribed to model observable")).doOnNext(record -> { if (counter.incrementAndGet() == 1) { LOG.debug("read first records from model observable"); } }).doOnCompleted(() -> LOG.debug("read '{}' records from model observable", counter.get())) .onBackpressureBuffer(10000).publish(); final BufferedInputStream bis = modelTuple.v2(); LOG.debug("deserialized GDM statements that were serialised as JSON"); LOG.debug("try to write GDM statements into graph db"); final TransactionHandler tx = new Neo4jTransactionHandler(database); final NamespaceIndex namespaceIndex = new NamespaceIndex(database, tx); final String prefixedDataModelURI = namespaceIndex.createPrefixedURI(dataModelURI); final GDMNeo4jProcessor processor = new DataModelGDMNeo4jProcessor(database, tx, namespaceIndex, prefixedDataModelURI); LOG.info("process GDM statements and write them into graph db for data model '{}' ('{}')", dataModelURI, prefixedDataModelURI); try { final GDMNeo4jHandler handler = new DataModelGDMNeo4jHandler(processor, enableVersioning); final Observable<Resource> newModel; final Observable<Boolean> deprecateRecordsObservable; // note: versioning is enable by default if (enableVersioning) { LOG.info("do versioning with GDM statements for data model '{}' ('{}')", dataModelURI, prefixedDataModelURI); final Optional<ContentSchema> optionalPrefixedContentSchema = getPrefixedContentSchema(metadata, namespaceIndex); // = new resources model, since existing, modified resources were already written to the DB final Tuple<Observable<Resource>, Observable<Long>> result = calculateDeltaForDataModel(model, optionalPrefixedContentSchema, prefixedDataModelURI, database, handler, namespaceIndex); final Observable<Resource> deltaModel = result.v1().onBackpressureBuffer(10000); final Optional<Boolean> optionalDeprecateMissingRecords = getDeprecateMissingRecordsFlag(metadata); if (optionalDeprecateMissingRecords.isPresent() && optionalDeprecateMissingRecords.get()) { final Optional<String> optionalRecordClassURI = getMetadataPart( DMPStatics.RECORD_CLASS_URI_IDENTIFIER, metadata, false); if (!optionalRecordClassURI.isPresent()) { throw new DMPGraphException( "could not deprecate missing records, because no record class uri is given"); } // deprecate missing records in DB final Observable<Long> processedResources = result.v2(); deprecateRecordsObservable = deprecateMissingRecords(processedResources, optionalRecordClassURI.get(), dataModelURI, ((Neo4jUpdateHandler) handler.getHandler()).getVersionHandler().getLatestVersion(), processor); } else { deprecateRecordsObservable = Observable.empty(); } newModel = deltaModel; LOG.info("finished versioning with GDM statements for data model '{}' ('{}')", dataModelURI, prefixedDataModelURI); } else { newModel = model; deprecateRecordsObservable = Observable.empty(); } final AtomicInteger counter2 = new AtomicInteger(0); final ConnectableObservable<Resource> newModelLogged = newModel .doOnSubscribe(() -> LOG.debug("subscribed to new model observable")).doOnNext(record -> { if (counter2.incrementAndGet() == 1) { LOG.debug("read first records from new model observable"); } }).doOnCompleted(() -> LOG.debug("read '{}' records from new model observable", counter2.get())) .onBackpressureBuffer(10000).publish(); //if (deltaModel.size() > 0) { // parse model only, when model contains some resources final AtomicInteger counter3 = new AtomicInteger(0); final GDMParser parser = new GDMModelParser(newModelLogged); parser.setGDMHandler(handler); final Observable<Boolean> newResourcesObservable = parser.parse() .doOnSubscribe(() -> LOG.debug("subscribed to new resources observable")).doOnNext(record -> { if (counter3.incrementAndGet() == 1) { LOG.debug("read first records from new resources observable"); } }).doOnCompleted( () -> LOG.debug("read '{}' records from new resources observable", counter3.get())); try { final Observable<Boolean> connectedObservable = deprecateRecordsObservable .concatWith(newResourcesObservable); final BlockingObservable<Boolean> blockingObservable = connectedObservable.toBlocking(); final Iterator<Boolean> iterator = blockingObservable.getIterator(); newModelLogged.connect(); if (!enableVersioning) { model.connect(); } if (!iterator.hasNext()) { LOG.debug("model contains no resources, i.e., nothing needs to be written to the DB"); } while (iterator.hasNext()) { iterator.next(); } } catch (final RuntimeException e) { throw new DMPGraphException(e.getMessage(), e.getCause()); } final Long size = handler.getHandler().getCountedStatements(); if (enableVersioning && size > 0) { // update data model version only when some statements are written to the DB ((Neo4jUpdateHandler) handler.getHandler()).getVersionHandler().updateLatestVersion(); } handler.getHandler().closeTransaction(); bis.close(); content.close(); LOG.info( "finished writing {} resources with {} GDM statements (added {} relationships, added {} nodes (resources + bnodes + literals), added {} literals) into graph db for data model URI '{}' ('{}')", parser.parsedResources(), handler.getHandler().getCountedStatements(), handler.getHandler().getRelationshipsAdded(), handler.getHandler().getNodesAdded(), handler.getHandler().getCountedLiterals(), dataModelURI, prefixedDataModelURI); return Response.ok().build(); } catch (final Exception e) { processor.getProcessor().failTx(); bis.close(); content.close(); LOG.error("couldn't write GDM statements into graph db: {}", e.getMessage(), e); throw e; } }
From source file:com.gs.collections.impl.test.Verify.java
/** * Runs the {@link Runnable} {@code code} and asserts that it throws an {@code Exception} of the type * {@code expectedExceptionClass}, which contains a cause of type expectedCauseClass. * <p>//from ww w . j a v a 2 s .c o m * {@code Runnable} is most appropriate when a subclass of {@link RuntimeException} will be thrown. * If a checked exception will be thrown, the form {@link #assertThrowsWithCause(Class, Class, Callable)} * may be more convenient. * <p> * e.g. * <pre> * Verify.assertThrowsWithCause(RuntimeException.class, StringIndexOutOfBoundsException.class, new Runnable() * { * public void run() * { * try * { * LOGGER.info("Craig".substring(42, 3)); * } * catch (final StringIndexOutOfBoundsException e) * { * throw new RuntimeException("Uh oh!", e); * } * } * }); * </pre> * * @see #assertThrowsWithCause(Class, Class, Callable) */ public static void assertThrowsWithCause(Class<? extends Exception> expectedExceptionClass, Class<? extends Throwable> expectedCauseClass, Runnable code) { try { code.run(); } catch (RuntimeException ex) { try { Assert.assertSame("Caught exception of type <" + ex.getClass().getName() + ">, expected one of type <" + expectedExceptionClass.getName() + '>', expectedExceptionClass, ex.getClass()); Throwable actualCauseClass = ex.getCause(); Assert.assertNotNull("Caught exception with null cause, expected cause of type <" + expectedCauseClass.getName() + '>', actualCauseClass); Assert.assertSame( "Caught exception with cause of type<" + actualCauseClass.getClass().getName() + ">, expected cause of type <" + expectedCauseClass.getName() + '>', expectedCauseClass, actualCauseClass.getClass()); return; } catch (AssertionError e) { Verify.throwMangledException(e); } } try { Assert.fail("Block did not throw an exception of type " + expectedExceptionClass.getName()); } catch (AssertionError e) { Verify.throwMangledException(e); } }
From source file:com.couchbase.lite.router.Router.java
/** * NOTE this departs from the iOS version, returning revision, passing status back by reference * <p/>/*from w w w . j a v a 2s. c om*/ * - (CBLStatus) update: (CBLDatabase*)db * docID: (NSString*)docID * body: (CBL_Body*)body * deleting: (BOOL)deleting * allowConflict: (BOOL)allowConflict * createdRev: (CBL_Revision**)outRev * error: (NSError**)outError */ private RevisionInternal update(Database _db, String docID, Body body, boolean deleting, boolean allowConflict, Status outStatus) { if (body != null && !body.isValidJSON()) { outStatus.setCode(Status.BAD_JSON); return null; } boolean isLocalDoc = docID != null && docID.startsWith(("_local")); String prevRevID; if (!deleting) { Boolean deletingBoolean = (Boolean) body.getPropertyForKey("_deleted"); deleting = (deletingBoolean != null && deletingBoolean.booleanValue()); if (docID == null) { if (isLocalDoc) { outStatus.setCode(Status.METHOD_NOT_ALLOWED); return null; } // POST's doc ID may come from the _id field of the JSON body, else generate a random one. docID = (String) body.getPropertyForKey("_id"); if (docID == null) { if (deleting) { outStatus.setCode(Status.BAD_REQUEST); return null; } docID = Misc.CreateUUID(); } } // PUT's revision ID comes from the JSON body. prevRevID = (String) body.getPropertyForKey("_rev"); } else { // DELETE's revision ID comes from the ?rev= query param prevRevID = getQuery("rev"); } // A backup source of revision ID is an If-Match header: if (prevRevID == null) { prevRevID = getRevIDFromIfMatchHeader(); } RevisionInternal rev = new RevisionInternal(docID, null, deleting); rev.setBody(body); RevisionInternal result = null; try { if (isLocalDoc) { // NOTE: putLocalRevision() does not use transaction internally with obeyMVCC=true final Database fDb = _db; final RevisionInternal _rev = rev; final String _prevRevID = prevRevID; final List<RevisionInternal> _revs = new ArrayList<RevisionInternal>(); try { fDb.getStore().runInTransaction(new TransactionalTask() { @Override public boolean run() { try { RevisionInternal r = fDb.getStore().putLocalRevision(_rev, _prevRevID, true); _revs.add(r); return true; } catch (CouchbaseLiteException e) { throw new RuntimeException(e); } } }); // success if (_revs.size() > 0) result = _revs.get(0); } catch (RuntimeException ex) { if (ex.getCause() != null && ex.getCause().getCause() != null && ex.getCause().getCause() instanceof CouchbaseLiteException) throw (CouchbaseLiteException) ex.getCause().getCause(); else throw new CouchbaseLiteException(ex, Status.INTERNAL_SERVER_ERROR); } } else { // putRevision() uses transaction internally. result = _db.putRevision(rev, prevRevID, allowConflict); } if (deleting) { outStatus.setCode(Status.OK); } else { outStatus.setCode(Status.CREATED); } } catch (CouchbaseLiteException e) { if (e.getCBLStatus() != null && e.getCBLStatus().getCode() == Status.CONFLICT) { // conflict is not critical error for replicators, not print stack trace Log.w(TAG, "Error updating doc: %s", docID); } else { Log.e(TAG, "Error updating doc: %s", e, docID); } outStatus.setCode(e.getCBLStatus().getCode()); } return result; }
From source file:org.jspresso.framework.model.component.basic.AbstractComponentInvocationHandler.java
@SuppressWarnings("unchecked") protected void removeFromProperty(Object proxy, ICollectionPropertyDescriptor<?> propertyDescriptor, Object value) {//from www.j a v a2 s . co m String propertyName = propertyDescriptor.getName(); // The following optimization breaks bidirectional N-N relationship persistence // if (!isInitialized(straightGetProperty(proxy, propertyName))) { // return; // } Collection<Object> collectionProperty = (Collection<Object>) straightGetProperty(proxy, propertyName); try { if (propertyProcessorsEnabled) { propertyDescriptor.preprocessRemover(proxy, collectionProperty, value); } if (collectionProperty.contains(value)) { IRelationshipEndPropertyDescriptor reversePropertyDescriptor = propertyDescriptor .getReverseRelationEnd(); if (reversePropertyDescriptor != null) { if (reversePropertyDescriptor instanceof IReferencePropertyDescriptor<?>) { accessorFactory .createPropertyAccessor(reversePropertyDescriptor.getName(), propertyDescriptor .getReferencedDescriptor().getElementDescriptor().getComponentContract()) .setValue(value, null); } else if (reversePropertyDescriptor instanceof ICollectionPropertyDescriptor<?>) { ICollectionAccessor collectionAccessor = accessorFactory.createCollectionPropertyAccessor( reversePropertyDescriptor.getName(), propertyDescriptor.getReferencedDescriptor().getElementDescriptor() .getComponentContract(), ((ICollectionPropertyDescriptor<?>) reversePropertyDescriptor) .getCollectionDescriptor().getElementDescriptor().getComponentContract()); if (collectionAccessor instanceof IModelDescriptorAware) { ((IModelDescriptorAware) collectionAccessor) .setModelDescriptor(reversePropertyDescriptor); } collectionAccessor.removeFromValue(value, proxy); } } Collection<?> oldCollectionSnapshot = CollectionHelper .cloneCollection((Collection<?>) collectionProperty); if (collectionProperty.remove(value)) { if (EntityHelper.isInlineComponentReference( propertyDescriptor.getReferencedDescriptor().getElementDescriptor())) { if (value != null) { ((IComponent) value).setOwningComponent(null, null); } } doFirePropertyChange(proxy, propertyName, oldCollectionSnapshot, collectionProperty); if (propertyProcessorsEnabled) { propertyDescriptor.postprocessRemover(proxy, collectionProperty, value); } if (proxy instanceof IEntity && value instanceof IEntity) { entityDetached((IEntity) proxy, (IEntity) value, propertyDescriptor); } } } } catch (RuntimeException ex) { rollbackProperty(proxy, propertyDescriptor, collectionProperty); throw ex; } catch (InvocationTargetException ex) { rollbackProperty(proxy, propertyDescriptor, collectionProperty); if (ex.getCause() instanceof RuntimeException) { throw (RuntimeException) ex.getCause(); } throw new ComponentException(ex.getCause()); } catch (IllegalAccessException | NoSuchMethodException ex) { throw new ComponentException(ex); } }
From source file:org.jspresso.framework.model.component.basic.AbstractComponentInvocationHandler.java
@SuppressWarnings("unchecked") protected void addToProperty(Object proxy, ICollectionPropertyDescriptor<?> propertyDescriptor, int index, Object value) {//from www.j a va2 s . c o m String propertyName = propertyDescriptor.getName(); Collection<Object> collectionProperty = (Collection<Object>) straightGetProperty(proxy, propertyName); if (value instanceof IEntity && collectionProperty.contains(value)) { if (collectionProperty instanceof Set<?>) { LOG.warn("You have added twice the same element to the following collection property : {}.{}" + componentDescriptor.getComponentContract().getName(), propertyName); } else { throw new ComponentException("Collection property does not allow duplicates : " + componentDescriptor.getComponentContract().getName() + "." + propertyName); } } try { if (propertyProcessorsEnabled) { propertyDescriptor.preprocessAdder(proxy, collectionProperty, value); } IRelationshipEndPropertyDescriptor reversePropertyDescriptor = propertyDescriptor .getReverseRelationEnd(); if (reversePropertyDescriptor != null) { if (reversePropertyDescriptor instanceof IReferencePropertyDescriptor<?>) { accessorFactory .createPropertyAccessor(reversePropertyDescriptor.getName(), propertyDescriptor .getReferencedDescriptor().getElementDescriptor().getComponentContract()) .setValue(value, proxy); } else if (reversePropertyDescriptor instanceof ICollectionPropertyDescriptor<?>) { ICollectionAccessor collectionAccessor = accessorFactory.createCollectionPropertyAccessor( reversePropertyDescriptor.getName(), propertyDescriptor.getReferencedDescriptor().getElementDescriptor() .getComponentContract(), ((ICollectionPropertyDescriptor<?>) reversePropertyDescriptor).getCollectionDescriptor() .getElementDescriptor().getComponentContract()); if (collectionAccessor instanceof IModelDescriptorAware) { ((IModelDescriptorAware) collectionAccessor).setModelDescriptor(reversePropertyDescriptor); } collectionAccessor.addToValue(value, proxy); } } Collection<?> oldCollectionSnapshot = CollectionHelper .cloneCollection((Collection<?>) collectionProperty); boolean inserted; if (collectionProperty instanceof List<?> && index >= 0 && index < collectionProperty.size()) { ((List<Object>) collectionProperty).add(index, value); inserted = true; } else { inserted = collectionProperty.add(value); } if (inserted) { if (EntityHelper.isInlineComponentReference( propertyDescriptor.getReferencedDescriptor().getElementDescriptor())) { if (value != null) { ((IComponent) value).setOwningComponent((IComponent) proxy, propertyDescriptor); } } if (collectionSortEnabled) { inlineComponentFactory.sortCollectionProperty((IComponent) proxy, propertyName); } doFirePropertyChange(proxy, propertyName, oldCollectionSnapshot, collectionProperty); if (propertyProcessorsEnabled) { propertyDescriptor.postprocessAdder(proxy, collectionProperty, value); } } } catch (RuntimeException ex) { rollbackProperty(proxy, propertyDescriptor, collectionProperty); throw ex; } catch (InvocationTargetException ex) { rollbackProperty(proxy, propertyDescriptor, collectionProperty); if (ex.getCause() instanceof RuntimeException) { throw (RuntimeException) ex.getCause(); } throw new ComponentException(ex.getCause()); } catch (IllegalAccessException | NoSuchMethodException ex) { throw new ComponentException(ex); } }
From source file:org.de.jmg.learn.MainActivity.java
public void LoadVokabel(String fileSelected, Uri uri, int index, int[] Lernvokabeln, int Lernindex, boolean CardMode) { try {//from ww w . jav a 2 s. com if (fPA.fragMain != null && fPA.fragMain.mainView != null) { fPA.fragMain.setBtnsEnabled(false); if (!fPA.fragMain.EndEdit(false)) return; } if (uri == null) { if (!saveVok(false)) return; } try { vok.LoadFile(this, fileSelected, uri, false, false, _blnUniCode); } catch (RuntimeException ex) { if (ex.getCause() != null) { if (ex.getCause().getMessage() != null && ex.getCause().getMessage().contains("IsSingleline")) { vok.LoadFile(this, fileSelected, uri, true, false, _blnUniCode); } else { throw ex; } } else { throw ex; } } if (vok.getCardMode() || CardMode) { if (fPA.fragMain != null && fPA.fragMain.mainView != null) fPA.fragMain.SetViewsToCardmode(); } else { if (fPA.fragMain != null && fPA.fragMain.mainView != null) fPA.fragMain.SetViewsToVokMode(); } // if (index >0 ) vok.setIndex(index); if (Lernvokabeln != null) vok.setLernvokabeln(Lernvokabeln); if (vok.getGesamtzahl() > 0) { if (Lernindex > 0) vok.setLernIndex((short) Lernindex); if (fPA.fragMain != null && fPA.fragMain.mainView != null) fPA.fragMain.setBtnsEnabled(true); } if (fPA.fragMain != null && fPA.fragMain.mainView != null) fPA.fragMain.getVokabel(false, false, false); } catch (Exception e) { lib.ShowException(this, e); if (fPA.fragMain != null && fPA.fragMain.mainView != null) { try { fPA.fragMain.getVokabel(true, true, false); } catch (Exception e1) { lib.ShowException(this, e); } } } }
From source file:com.silentcircle.silenttext.application.SilentTextApplication.java
public UserPreferences getGlobalPreferences() { createApplicationPreferencesRepository(); UserPreferences preferences = null;//from w w w . jav a2 s .co m try { preferences = applicationPreferencesRepository.findByID(APPLICATION_PREFERENCES_KEY.toCharArray()); } catch (RuntimeException exception) { getLog().info(exception, "#getGlobalPreferences #load"); } if (preferences == null) { preferences = createDefaultApplicationPreferences(); try { applicationPreferencesRepository.save(preferences); } catch (RuntimeException exception) { getLog().warn(exception.getCause(), "#getGlobalPreferences #save"); } } return preferences; }
From source file:de.dal33t.powerfolder.clientserver.ServerClient.java
/** * Logs into the server and saves the identity as my login. * <p>/*from ww w . ja v a 2 s . c o m*/ * If the server is not connected and invalid account is returned and the * login data saved for auto-login on reconnect. * * @param theUsername * @param thePasswordObj * the obfuscated password * @param saveLastLogin * if the last login should be remembered. * @return the identity with this username or <code>InvalidAccount</code> if * login failed. NEVER returns <code>null</code> */ public Account login(String theUsername, String thePasswordObj, boolean saveLastLogin) { logFine("Login with: " + theUsername); synchronized (loginLock) { loggingIn.set(true); String prevUsername = username; String prevPasswordObf = passwordObf; try { username = theUsername; passwordObf = thePasswordObj; if (saveLastLogin) { saveLastKnowLogin(username, passwordObf); } boolean disconnected = !server.isConnected(); boolean pwEmpty = StringUtils.isBlank(passwordObf); boolean noKerberosLogin = !isKerberosLogin(); if (disconnected || (pwEmpty && noKerberosLogin)) { setAnonAccount(); fireLogin(accountDetails); return accountDetails.getAccount(); } boolean loginOk = false; char[] pw = LoginUtil.deobfuscate(passwordObf); try { if (isShibbolethLogin()) { // PFC-2534: Start try { String currentIdP = ConfigurationEntry.SERVER_IDP_LAST_CONNECTED_ECP .getValue(getController()); boolean idpEqual = StringUtils.isEqual(lastIdPUsed, currentIdP); boolean pwEqual = StringUtils.isEqual(prevPasswordObf, passwordObf); boolean unEqual = StringUtils.isEqual(prevUsername, username); if (shibbolethUnauthRetriesSkip != 0 && unEqual && pwEqual && idpEqual) { shibbolethUnauthRetriesSkip--; if (isFine()) { logFine("Skipping login another " + shibbolethUnauthRetriesSkip + " times"); } setAnonAccount(); return accountDetails.getAccount(); } lastIdPUsed = currentIdP; shibbolethUnauthRetriesSkip = 0; } catch (RuntimeException e) { logWarning("An error occured skipping shibboleth login: " + e); } // PFC-2534: End boolean externalUser = prepareShibbolethLogin(username, pw, (prevUsername != null && !prevUsername.equals(username)) || (prevPasswordObf != null && !prevPasswordObf.equals(passwordObf))); if (externalUser) { loginOk = securityService.login(username, pw); } else if (shibUsername != null && shibToken != null) { loginOk = securityService.login(shibUsername, Util.toCharArray(shibToken)); } else { logWarning("Neither Shibboleth nor external login possible!"); } } else if (isKerberosLogin()) { byte[] serviceTicket = prepareKerberosLogin(); loginOk = securityService.login(username, serviceTicket); } else { loginOk = securityService.login(username, pw); } lastLoginSuccessful.set(loginOk); loginExecuted.set(true); } catch (RemoteCallException e) { if (e.getCause() instanceof NoSuchMethodException) { // Old server version (Pre 1.5.0 or older) // Try it the old fashioned way logSevere("Client incompatible with server: Server version too old"); } // Rethrow throw e; } finally { LoginUtil.clear(pw); } if (!loginOk) { logWarning("Login to server " + server + " (user " + theUsername + ") failed!"); setAnonAccount(); fireLogin(accountDetails, false); return accountDetails.getAccount(); } AccountDetails newAccountDetails = securityService.getAccountDetails(); logInfo("Login to server " + server.getReconnectAddress() + " (user " + theUsername + ") result: " + newAccountDetails); if (newAccountDetails != null) { accountDetails = newAccountDetails; if (updateConfig) { boolean configChanged; if (accountDetails.getAccount().getServer() != null) { configChanged = setServerWebURLInConfig( accountDetails.getAccount().getServer().getWebUrl()); configChanged = setServerHTTPTunnelURLInConfig( accountDetails.getAccount().getServer().getHTTPTunnelUrl()) || configChanged; } else { configChanged = setServerWebURLInConfig(null); configChanged = setServerHTTPTunnelURLInConfig(null) || configChanged; } if (configChanged) { getController().saveConfig(); } } // Fire login success loggingIn.set(false); fireLogin(accountDetails); getController().schedule(new Runnable() { @Override public void run() { // Also switches server updateLocalSettings(accountDetails.getAccount()); } }, 0); } else { setAnonAccount(); fireLogin(accountDetails, false); } return accountDetails.getAccount(); } catch (Exception e) { logWarning("Unable to login: " + e); if (isShibbolethLogin()) { // PFC-2534: Start // username = prevUsername; // passwordObf = prevPasswordObf; // PFC-2534: End saveLastKnowLogin(username, passwordObf); } setAnonAccount(); fireLogin(accountDetails, false); return accountDetails.getAccount(); } finally { loggingIn.set(false); } } }
From source file:org.apache.hadoop.hive.ql.metadata.Hive.java
/** * @return the metastore client for the current thread * @throws MetaException//from w w w . ja v a 2s .c om */ @LimitedPrivate(value = { "Hive" }) @Unstable public synchronized IMetaStoreClient getMSC(boolean allowEmbedded, boolean forceCreate) throws MetaException { if (metaStoreClient == null || forceCreate) { try { owner = UserGroupInformation.getCurrentUser(); } catch (IOException e) { String msg = "Error getting current user: " + e.getMessage(); LOG.error(msg, e); throw new MetaException(msg + "\n" + StringUtils.stringifyException(e)); } try { metaStoreClient = createMetaStoreClient(allowEmbedded); } catch (RuntimeException ex) { Throwable t = ex.getCause(); while (t != null) { if (t instanceof JDODataStoreException && t.getMessage() != null && t.getMessage().contains("autoCreate")) { LOG.error("Cannot initialize metastore due to autoCreate error", t); // DataNucleus wants us to auto-create, but we shall do no such thing. throw new SchemaException("Hive metastore database is not initialized. Please use " + "schematool (e.g. ./schematool -initSchema -dbType ...) to create the schema. If " + "needed, don't forget to include the option to auto-create the underlying database" + " in your JDBC connection string (e.g. ?createDatabaseIfNotExist=true for mysql)"); } t = t.getCause(); } throw ex; } String metaStoreUris = conf.getVar(HiveConf.ConfVars.METASTOREURIS); if (!org.apache.commons.lang3.StringUtils.isEmpty(metaStoreUris)) { // get a synchronized wrapper if the meta store is remote. metaStoreClient = HiveMetaStoreClient.newSynchronizedClient(metaStoreClient); } } return metaStoreClient; }