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

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project aerogear-controller, under directory /src/main/java/org/jboss/aerogear/controller/router/.

Source file: DefaultRouter.java

  19 
vote

@Override public void dispatch(HttpServletRequest request,HttpServletResponse response,FilterChain chain) throws ServletException {
  try {
    final String requestPath=extractPath(request);
    Route route=routes.routeFor(extractMethod(request),requestPath);
    Object[] params;
    if (route.isSecured()) {
      securityProvider.isRouteAllowed(route);
    }
    if (route.isParameterized()) {
      params=extractPathParameters(requestPath,route);
    }
 else {
      params=extractParameters(request,route);
    }
    Object result=route.getTargetMethod().invoke(getController(route),params);
    String viewPath=viewResolver.resolveViewPathFor(route);
    View view=new View(viewPath,result);
    if (view.hasModelData()) {
      request.setAttribute(view.getModelName(),view.getModel());
    }
    request.getRequestDispatcher(view.getViewPath()).forward(request,response);
  }
 catch (  Exception e) {
    if (e instanceof HttpStatusAwareException) {
      response.setStatus(((HttpStatusAwareException)e).getStatus());
    }
    final Throwable rootCause=Throwables.getRootCause(e);
    final Route errorRoute=routes.routeFor(rootCause);
    invokeErrorRoute(errorRoute,rootCause);
    forwardErrorToView(errorRoute,rootCause,request,response);
  }
}
 

Example 2

From project airlift, under directory /discovery/src/test/java/io/airlift/discovery/client/.

Source file: TestServiceTypes.java

  19 
vote

public TestServiceTypes(){
  try {
    this.appleServiceType=getClass().getDeclaredField("appleServiceType").getAnnotation(ServiceType.class);
    this.bananaServiceType=getClass().getDeclaredField("bananaServiceType").getAnnotation(ServiceType.class);
  }
 catch (  NoSuchFieldException e) {
    throw Throwables.propagate(e);
  }
}
 

Example 3

From project android-rackspacecloud, under directory /extensions/httpnio/src/main/java/org/jclouds/http/pool/.

Source file: ConnectionPoolTransformingHttpCommandExecutorService.java

  19 
vote

private void takeACommandOffTheQueueAndInvokeIt() throws InterruptedException {
  HttpCommandRendezvous<?> rendezvous=commandQueue.poll(1,TimeUnit.SECONDS);
  if (rendezvous != null) {
    try {
      invoke(rendezvous);
    }
 catch (    Exception e) {
      Throwables.propagateIfPossible(e,InterruptedException.class);
      logger.error(e,"Error processing command %s",rendezvous.getCommand());
    }
  }
}
 

Example 4

From project android_external_guava, under directory /src/com/google/common/util/concurrent/.

Source file: AbstractExecutionThreadService.java

  19 
vote

@Override protected final void doStart(){
  executor().execute(new Runnable(){
    public void run(){
      try {
        startUp();
        notifyStarted();
        if (isRunning()) {
          try {
            AbstractExecutionThreadService.this.run();
          }
 catch (          Throwable t) {
            try {
              shutDown();
            }
 catch (            Exception ignored) {
            }
            throw t;
          }
        }
        shutDown();
        notifyStopped();
      }
 catch (      Throwable t) {
        notifyFailed(t);
        throw Throwables.propagate(t);
      }
    }
  }
);
}
 

Example 5

From project appdriver, under directory /android/src/com/google/android/testing/nativedriver/client/.

Source file: AndroidNativeDriver.java

  19 
vote

protected String imageToBase64Png(BufferedImage image){
  ByteArrayOutputStream rawPngStream=new ByteArrayOutputStream();
  try {
    if (!writeImageAsPng(image,rawPngStream)) {
      throw new RuntimeException("This Java environment does not support converting to PNG.");
    }
  }
 catch (  IOException exception) {
    Throwables.propagate(exception);
  }
  byte[] rawPngBytes=rawPngStream.toByteArray();
  return new Base64Encoder().encode(rawPngBytes);
}
 

