Java Code Examples for com.google.common.base.Throwables

The following are top voted examples for showing how to use com.google.common.base.Throwables. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Equella   File: SectionsControllerImpl.java   View source code 9 votes vote down vote up
@Override
public void forwardToUrl(SectionInfo info, String link, int code)
{
	info.setRendered();
	try
	{
		HttpServletResponse response = info.getResponse();
		if( response == null )
		{
			throw new Error("info not bound to a request/response");
		}
		response.setStatus(code);
		response.setHeader("Location", link);
		response.flushBuffer();
	}
	catch( Exception e )
	{
		throw Throwables.propagate(e);
	}
}
 
Example 2
Project: cas-5.1.0   File: AbstractJacksonBackedStringSerializer.java   View source code 7 votes vote down vote up
@Override
public void to(final File out, final T object) {
    try (StringWriter writer = new StringWriter()) {
        this.objectMapper.writer(this.prettyPrinter).writeValue(writer, object);

        if (isJsonFormat()) {
            try (FileWriter fileWriter = new FileWriter(out);
                 BufferedWriter buffer = new BufferedWriter(fileWriter)) {
                JsonValue.readHjson(writer.toString()).writeTo(buffer);
                buffer.flush();
                fileWriter.flush();
            }
        } else {
            FileUtils.write(out, writer.toString(), StandardCharsets.UTF_8);
        }
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
 
Example 3
Project: athena   File: AtomixLeaderElectorState.java   View source code 6 votes vote down vote up
/**
 * Applies an {@link AtomixLeaderElectorCommands.Anoint} commit.
 * @param commit anoint commit
 * @return {@code true} if changes were made and the transfer occurred; {@code false} if it did not.
 */
public boolean anoint(Commit<? extends Anoint> commit) {
    try {
        String topic = commit.operation().topic();
        NodeId nodeId = commit.operation().nodeId();
        Leadership oldLeadership = leadership(topic);
        ElectionState electionState = elections.computeIfPresent(topic,
                (k, v) -> v.transferLeadership(nodeId, termCounter(topic)));
        Leadership newLeadership = leadership(topic);
        if (!Objects.equal(oldLeadership, newLeadership)) {
            notifyLeadershipChange(oldLeadership, newLeadership);
        }
        return (electionState != null &&
                electionState.leader() != null &&
                commit.operation().nodeId().equals(electionState.leader().nodeId()));
    } catch (Exception e) {
        log.error("State machine operation failed", e);
        throw Throwables.propagate(e);
    } finally {
        commit.close();
    }
}
 
Example 4
Project: Elasticsearch   File: CountContext.java   View source code 6 votes vote down vote up
@Override
public void innerStart() {
    try {
        countFuture = countOperation.count(indexShardMap, whereClause);
    } catch (IOException | InterruptedException e) {
        throw Throwables.propagate(e);
    }
    Futures.addCallback(countFuture, new FutureCallback<Long>() {
        @Override
        public void onSuccess(@Nullable Long result) {
            rowReceiver.setNextRow(new Row1(result));
            close();
        }

        @Override
        public void onFailure(@Nonnull Throwable t) {
            close(t);
        }
    });
}
 
Example 5
Project: flume-release-1.7.0   File: TestDatasetSink.java   View source code 6 votes vote down vote up
public static int remaining(Channel ch) throws EventDeliveryException {
  Transaction t = ch.getTransaction();
  try {
    t.begin();
    int count = 0;
    while (ch.take() != null) {
      count += 1;
    }
    t.commit();
    return count;
  } catch (Throwable th) {
    t.rollback();
    Throwables.propagateIfInstanceOf(th, Error.class);
    Throwables.propagateIfInstanceOf(th, EventDeliveryException.class);
    throw new EventDeliveryException(th);
  } finally {
    t.close();
  }
}
 
Example 6
Project: athena   File: RetryingFunction.java   View source code 6 votes vote down vote up
@SuppressWarnings("squid:S1181")
// Yes we really do want to catch Throwable
@Override
public V apply(U input) {
    int retryAttempts = 0;
    while (true) {
        try {
            return baseFunction.apply(input);
        } catch (Throwable t) {
            if (!exceptionClass.isAssignableFrom(t.getClass()) || retryAttempts == maxRetries) {
                Throwables.propagate(t);
            }
            Tools.randomDelay(maxDelayBetweenRetries);
            retryAttempts++;
        }
    }
}
 
Example 7
Project: Equella   File: CloudServiceImpl.java   View source code 6 votes vote down vote up
@Override
public int getLiveItemVersion(String uuid)
{
	try
	{
		final String response = doGetItem(uuid, "latest", "detail");
		if( response == null )
		{
			throw new NotFoundException("No cloud item with UUID " + uuid);
		}
		final CloudItemBean cib = getObjectMapper().readValue(response, CloudItemBean.class);
		return cib.getVersion();
	}
	catch( Exception e )
	{
		throw Throwables.propagate(e);
	}
}
 
Example 8
Project: Equella   File: AbstractMetsAttachmentImportExporter.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private BinData getFileAsBinData(FileHandle file, String filename)
{
	try( InputStream in = fileSystemService.read(file, filename) )
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ByteStreams.copy(in, baos);

		BinData data = new BinData();
		data.getContent().add(new PCData(new Base64().encode(baos.toByteArray())));
		return data;
	}
	catch( IOException io )
	{
		throw Throwables.propagate(io);
	}
}
 
Example 9
Project: athena   File: OnosCopycatClient.java   View source code 6 votes vote down vote up
private <T> void submit(Query<T> query, int attemptIndex, CompletableFuture<T> future) {
    client.submit(query).whenComplete((r, e) -> {
        if (e != null) {
            if (attemptIndex < maxRetries + 1 && retryableCheck.test(Throwables.getRootCause(e))) {
                log.debug("Retry attempt ({} of {}). Failure due to {}",
                        attemptIndex, maxRetries, Throwables.getRootCause(e).getClass());
                executor.schedule(() ->
                    submit(query, attemptIndex + 1, future), delayBetweenRetriesMillis, TimeUnit.MILLISECONDS);
            } else {
                future.completeExceptionally(e);
            }
        } else {
            future.complete(r);
        }
    });
}
 
Example 10
Project: cas-5.1.0   File: CRLDistributionPointRevocationChecker.java   View source code 6 votes vote down vote up
@Override
protected boolean addCRL(final Object id, final X509CRL crl) {
    try {
        if (crl == null) {
            LOGGER.debug("No CRL was passed. Removing [{}] from cache...", id);
            return this.crlCache.remove(id);
        }

        this.crlCache.put(new Element(id, crl.getEncoded()));
        return this.crlCache.get(id) != null;

    } catch (final Exception e) {
        LOGGER.warn("Failed to add the crl entry [{}] to the cache", crl);
        throw Throwables.propagate(e);
    }
}
 
Example 11
Project: spark_deep   File: TransportRequestHandler.java   View source code 6 votes vote down vote up
private void processStreamRequest(final StreamRequest req) {
  ManagedBuffer buf;
  try {
    buf = streamManager.openStream(req.streamId);
  } catch (Exception e) {
    logger.error(String.format(
      "Error opening stream %s for request from %s", req.streamId, getRemoteAddress(channel)), e);
    respond(new StreamFailure(req.streamId, Throwables.getStackTraceAsString(e)));
    return;
  }

  if (buf != null) {
    respond(new StreamResponse(req.streamId, buf.size(), buf));
  } else {
    respond(new StreamFailure(req.streamId, String.format(
      "Stream '%s' was not found.", req.streamId)));
  }
}
 
Example 12
Project: Equella   File: PdfExtracter.java   View source code 6 votes vote down vote up
@Override
public void extractText(String mimeType, InputStream input, StringBuilder outputText, int maxSize)
	throws IOException
{
	WriteOutContentHandler wrapped = new WriteOutContentHandler(maxSize);
	ContentHandler handler = new BodyContentHandler(wrapped);
	try
	{
		Metadata meta = new Metadata();
		Parser parser = new AutoDetectParser(new TikaConfig(getClass().getClassLoader()));
		parser.parse(input, handler, meta, new ParseContext());

		appendText(handler, outputText, maxSize);
	}
	catch( Exception t )
	{
		if( wrapped.isWriteLimitReached(t) )
		{
			// keep going
			LOGGER.debug("PDF size limit reached.  Indexing truncated text");
			appendText(handler, outputText, maxSize);
			return;
		}
		throw Throwables.propagate(t);
	}
}
 
Example 13
Project: Equella   File: InstitutionServiceImpl.java   View source code 6 votes vote down vote up
private InstitutionMessageResponse sendTaskMessage(InstitutionMessage message)
{
	InstitutionMessageResponse response = taskService.postSynchronousMessage(institutionTaskId, message,
			DEFAULT_TIMEOUT);

	Map<Long, InstitutionStatus> map = response.getInstitutionMap();
	if( map != null )
	{
		setAllInstitutions(map);
	}
	Throwable error = response.getError();
	if( error != null )
	{
		Throwables.propagate(error);
	}
	return response;
}
 
Example 14
Project: ditb   File: ThriftServerRunner.java   View source code 6 votes vote down vote up
@Override
public void deleteTable(ByteBuffer in_tableName) throws IOError {
  TableName tableName = getTableName(in_tableName);
  if (LOG.isDebugEnabled()) {
    LOG.debug("deleteTable: table=" + tableName);
  }
  try {
    if (!getAdmin().tableExists(tableName)) {
      throw new IOException("table does not exist");
    }
    getAdmin().deleteTable(tableName);
  } catch (IOException e) {
    LOG.warn(e.getMessage(), e);
    throw new IOError(Throwables.getStackTraceAsString(e));
  }
}
 
Example 15
Project: Equella   File: GoogleServiceImpl.java   View source code 6 votes vote down vote up
@Override
public List<Channel> getChannels(List<String> channelIds)
{
	try
	{
		YouTube.Channels.List channels = getTubeService().channels().list("snippet");
		channels.setKey(getApiKey());
		channels.setId(Joiner.on(",").join(channelIds));
		ChannelListResponse channelListResponse = channels.execute();

		return channelListResponse.getItems();
	}
	catch( Exception ex )
	{
		throw Throwables.propagate(ex);
	}
}
 
Example 16
Project: Elasticsearch   File: ArrayMapper.java   View source code 6 votes vote down vote up
public Mapper create(String name, ObjectMapper parentMapper, ParseContext context) {
    BuilderContext builderContext = new BuilderContext(context.indexSettings(), context.path());
    try {
        Mapper.Builder<?, ?> innerBuilder = detectInnerMapper(context, name, context.parser());
        if (innerBuilder == null) {
            return null;
        }
        Mapper mapper = innerBuilder.build(builderContext);
        mapper = DocumentParser.parseAndMergeUpdate(mapper, context);
        MappedFieldType mappedFieldType = newArrayFieldType(innerBuilder);
        String fullName = context.path().fullPathAsText(name);
        mappedFieldType.setNames(new MappedFieldType.Names(fullName));
        return new ArrayMapper(
                name,
                mappedFieldType,
                mappedFieldType.clone(),
                context.indexSettings(),
                MultiFields.empty(),
                null,
                mapper);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}
 
Example 17
Project: Equella   File: FileSystemResourceLocator.java   View source code 6 votes vote down vote up
@Override
public InputStream findResource(URI systemId)
{
	try
	{
		String path = systemId.toString();
		if( !path.startsWith(basePath) )
		{
			path = PathUtils.filePath(basePath, path);
		}
		return fileSystemService.read(handle, path);
	}
	catch( IOException e )
	{
		throw Throwables.propagate(e);
	}
}
 
Example 18
Project: embulk-input-parquet_hadoop   File: ParquetHadoopInputPlugin.java   View source code 6 votes vote down vote up
@Override
public ConfigDiff transaction(ConfigSource config,
        InputPlugin.Control control)
{
    PluginTask task = config.loadConfig(PluginTask.class);
    configureParquetLogger(task);

    Path rootPath = new Path(task.getPath());

    try (PluginClassLoaderScope ignored = new PluginClassLoaderScope()) {
        Configuration conf = ConfigurationFactory.create(task);

        FileSystem fs = FileSystem.get(rootPath.toUri(), conf);
        List<FileStatus> statusList = listFileStatuses(fs, rootPath);
        if (statusList.isEmpty()) {
            throw new PathNotFoundException(rootPath.toString());
        }

        for (FileStatus status : statusList) {
            logger.debug("embulk-input-parquet_hadoop: Loading paths: {}, length: {}",
                    status.getPath(), status.getLen());
        }

        List<String> files = Lists.transform(statusList, new Function<FileStatus, String>() {
                @Nullable
                @Override
                public String apply(@Nullable FileStatus input)
                {
                    return input.getPath().toString();
                }
        });
        task.setFiles(files);
    }
    catch (IOException e) {
        throw Throwables.propagate(e);
    }

    Schema schema = newSchema();
    int taskCount = task.getFiles().size();

    return resume(task.dump(), schema, taskCount, control);
}
 
Example 19
Project: cas-5.1.0   File: HazelcastSessionConfiguration.java   View source code 6 votes vote down vote up
/**
 * Hazelcast instance that is used by the spring session
 * repository to broadcast session events. The name
 * of this bean must be left untouched.
 *
 * @return the hazelcast instance
 */
@Bean
public HazelcastInstance hazelcastInstance() {
    final Resource hzConfigResource = casProperties.getWebflow().getSession().getHzLocation();
    try {
        final URL configUrl = hzConfigResource.getURL();
        final Config config = new XmlConfigBuilder(hzConfigResource.getInputStream()).build();
        config.setConfigurationUrl(configUrl);
        config.setInstanceName(this.getClass().getSimpleName())
                .setProperty("hazelcast.logging.type", "slf4j")
                .setProperty("hazelcast.max.no.heartbeat.seconds", "300");
        return Hazelcast.newHazelcastInstance(config);
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
 
Example 20
Project: dremio-oss   File: MaterializationPlanningTask.java   View source code 6 votes vote down vote up
public List<DependencyNode> getDependencies() throws ExecutionSetupException {
  try {
    latch.await();
  } catch (InterruptedException e) {
    Throwables.propagate(e);
  }

  if (logicalPlan.get() == null) {
    if (exception.get() != null) {
      throw new ExecutionSetupException("Logical Plan cannot be created", exception.get());
    } else {
      throw new ExecutionSetupException("Logical Plan cannot be created");
    }
  }

  return constructDependencies(jobRef.get().getJobAttempt(), logicalPlan.get(), ns, accelerationService, acceleratorStorageName);
}
 
Example 21
Project: Equella   File: ChangedItemIdHtmlMunger.java   View source code 6 votes vote down vote up
@Override
public void processFiles(ItemId oldId, FileHandle oldHandle, Item newItem, FileHandle newHandle)
{
	for( Attachment attachment : newItem.getAttachments() )
	{
		if( attachment instanceof HtmlAttachment )
		{
			HtmlAttachment html = (HtmlAttachment) attachment;
			try( Reader reader = getReader(oldHandle, html.getFilename()) )
			{
				String newHtml = convertHtmlService.convert(reader, false,
					new PrefixConversion("file/" + oldId, "file/" + newItem.getUuid() + "/" + newItem.getVersion()),
					new PrefixConversion("item/" + oldId,
						"item/" + newItem.getUuid() + "/" + newItem.getVersion()));
				fileSystemService.write(newHandle, html.getFilename(),
					new ByteArrayInputStream(newHtml.getBytes(Constants.UTF8)), false);
			}
			catch( Exception e )
			{
				throw Throwables.propagate(e);
			}
		}
	}
}
 
Example 22
Project: athena   File: AtomixLeaderElectorState.java   View source code 6 votes vote down vote up
/**
 * Applies an {@link AtomixLeaderElectorCommands.Promote} commit.
 * @param commit promote commit
 * @return {@code true} if changes desired end state is achieved.
 */
public boolean promote(Commit<? extends Promote> commit) {
    try {
        String topic = commit.operation().topic();
        NodeId nodeId = commit.operation().nodeId();
        Leadership oldLeadership = leadership(topic);
        if (oldLeadership == null || !oldLeadership.candidates().contains(nodeId)) {
            return false;
        }
        elections.computeIfPresent(topic, (k, v) -> v.promote(nodeId));
        Leadership newLeadership = leadership(topic);
        if (!Objects.equal(oldLeadership, newLeadership)) {
            notifyLeadershipChange(oldLeadership, newLeadership);
        }
        return true;
    } catch (Exception e) {
        log.error("State machine operation failed", e);
        throw Throwables.propagate(e);
    } finally {
        commit.close();
    }
}
 
Example 23
Project: hbase-client   File: HUtils.java   View source code 6 votes vote down vote up
/**
 * Return string representation of all batch errors.
 *
 * @param batchResults Batch result array
 * @return
 */
public static String getBatchErrors( final Object[] batchResults ) {
    final StringBuilder errorBuilder = new StringBuilder();
    for ( int i = 0 ; i < batchResults.length ; i++ ) {
        if ( batchResults[i] instanceof Throwable ) {
            errorBuilder.append("One of batch operations raise exception:");
            errorBuilder.append(System.lineSeparator());
            errorBuilder.append(Throwables.getStackTraceAsString(
                                                (Throwable) batchResults[i]));
            errorBuilder.append(System.lineSeparator());
            errorBuilder.append(System.lineSeparator());
        }
        if ( batchResults[i] == null ) {
            errorBuilder.append("Communication error happened "
                                + "on some batch operation(op index=");
            errorBuilder.append(i);
            errorBuilder.append(')');
            errorBuilder.append(System.lineSeparator());
            errorBuilder.append(System.lineSeparator());
        }
    }
    return errorBuilder.toString();
}
 
Example 24
Project: ditb   File: ThriftServerRunner.java   View source code 6 votes vote down vote up
@Override
public void increment(TIncrement tincrement) throws IOError, TException {

  if (tincrement.getRow().length == 0 || tincrement.getTable().length == 0) {
    throw new TException("Must supply a table and a row key; can't increment");
  }

  if (conf.getBoolean(COALESCE_INC_KEY, false)) {
    this.coalescer.queueIncrement(tincrement);
    return;
  }

  Table table = null;
  try {
    table = getTable(tincrement.getTable());
    Increment inc = ThriftUtilities.incrementFromThrift(tincrement);
    table.increment(inc);
  } catch (IOException e) {
    LOG.warn(e.getMessage(), e);
    throw new IOError(Throwables.getStackTraceAsString(e));
  } finally{
    closeTable(table);
  }
}
 
Example 25
Project: talchain   File: EncryptionHandshake.java   View source code 6 votes vote down vote up
public AuthResponseMessageV4 decryptAuthResponseV4(byte[] in, ECKey myKey) {
    try {

        byte[] prefix = new byte[2];
        System.arraycopy(in, 0, prefix, 0, 2);
        short size = ByteUtil.bigEndianToShort(prefix, 0);
        byte[] ciphertext = new byte[size];
        System.arraycopy(in, 2, ciphertext, 0, size);

        byte[] plaintext = ECIESCoder.decrypt(myKey.getPrivKey(), ciphertext, prefix);

        return AuthResponseMessageV4.decode(plaintext);
    } catch (IOException | InvalidCipherTextException e) {
        throw Throwables.propagate(e);
    }
}
 
Example 26
Project: presto-rest   File: GithubRest.java   View source code 6 votes vote down vote up
@Override
public Collection<? extends List<?>> getRows(SchemaTableName schemaTableName)
{
    try {
        Response<List<Issue>> execute = service.listPrestoIssues().execute();
        if (!execute.isSuccessful()) {
            throw new IllegalStateException("Unable to read: " + execute.message());
        }
        List<Issue> issues = execute.body();
        return issues.stream()
                .map(issue -> ImmutableList.of(issue.getNumber(), issue.getState(), issue.getUser().getLogin(), issue.getTitle()))
                .collect(toList());
    }
    catch (IOException e) {
        throw Throwables.propagate(e);
    }
}
 
Example 27
Project: cas-5.1.0   File: CasConfigurationPropertiesEnvironmentManager.java   View source code 6 votes vote down vote up
/**
 * Save property for standalone profile.
 *
 * @param pair the pair
 */
public void savePropertyForStandaloneProfile(final Pair<String, String> pair) {
    try {
        final File file = getStandaloneProfileConfigurationDirectory();
        final Parameters params = new Parameters();

        final FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
                new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
                        .configure(params.properties().setFile(new File(file, getApplicationName() + ".properties")));

        final Configuration config = builder.getConfiguration();
        config.setProperty(pair.getKey(), pair.getValue());
        builder.save();
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
 
Example 28
Project: cas-5.1.0   File: OidcJsonWebKeystoreGeneratorService.java   View source code 6 votes vote down vote up
/**
 * Generate.
 */
@PostConstruct
public void generate() {
    try {
        final File file = oidcProperties.getJwksFile().getFile();
        if (!file.exists()) {
            final RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
            final JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(rsaJsonWebKey);
            final String data = jsonWebKeySet.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);
            FileUtils.write(file, data, StandardCharsets.UTF_8);
            LOGGER.debug("Generated JSON web keystore at [{}]", file);
        } else {
            LOGGER.debug("Located JSON web keystore at [{}]", file);
        }
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
 
Example 29
Project: flume-elasticsearch-sink   File: CsvSerializer.java   View source code 6 votes vote down vote up
/**
 *
 * Configure the field and its type with the custom delimiter
 */
@Override
public void configure(Context context) {
    String fields = context.getString(ES_CSV_FIELDS);
    if(fields == null) {
        Throwables.propagate(new Exception("Fields for csv files are not configured," +
                " please configured the property " + ES_CSV_FIELDS));
    }
    try {
        delimiter = context.getString(ES_CSV_DELIMITER, DEFAULT_ES_CSV_DELIMITER);
        String[] fieldTypes = fields.split(COMMA);
        for (String fieldType : fieldTypes) {
            names.add(getValue(fieldType, 0));
            types.add(getValue(fieldType, 1));
        }
    } catch(Exception e) {
        Throwables.propagate(e);
    }
}
 
Example 30
Project: Equella   File: CanvasConnectorService.java   View source code 6 votes vote down vote up
@Override
public boolean editContent(Connector connector, String username, String contentId, String title, String description)
	throws LmsUserNotFoundException
{
	final CanvasModuleItemKey moduleKey = parseContentId(contentId);
	final Request request = new Request(apiPath(connector, COURSES, moduleKey.getCourseId(), MODULES,
		moduleKey.getModuleId(), MODULE_ITEMS, moduleKey.getContentId()));
	request.setMethod(Method.PUT);
	final List<NameValue> params = new ArrayList<>();
	if( !title.isEmpty() )
	{
		params.add(new NameValue(MODULE_ITEM_TITLE, title));
	}
	// FYI, there is no description for Canvas module items.
	request.setHtmlForm(params);

	try( final Response response = getCanvasResponse(request, connector, username) )
	{
		return true;
	}
	catch( IOException io )
	{
		throw Throwables.propagate(io);
	}
}
 
Example 31
Project: CustomWorldGen   File: GameData.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void onClear(IForgeRegistry<Block> registry, Map<ResourceLocation, ?> slaveset)
{
    ClearableObjectIntIdentityMap<IBlockState> blockstateMap = (ClearableObjectIntIdentityMap<IBlockState>)slaveset.get(BLOCKSTATE_TO_ID);
    blockstateMap.clear();
    final Map<ResourceLocation, Block> originals = (Map<ResourceLocation, Block>)slaveset.get(PersistentRegistryManager.SUBSTITUTION_ORIGINALS);
    final BiMap<Block, Item> blockItemMap = (BiMap<Block, Item>)slaveset.get(BLOCK_TO_ITEM);
    for (Item it : blockItemMap.values())
    {
        if (it instanceof ItemBlock) {
            ItemBlock itemBlock = (ItemBlock)it;
            final ResourceLocation registryKey = registry.getKey(itemBlock.block);
            if (!originals.containsKey(registryKey)) continue;
            try
            {
                FinalFieldHelper.setField(blockField, itemBlock, originals.get(registryKey));
            }
            catch (Exception e)
            {
                throw Throwables.propagate(e);
            }
        }
    }
}
 
Example 32
Project: presto-kudu   File: KuduConnectorFactory.java   View source code 6 votes vote down vote up
@Override
public Connector create(final String connectorId, Map<String, String> requiredConfig, ConnectorContext context)
{
    requireNonNull(requiredConfig, "config is null");

    try {
        Bootstrap app = new Bootstrap(
                binder -> binder.bind(NodeManager.class).toInstance(context.getNodeManager()),
                new KuduModule(connectorId));

        Injector injector = app
                .strictConfig()
                .doNotInitializeLogging()
                .setRequiredConfigurationProperties(requiredConfig)
                .initialize();

        return injector.getInstance(KuduConnector.class);
    }
    catch (Exception e) {
        throw Throwables.propagate(e);
    }
}
 
Example 33
Project: athena   File: ClusterCommunicationManager.java   View source code 6 votes vote down vote up
/**
 * Performs the timed function, returning the value it would while timing the operation.
 *
 * @param timedFunction the function to be timed
 * @param meter the metering agent to be used to time the function
 * @param opName the opname to be used when starting the meter
 * @param <A> The param type of the function
 * @param <B> The return type of the function
 * @return the value returned by the timed function
 */
private <A, B> Function<A, B> timeFunction(Function<A, B> timedFunction,
                                           MeteringAgent meter, String opName) {
    checkNotNull(timedFunction);
    checkNotNull(meter);
    checkNotNull(opName);
    return new Function<A, B>() {
        @Override
        public B apply(A a) {
            final MeteringAgent.Context context = meter.startTimer(opName);
            B result = null;
            try {
                result = timedFunction.apply(a);
                context.stop(null);
                return result;
            } catch (Exception e) {
                context.stop(e);
                Throwables.propagate(e);
                return null;
            }
        }
    };
}
 
Example 34
Project: Equella   File: SerialisedValue.java   View source code 6 votes vote down vote up
public synchronized byte[] getData()
{
	if( data == null )
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try( ObjectOutputStream oos = new PluginAwareObjectOutputStream(baos) )
		{
			oos.writeObject(object);
			oos.flush();
			data = baos.toByteArray();
		}
		catch( IOException e )
		{
			Throwables.propagate(e);
		}
	}
	return data;
}
 
Example 35
Project: cas-5.1.0   File: CouchbaseClientFactory.java   View source code 5 votes vote down vote up
/**
 * Inverse of initialize, shuts down the client, cancelling connection
 * task if not completed.
 */
public void shutdown() {
    try {
        if (this.cluster != null) {
            this.cluster.disconnect();
        }
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
 
Example 36
Project: Equella   File: CanvasConnectorService.java   View source code 5 votes vote down vote up
private CanvasCourseBean getCanvasCourse(Connector connector, String username, String courseId)
{
	try
	{
		final String courseResponse = getCanvasJSONResponse(new Request(apiPath(connector, COURSES, courseId)),
			connector, username);
		final CanvasCourseBean canvasCourse = jsonMapper.readValue(courseResponse, CanvasCourseBean.class);
		return canvasCourse;
	}
	catch( Exception e )
	{
		throw Throwables.propagate(e);
	}
}
 
Example 37
Project: Equella   File: GuicePlugin.java   View source code 5 votes vote down vote up
private void checkException()
{
	if( exception != null )
	{
		LOGGER.error("Error creating injector for:" + pluginId, exception); //$NON-NLS-1$
		throw Throwables.propagate(exception);
	}
}
 
Example 38
Project: cas-5.1.0   File: EncodedTicket.java   View source code 5 votes vote down vote up
/**
 * Creates a new encoded ticket using the given encoder to encode the given
 * source ticket.
 *
 * @param encodedTicket   the encoded ticket
 * @param encodedTicketId the encoded ticket id
 */
public EncodedTicket(final ByteSource encodedTicket, final String encodedTicketId) {
    try {
        this.id = encodedTicketId;
        this.encodedTicket = encodedTicket.read();
    } catch (final IOException e) {
        throw Throwables.propagate(e);
    }
}
 
Example 39
Project: Equella   File: FlickrServiceImpl.java   View source code 5 votes vote down vote up
/**
 * Having what we presume is an email, query Flickr for the UserId string
 * 
 * @param presumedEmail
 * @return Flickr user's Id string if found, otherwise null
 * @throws FlickrException Flickr throws with a user not found message if
 *             such applies
 */
private String queryFlickrOnUsername(Flickr flickr, String presumedUsername) throws FlickrException
{
	String flickrUserId = null;
	PeopleInterface pi = flickr.getPeopleInterface();
	User flickrUser = null;
	try
	{
		flickrUser = pi.findByUsername(presumedUsername);
	}
	catch( FlickrException fe ) // NOSONAR - throw these in the raw, wrap
								// any others
	{
		throw fe;
	}
	catch( Exception e )
	{
		throw Throwables.propagate(e);
	}

	if( flickrUser != null )
	{
		flickrUserId = flickrUser.getId();
	}

	return flickrUserId;
}
 
Example 40
Project: cas-5.1.0   File: BaseDuoAuthenticationService.java   View source code 5 votes vote down vote up
/**
 * Sign http users request http.
 *
 * @param request the request
 * @return the http
 */
protected Http signHttpUserPreAuthRequest(final Http request) {
    try {
        request.signRequest(
                duoProperties.getDuoIntegrationKey(),
                duoProperties.getDuoSecretKey());
        return request;
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}