Example 6

From project atlas, under directory /src/main/java/com/ning/atlas/bus/.

Source file: EventBus.java

  19 
vote

/** 
 * Flattens a class's type hierarchy into a set of Class objects.  The set will include all superclasses (transitively), and all interfaces implemented by these superclasses.
 * @param concreteClass  class whose type hierarchy will be retrieved.
 * @return {@code clazz}'s complete type hierarchy, flattened and uniqued.
 */
@VisibleForTesting Set<Class<?>> flattenHierarchy(Class<?> concreteClass){
  try {
    return flattenHierarchyCache.get(concreteClass);
  }
 catch (  ExecutionException e) {
    throw Throwables.propagate(e.getCause());
  }
}
 

Example 7

From project Cafe, under directory /webapp/src/org/openqa/selenium/browserlaunchers/.

Source file: LauncherUtils.java

  19 
vote

public static void copySingleFileWithOverwrite(File sourceFile,File destFile,boolean overwrite){
  if (!sourceFile.exists()) {
    throw new RuntimeException("Source file does not exist: " + sourceFile);
  }
  if (!sourceFile.isFile()) {
    throw new RuntimeException("Source is not a single file: " + sourceFile);
  }
  if (!overwrite && destFile.exists()) {
    throw new RuntimeException("Destination file already exists: " + destFile);
  }
  try {
    FileHandler.copy(sourceFile,destFile);
  }
 catch (  IOException e) {
    throw Throwables.propagate(e);
  }
}
 

Example 8

From project closure-templates, under directory /java/src/com/google/template/soy/javasrc/dyncompile/.

Source file: ClasspathUtils.java

  19 
vote

/** 
 * The resource paths for each class loadable by the Classloader in the given package (and subpackages iff  {@code isRecursive}). E.g. the resource path for a class  {@code java.lang.Class} is {@code java/lang/Class.class}. Resource paths are URL paths, so the file separator  {@code /} is used regardless of theunderlying file system.
 * @param isRecursive True iff class enumeration should recurse into sub-packages.
 * @return The resource path for each loadable class in no particular order.
 */
static Iterable<String> getClassResourcePaths(String packageName,boolean isRecursive) throws IOException {
  ImmutableList.Builder<String> classResourcePaths=ImmutableList.builder();
  String relativeUrl=packageName.replace('.','/');
  PackageContent packageContent=getPackagePathToContentMap().get(relativeUrl);
  if (packageContent != null) {
    packageContent.enumerateResources(classResourcePaths,isRecursive);
  }
  @Nullable URL url=CLASS_LOADER.getResource(relativeUrl);
  if (url != null) {
    String protocol=url.getProtocol();
    if ("file".equals(protocol)) {
      try {
        searchFileTree(packageName,new File(url.toURI()),isRecursive,classResourcePaths);
      }
 catch (      URISyntaxException ex) {
        Throwables.propagate(ex);
      }
    }
 else     if ("jar".equals(protocol)) {
      searchZipFile(packageName,isRecursive,url,classResourcePaths);
    }
  }
  return classResourcePaths.build();
}
 

Example 9

From project cloud-management, under directory /src/main/java/com/proofpoint/cloudmanagement/service/inventoryclient/.

Source file: InventoryClient.java

  19 
vote

public void notifyInstanceCreated(String instanceId){
  try {
    String inventoryName=getPcmSystemName(instanceId);
    InventorySystem inventorySystem=new InventorySystem(inventoryName);
    inventorySystem.setPicInstance(instanceId);
    patchSystem(inventorySystem);
  }
 catch (  Exception e) {
    log.error("Expected to get a server name from inventory for instanceId [" + instanceId + "] but caught exception "+ e.getMessage(),e);
    throw Throwables.propagate(e);
  }
}
 

Example 10

From project components-ness-hbase, under directory /src/main/java/com/nesscomputing/hbase/.

Source file: HBaseWriter.java

  19 
vote

@Override public Put apply(@Nullable final Callable<Put> callable){
  try {
    return callable == null ? null : callable.call();
  }
 catch (  Exception e) {
    throw Throwables.propagate(e);
  }
}
 

Example 11

From project components-ness-httpclient, under directory /client/src/main/java/com/nesscomputing/httpclient/response/.

Source file: NumberContentConverter.java

  19 
vote

protected NumberContentConverter(final Class<T> numberClass,final boolean ignore404){
  try {
    this.numberClass=numberClass;
    this.ignore404=ignore404;
    this.valueOfMethod=numberClass.getMethod("valueOf",String.class);
    this.emptyValue=numberClass.cast(safeInvoke("0"));
  }
 catch (  NoSuchMethodException nsme) {
    throw Throwables.propagate(nsme);
  }
}
 

Example 12

From project components-ness-httpserver_1, under directory /src/main/java/com/nesscomputing/httpserver/.

Source file: AbstractJetty8HttpServer.java

  19 
vote

@Override @OnStage(LifecycleStage.STOP) public void stop(){
  Preconditions.checkNotNull(server,"Server was never started!");
  try {
    server.stop();
  }
 catch (  Exception e) {
    throw Throwables.propagate(e);
  }
  server.setHandler(null);
  server.setStopAtShutdown(false);
  Preconditions.checkState(server.isStopped(),"Server did not stop");
  server=null;
}
 

Example 13

From project components-ness-integration-testing, under directory /src/main/java/com/nesscomputing/testing/tweaked/.

Source file: ModuleProvider.java

  19 
vote

public Module getModule(@Nonnull final Config config){
  if (module != null) {
    return module;
  }
  try {
    if (this.moduleClass == null) {
      this.moduleClass=Class.forName(moduleClassName);
    }
    try {
      return Module.class.cast(moduleClass.getConstructor(Config.class).newInstance(config));
    }
 catch (    NoSuchMethodException nsme) {
      return Module.class.cast(moduleClass.getConstructor().newInstance());
    }
  }
 catch (  Exception e) {
    throw Throwables.propagate(e);
  }
}
 

Example 14

From project components-ness-jackson, under directory /src/main/java/com/nesscomputing/jackson/.

Source file: SerializerBinderBuilderImpl.java

  19 
vote

@Override public Function<In,Out> get(){
  return new Function<In,Out>(){
    @Override public Out apply(    In input){
      try {
        return serialize(input);
      }
 catch (      Exception e) {
        try {
          action.call(e);
        }
 catch (        Exception e1) {
          throw Throwables.propagate(e1);
        }
        return null;
      }
    }
  }
;
}
 

Example 15

From project components-ness-lifecycle, under directory /src/main/java/com/nesscomputing/lifecycle/guice/.

Source file: LifecycleAnnotationFinder.java

  19 
vote

void visit(Lifecycle lifecycle){
  method.setAccessible(true);
  lifecycle.addListener(stage,new LifecycleListener(){
    @Override public void onStage(    LifecycleStage lifecycleStage){
      try {
        method.invoke(object);
      }
 catch (      IllegalAccessException e) {
        Throwables.propagate(e);
      }
catch (      InvocationTargetException e) {
        if (e.getCause() == null) {
          Throwables.propagate(e);
        }
        Throwables.propagate(e.getCause());
      }
    }
  }
);
}
 

Example 16

From project components-ness-mongo, under directory /src/main/java/com/nesscomputing/mongo/.

Source file: MongoWriter.java

  19 
vote

@Override public DBObject apply(@Nullable final Callable<DBObject> callable){
  try {
    return callable == null ? null : callable.call();
  }
 catch (  Exception e) {
    throw Throwables.propagate(e);
  }
}
 

Example 17

From project components-ness-pg, under directory /pg/src/main/java/com/nesscomputing/db/postgres/junit/.

Source file: PostgresRules.java

  19 
vote

/** 
 * Returns a  {@link TestRule} to create and load a postgres database with a set of personalities.This method takes an  {@link java.net.URL} as the base to allow one line usage with {@link Resources#getResource(Class,String)}.
 * @param baseUri Base to load personalities from.
 * @param personalities List of personalities to load.
 * @return A {@link TestRule} to use in junit unit tests.
 */
public static LocalPostgresPreparerTestRule databasePreparerRule(final URL baseUrl,final String... personalities){
  try {
    final URI baseUri=baseUrl.toURI();
    return new LocalPostgresPreparerTestRule(DatabasePreparers.forPostgres(baseUri),personalities);
  }
 catch (  URISyntaxException use) {
    throw Throwables.propagate(use);
  }
}
 

Example 18

From project cp-common-utils, under directory /src/com/clarkparsia/common/iterations/.

Source file: TransformException.java

  19 
vote

@SuppressWarnings("unchecked") private RuntimeException wrapException(Throwable e) throws OE {
  Throwables.propagateIfPossible(e);
  try {
    throw mFunc.apply((IE)e);
  }
 catch (  Throwable ignore) {
    throw new RuntimeException(e);
  }
}
 

Example 19

From project event-collector, under directory /event-collector/src/main/java/com/proofpoint/event/collector/.

Source file: S3StorageHelper.java

  19 
vote

public static URI getS3Directory(URI location){
  checkValidS3Uri(location);
  String path=location.getPath();
  if (path.contains("/")) {
    path=path.substring(0,path.lastIndexOf('/') + 1);
  }
  try {
    return new URI(location.getScheme(),location.getHost(),path,null);
  }
 catch (  URISyntaxException e) {
    throw Throwables.propagate(e);
  }
}
 

Example 20

From project flume, under directory /flume-ng-channels/flume-file-channel/src/main/java/org/apache/flume/channel/file/encryption/.

Source file: AESCTRNoPaddingProvider.java

  19 
vote

private static byte[] doFinal(Cipher cipher,byte[] input){
  try {
    return cipher.doFinal(input);
  }
 catch (  Exception e) {
    String msg="Unable to encrypt or decrypt data " + TYPE + " input.length "+ input.length;
    LOG.error(msg,e);
    throw Throwables.propagate(e);
  }
}
 

Example 21

From project FML, under directory /common/cpw/mods/fml/common/discovery/.

Source file: ModDiscoverer.java

  19 
vote

public List<ModContainer> identifyMods(){
  List<ModContainer> modList=Lists.newArrayList();
  for (  ModCandidate candidate : candidates) {
    try {
      List<ModContainer> mods=candidate.explore(dataTable);
      if (mods.isEmpty() && !candidate.isClasspath()) {
        nonModLibs.add(candidate.getModContainer());
      }
 else {
        modList.addAll(mods);
      }
    }
 catch (    LoaderException le) {
      FMLLog.log(Level.WARNING,le,"Identified a problem with the mod candidate %s, ignoring this source",candidate.getModContainer());
    }
catch (    Throwable t) {
      Throwables.propagate(t);
    }
  }
  return modList;
}
 

Example 22

From project galaxy, under directory /src/co/paralleluniverse/common/io/.

Source file: Streamables.java

  19 
vote

public T construct(byte type){
  try {
    if (constructorWithQualifier)     return constructor.newInstance(type);
 else     return constructor.newInstance();
  }
 catch (  InstantiationException ex) {
    throw Throwables.propagate(ex);
  }
catch (  IllegalAccessException ex) {
    throw Throwables.propagate(ex);
  }
catch (  IllegalArgumentException ex) {
    throw Throwables.propagate(ex);
  }
catch (  InvocationTargetException ex) {
    throw Throwables.propagate(ex);
  }
}
 

Example 23

From project guice-jit-providers, under directory /extensions/servlet/src/com/google/inject/servlet/.

Source file: FilterChainInvocation.java

  19 
vote

public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse) throws IOException, ServletException {
  GuiceFilter.Context previous=GuiceFilter.localContext.get();
  HttpServletRequest request=(HttpServletRequest)servletRequest;
  HttpServletResponse response=(HttpServletResponse)servletResponse;
  HttpServletRequest originalRequest=(previous != null) ? previous.getOriginalRequest() : request;
  GuiceFilter.localContext.set(new GuiceFilter.Context(originalRequest,request,response));
  try {
    Filter filter=findNextFilter(request);
    if (filter != null) {
      filter.doFilter(servletRequest,servletResponse,this);
    }
 else {
      final boolean serviced=servletPipeline.service(servletRequest,servletResponse);
      if (!serviced) {
        proceedingChain.doFilter(servletRequest,servletResponse);
      }
    }
  }
 catch (  Throwable t) {
    if (!cleanedStacks) {
      cleanedStacks=true;
      pruneStacktrace(t);
    }
    Throwables.propagateIfInstanceOf(t,ServletException.class);
    Throwables.propagateIfInstanceOf(t,IOException.class);
    throw Throwables.propagate(t);
  }
 finally {
    GuiceFilter.localContext.set(previous);
  }
}
 

Example 24

From project hdfs-nfs-proxy, under directory /src/main/java/com/cloudera/hadoop/hdfs/nfs/nfs4/.

Source file: FileBackedWrite.java

  19 
vote

public FileBackedWrite(File backingFile,String name,int xid,long offset,boolean sync,byte[] data,int start,int length){
  super(name,xid,offset,sync);
  this.backingFile=backingFile;
  this.length=length;
  this.hashCode=getHashCode(offset,data,start,length);
  this.size=getSize(name,length);
  try {
    writeBytes(data,start,length);
  }
 catch (  IOException e) {
    try {
      writeBytes(data,start,length);
    }
 catch (    IOException ex) {
      Throwables.propagate(ex);
    }
  }
}
 

Example 25

From project jagger, under directory /chassis/coordinator.http/src/main/java/com/griddynamics/jagger/coordinator/http/server/.

Source file: CoordinatorAdapter.java

  19 
vote

private AbstractProxyWorker createProxyWorker(final Set<Qualifier<Command<Serializable>>> qualifiers){
  return new AbstractProxyWorker(qualifiers){
    @Override protected Serializable handleCommand(    Command<Serializable> command,    NodeContext nodeContext){
      log.debug("Handling command {} for node {}",command,nodeContext);
      AsyncRunner<Command<Serializable>,Serializable> packExchanger=exchangers.get(nodeContext.getId());
      FutureAsyncCallback<Serializable> callback=FutureAsyncCallback.create();
      packExchanger.run(command,callback);
      SettableFuture<Serializable> future=callback.getFuture();
      try {
        log.debug("Waiting for command completion");
        return future.get();
      }
 catch (      InterruptedException e) {
        throw Throwables.propagate(e);
      }
catch (      ExecutionException e) {
        throw Throwables.propagate(e);
      }
    }
  }
;
}
 

Example 26

From project jclouds-abiquo, under directory /core/src/main/java/org/jclouds/abiquo/events/handlers/.

Source file: BlockingEventHandler.java

  19 
vote

/** 
 * Blocks the thread until all locked objects have been released.
 */
public void lock(){
  if (!lockedObjects.isEmpty()) {
    try {
      completeSignal=new CountDownLatch(lockedObjects.size());
      logger.debug("creating lock for %s object(s)",lockedObjects.size());
      completeSignal.await();
    }
 catch (    InterruptedException ex) {
      Throwables.propagate(ex);
    }
  }
 else {
    logger.debug("there is nothing to watch. Ignoring lock.");
  }
}
 

Example 27

From project jclouds-bean-cleaner, under directory /src/main/java/org/jclouds/cleanup/.

Source file: DomainObjectDocletCleaner.java

  19 
vote

/** 
 * Route into doclet processing
 * @see com.sun.javadoc.Doclet#start(com.sun.javadoc.RootDoc)
 */
@SuppressWarnings("unused") public static boolean start(RootDoc root){
  cfg.setTemplateLoader(new ClassTemplateLoader(DomainObjectDocletCleaner.class,"/"));
  try {
    readOptions(root.options());
    ClassDocParser parser=new ClassDocParser();
    Template template=cfg.getTemplate(parseOptions.getFormat() == ParseOptions.Format.MINIMAL ? "MinimalBean.ftl" : "Bean.ftl");
    List<Bean> beans=Lists.newArrayList();
    for (    ClassDoc clazz : root.classes()) {
      if (clazz.containingClass() == null && clazz.isClass() && !clazz.isEnum()) {
        beans.add(parser.parseBean(clazz,parseOptions,false));
      }
    }
    for (    Bean bean : beans) {
      if (bean.getAllFields().size() > 0) {
        String className=bean.getType();
        String packageName=bean.getPackageName();
        File outputFile=new File(outputPath,packageName.replaceAll("\\.",File.separator) + File.separator + className+ ".java");
        outputFile.getParentFile().mkdirs();
        LOG.info("Processing " + bean.getType() + " writing to "+ outputFile.getAbsolutePath());
        template.process(bean,new FileWriter(outputFile));
      }
    }
    return true;
  }
 catch (  Exception e) {
    throw Throwables.propagate(e);
  }
}
 

Example 28

From project jclouds-chef, under directory /core/src/main/java/org/jclouds/chef/config/.

Source file: ChefParserModule.java

  19 
vote

@Override public PrivateKey deserialize(JsonElement json,Type typeOfT,JsonDeserializationContext context) throws JsonParseException {
  String keyText=json.getAsString().replaceAll("\\n","\n");
  try {
    return crypto.rsaKeyFactory().generatePrivate(Pems.privateKeySpec(InputSuppliers.of(keyText)));
  }
 catch (  UnsupportedEncodingException e) {
    Throwables.propagate(e);
    return null;
  }
catch (  InvalidKeySpecException e) {
    Throwables.propagate(e);
    return null;
  }
catch (  IOException e) {
    Throwables.propagate(e);
    return null;
  }
}
 

Example 29

From project jclouds-examples, under directory /blobstore-hdfs/src/main/java/org/jclouds/examples/blobstore/hdfs/io/payloads/.

Source file: HdfsPayload.java

  19 
vote

public InputStream getInput(){
  try {
    return content.getFileSystem(configuration).open(content);
  }
 catch (  IOException e) {
    Throwables.propagate(e);
    return null;
  }
}
 

Example 30

From project jmxutils, under directory /src/main/java/org/weakref/jmx/guice/.

Source file: MapExportBinder.java

  19 
vote

public void withGeneratedName(final NamingFunction<V> valueNamingFunction){
  ObjectNameFunction<Map.Entry<K,V>> objectNameFunction=new ObjectNameFunction<Map.Entry<K,V>>(){
    public ObjectName name(    Map.Entry<K,V> entry){
      try {
        String itemName=valueNamingFunction.name(entry.getValue());
        return new ObjectName(ObjectNames.generatedNameOf(valueClass,itemName));
      }
 catch (      MalformedObjectNameException e) {
        throw Throwables.propagate(e);
      }
    }
  }
;
  binder.addBinding().toInstance(new MapMapping<K,V>(keyClass,valueClass,objectNameFunction));
}
 

Example 31

From project l2jserver2, under directory /l2jserver2-gameserver/l2jserver2-gameserver-core/src/main/java/com/l2jserver/game/net/handler/.

Source file: Lineage2PacketHandler.java

  19 
vote

@Override public void exceptionCaught(ChannelHandlerContext ctx,ExceptionEvent event) throws Exception {
  final Throwable e=event.getCause();
  try {
    if (e instanceof ChannelException)     return;
    if (e instanceof IOException)     return;
    if (!connection.isConnected())     return;
    final String exception=Throwables.getStackTraceAsString(e).replaceAll("\n","<br>").replace("	","");
    final HtmlTemplate template=new HtmlTemplate("Java Exception"){
      @Override public void build(      MarkupTag body){
        body.text(exception);
      }
    }
;
    connection.sendHTML(template);
    connection.sendActionFailed();
    final String[] lines=Throwables.getStackTraceAsString(e).split("\n");
    for (    final String line : lines) {
      connection.sendMessage(line);
    }
  }
  finally {
    e.printStackTrace();
  }
}
 

Example 32

From project leveldb, under directory /leveldb/src/main/java/org/iq80/leveldb/impl/.

Source file: DbImpl.java

  19 
vote

public Snapshot writeInternal(WriteBatchImpl updates,WriteOptions options) throws DBException {
  checkBackgroundException();
  mutex.lock();
  try {
    makeRoomForWrite(false);
    final long sequenceBegin=versions.getLastSequence() + 1;
    final long sequenceEnd=sequenceBegin + updates.size() - 1;
    versions.setLastSequence(sequenceEnd);
    Slice record=writeWriteBatch(updates,sequenceBegin);
    try {
      log.addRecord(record,options.sync());
    }
 catch (    IOException e) {
      throw Throwables.propagate(e);
    }
    updates.forEach(new InsertIntoHandler(memTable,sequenceBegin));
    if (options.snapshot()) {
      return new SnapshotImpl(versions.getCurrent(),sequenceEnd);
    }
 else {
      return null;
    }
  }
  finally {
    mutex.unlock();
  }
}
 

Example 33

From project maven-git-commit-id-plugin, under directory /src/main/java/pl/project13/jgit/.

Source file: DescribeCommand.java

  19 
vote

private Map<ObjectId,String> findTagObjectIds(@NotNull Repository repo,boolean tagsFlag){
  Map<ObjectId,String> commitIdsToTagNames=newHashMap();
  RevWalk walk=new RevWalk(repo);
  try {
    walk.markStart(walk.parseCommit(repo.resolve("HEAD")));
    List<Ref> tagRefs=Git.wrap(repo).tagList().call();
    for (    Ref tagRef : tagRefs) {
      walk.reset();
      String name=tagRef.getName();
      ObjectId resolvedCommitId=repo.resolve(name);
      try {
        RevTag revTag=walk.parseTag(resolvedCommitId);
        ObjectId taggedCommitId=revTag.getObject().getId();
        commitIdsToTagNames.put(taggedCommitId,trimFullTagName(name));
      }
 catch (      IncorrectObjectTypeException ex) {
        if (tagsFlag) {
          log("Including lightweight tag [%s]",name);
          commitIdsToTagNames.put(resolvedCommitId,trimFullTagName(name));
        }
      }
catch (      Exception ignored) {
        log("Failed while parsing [%s] -- %s",tagRef,ignored);
      }
    }
    return commitIdsToTagNames;
  }
 catch (  Exception e) {
    log("Unable to locate tags\n[%s]",Throwables.getStackTraceAsString(e));
  }
 finally {
    walk.release();
  }
  return Collections.emptyMap();
}
 

Example 34

From project metric, under directory /src/main/java/com/gnapse/metric/app/.

Source file: Main.java

  19 
vote

/** 
 * Returns the folder where the application binaries are located.  If the application is being run from a  {@code .jar} file, this returns the absolute path of the folder where the{@code .jar} file is located.  If the application is being run directly from the treestructure with compiled  {@code .class} files, this method returns the absolute path of theparent of the root folder where the class files tree structure is located.
 * @return the absolute path of the folder where the application's binary files are located
 */
private static String getAppFolder(){
  try {
    return new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getAbsoluteFile().getParentFile().getAbsolutePath();
  }
 catch (  URISyntaxException e) {
    throw Throwables.propagate(e);
  }
}
 

Example 35

From project monitor-event-tap, under directory /src/main/java/com/proofpoint/event/monitor/.

Source file: MonitorsProvider.java

  19 
vote

@Override public synchronized Set<Monitor> get(){
  if (monitors == null) {
    try {
      String json=Files.toString(new File(monitorRulesFile),Charsets.UTF_8);
      monitors=monitorLoader.load(json);
    }
 catch (    IOException e) {
      throw Throwables.propagate(e);
    }
    for (    Monitor monitor : monitors) {
      monitor.start();
    }
    Set<String> eventTypes=newHashSet();
    for (    Monitor monitor : monitors) {
      eventTypes.add(monitor.getEventType());
    }
    if (announcer != null) {
      for (      String eventType : eventTypes) {
        ServiceAnnouncement announcement=ServiceAnnouncement.serviceAnnouncement("eventTap").addProperty("http",httpServerInfo.getHttpUri().toString() + "/v1/event").addProperty("tapId",flowId).addProperty("flowId",flowId).addProperty("eventType",eventType).build();
        announcer.addServiceAnnouncement(announcement);
        announcements.add(announcement);
      }
    }
    if (exporter != null) {
      for (      Monitor monitor : monitors) {
        String name=generatedNameOf(Monitor.class,named(monitor.getName()));
        exporter.export(name,monitor);
        mbeanNames.add(name);
      }
    }
  }
  return monitors;
}
 

Example 36

From project nexus-obr-plugin, under directory /nexus-obr-testsuite/src/test/java/org/sonatype/nexus/plugin/obr/test/.

Source file: ObrITSupport.java

  19 
vote

protected void createObrHostedRepository(final String repositoryId){
  final RepositoryResource repo=new RepositoryResource();
  repo.setId(repositoryId);
  repo.setRepoType("hosted");
  repo.setName(repositoryId);
  repo.setProvider("obr-proxy");
  repo.setRepoPolicy(RepositoryPolicy.RELEASE.name());
  repo.setChecksumPolicy(ChecksumPolicy.WARN.name());
  repo.setBrowseable(true);
  repo.setIndexable(false);
  repo.setExposed(true);
  try {
    repositories().createRepository(repo);
  }
 catch (  final IOException e) {
    throw Throwables.propagate(e);
  }
}
 

Example 37

From project objectos-blog-engine, under directory /src/main/java/br/com/objectos/blog/.

Source file: PostTemplateLoaderGuice.java

  19 
vote

@Override public PostTemplate loadFromFile(File template) throws BlogException {
  try {
    BufferedReader reader=Files.newReader(template,Charsets.UTF_8);
    String _template=CharStreams.toString(reader);
    return load(_template);
  }
 catch (  FileNotFoundException e) {
    throw Throwables.propagate(e);
  }
catch (  IOException e) {
    throw new PostTemplateException(e);
  }
}
 

Example 38

From project objectos-comuns-dbunit, under directory /src/main/java/br/com/objectos/comuns/testing/dbunit/.

Source file: DBUnit.java

  19 
vote

private void tryToExecute(List<DataSupplier> datasets){
  IDatabaseConnection conn=connections.get();
  try {
    disableReferentialIntegrity(conn);
    for (    DataSupplier op : datasets) {
      try {
        IDataSet dataSet=op.get();
        DatabaseOperation operacao=op.getOperation();
        DatabaseOperation trx=DatabaseOperation.TRANSACTION(operacao);
        trx.execute(conn,dataSet);
      }
 catch (      Exception e) {
        Throwables.propagateIfInstanceOf(e,DBUnitSetupException.class);
        String msg=String.format("Could not load DBUnit file: %s",op.getFilename());
        throw new DBUnitSetupException(msg,e);
      }
    }
    enableReferentialIntegrity(conn);
  }
  finally {
    try {
      conn.close();
    }
 catch (    SQLException e) {
    }
  }
}
 

Example 39

From project objectos-comuns-jdbc, under directory /src/main/java/br/com/objectos/comuns/relational/jdbc/.

Source file: InsertOperationException.java

  19 
vote

public boolean isIntegrityViolation(){
  Throwable cause=getCause();
  List<Throwable> causes=Throwables.getCausalChain(cause);
  Iterable<SQLIntegrityConstraintViolationException> iter;
  iter=Iterables.filter(causes,SQLIntegrityConstraintViolationException.class);
  List<SQLIntegrityConstraintViolationException> integrity=ImmutableList.copyOf(iter);
  return !integrity.isEmpty();
}