public T instance() {
   T singletonInstancePerThread = null;
   // use weak reference to prevent cyclic reference during GC
   WeakReference<T> ref = (WeakReference<T>) perThreadCache.get();
   // singletonInstancePerThread=perThreadCache.get();
   // if (singletonInstancePerThread==null) {
   if (ref == null || ref.get() == null) {
     Class<T> clazz = null;
     try {
       clazz =
           (Class<T>) Thread.currentThread().getContextClassLoader().loadClass(singletonClassName);
       singletonInstancePerThread = clazz.newInstance();
     } catch (Exception ignore) {
       try {
         clazz = (Class<T>) Class.forName(singletonClassName);
         singletonInstancePerThread = clazz.newInstance();
       } catch (Exception ignore2) {
       }
     }
     perThreadCache.set(new WeakReference<T>(singletonInstancePerThread));
   } else {
     singletonInstancePerThread = ref.get();
   }
   return singletonInstancePerThread;
 }
Example #2
0
    /*
     * (non-Javadoc)
     * @see android.os.AsyncTask#doInBackground(Params[])
     */
    @Override
    protected Boolean doInBackground(String... params) {
      if (mTarget.get() != null) {
        try {
          IssueCreateActivity activity = mTarget.get();
          GitHubServiceFactory factory = GitHubServiceFactory.newInstance();
          IssueService service = factory.createIssueService();
          Authentication auth =
              new LoginPasswordAuthentication(
                  mTarget.get().getAuthUsername(), mTarget.get().getAuthPassword());
          service.setAuthentication(auth);

          // CheckBox cbSign = (CheckBox) activity.findViewById(R.id.cb_sign);
          String comment = params[1];
          //                    if (cbSign.isChecked()) {
          //                        comment = comment + "\n\n" +
          // activity.getResources().getString(R.string.sign);
          //                    }

          service.createIssue(activity.mUserLogin, activity.mRepoName, params[0], comment);
          return true;
        } catch (GitHubException e) {
          Log.e(Constants.LOG_TAG, e.getMessage(), e);
          mException = true;
          return null;
        }
      } else {
        return false;
      }
    }
 @Override
 public void onDrawerOpened(View drawerView) {
   if (Ref.alive(activityRef)) {
     UIUtils.hideKeyboardFromActivity(activityRef.get());
     activityRef.get().invalidateOptionsMenu();
   }
 }
  @Override
  protected void onPostExecute(PlaceRecord result) {

    if (null != result && null != mParent.get()) {
      mParent.get().addNewPlace(result);
    }
  }
Example #5
0
  /** Initiate the service binding protocol. */
  @Override
  public void bindService() {
    Log.d(TAG, "calling bindService()");

    // Launch the Acronym Bound Services if they aren't already
    // running via a call to bindService(), which binds this
    // activity to the AcronymService* if they aren't already
    // bound.
    if (mServiceConnectionSync.getInterface() == null)
      mActivity
          .get()
          .getApplicationContext()
          .bindService(
              AcronymServiceSync.makeIntent(mActivity.get()),
              mServiceConnectionSync,
              Context.BIND_AUTO_CREATE);

    if (mServiceConnectionAsync.getInterface() == null)
      mActivity
          .get()
          .getApplicationContext()
          .bindService(
              AcronymServiceAsync.makeIntent(mActivity.get()),
              mServiceConnectionAsync,
              Context.BIND_AUTO_CREATE);
  }
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
   if (mContextActivity.get() != null) {
     mContextActivity.get().getMenuInflater().inflate(R.menu.menu_photo_viewer, menu);
   }
   return true;
 }
Example #7
0
  @SuppressWarnings("deprecation")
  public void setCircleButtonStateListDrawable(
      View circleButton, int radius, int pressedColor, int normalColor) {
    WeakReference<Bitmap> imagePressed =
        new WeakReference<>(Bitmap.createBitmap(2 * radius, 2 * radius, Bitmap.Config.ARGB_8888));
    Canvas canvasPressed = new Canvas(imagePressed.get());
    Paint paintPressed = new Paint();
    paintPressed.setAntiAlias(true);
    paintPressed.setColor(pressedColor);
    canvasPressed.drawCircle(radius, radius, radius, paintPressed);

    WeakReference<Bitmap> imageNormal =
        new WeakReference<>(Bitmap.createBitmap(2 * radius, 2 * radius, Bitmap.Config.ARGB_8888));
    Canvas canvasNormal = new Canvas(imageNormal.get());
    Paint paintNormal = new Paint();
    paintNormal.setAntiAlias(true);
    paintNormal.setColor(normalColor);
    canvasNormal.drawCircle(radius, radius, radius, paintNormal);

    StateListDrawable stateListDrawable = new StateListDrawable();
    stateListDrawable.addState(
        new int[] {android.R.attr.state_pressed},
        new BitmapDrawable(circleButton.getContext().getResources(), imagePressed.get()));
    stateListDrawable.addState(
        StateSet.WILD_CARD,
        new BitmapDrawable(circleButton.getContext().getResources(), imageNormal.get()));

    if (android.os.Build.VERSION.SDK_INT >= 16) {
      circleButton.setBackground(stateListDrawable);
    } else {
      circleButton.setBackgroundDrawable(stateListDrawable);
    }
  }
 static synchronized WritableRaster makeRaster(ColorModel cm, Raster srcRas, int w, int h) {
   if (xrgbmodel == cm) {
     if (xrgbRasRef != null) {
       WritableRaster wr = (WritableRaster) xrgbRasRef.get();
       if (wr != null && wr.getWidth() >= w && wr.getHeight() >= h) {
         xrgbRasRef = null;
         return wr;
       }
     }
     // If we are going to cache this Raster, make it non-tiny
     if (w <= 32 && h <= 32) {
       w = h = 32;
     }
   } else if (argbmodel == cm) {
     if (argbRasRef != null) {
       WritableRaster wr = (WritableRaster) argbRasRef.get();
       if (wr != null && wr.getWidth() >= w && wr.getHeight() >= h) {
         argbRasRef = null;
         return wr;
       }
     }
     // If we are going to cache this Raster, make it non-tiny
     if (w <= 32 && h <= 32) {
       w = h = 32;
     }
   }
   if (srcRas != null) {
     return srcRas.createCompatibleWritableRaster(w, h);
   } else {
     return cm.createCompatibleWritableRaster(w, h);
   }
 }
Example #9
0
  public String cachedValueOf(final String str) {
    if (str != null && (lengthLimit < 0 || str.length() <= lengthLimit)) {
      // Return value from cache if available
      try {
        lock.readLock().lock();
        WeakReference<String> ref = cache.get(str);
        if (ref != null) {
          return ref.get();
        }
      } finally {
        lock.readLock().unlock();
      }

      // Update cache with new content
      try {
        lock.writeLock().lock();
        WeakReference<String> ref = cache.get(str);
        if (ref != null) {
          return ref.get();
        }
        cache.put(str, new WeakReference<>(str));
      } finally {
        lock.writeLock().unlock();
      }
      return str;
    }
    return str;
  }
Example #10
0
  @Override
  protected void notifyUpdate(Iterable<PicItem> entities) {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    for (PicItem entity : entities) {
      Long key = getKey(entity);
      if (key != null) {
        notifyExtraOb(key);

        ops.add(
            ContentProviderOperation.newUpdate(ContentUris.withAppendedId(CONTENT_URI, key))
                .withValue(null, null)
                .build());
      }
    }

    try {
      if (contextWeakReference.get() != null)
        contextWeakReference.get().getContentResolver().applyBatch(AUTHORITY, ops);
    } catch (RemoteException e) {
      e.printStackTrace();
    } catch (OperationApplicationException e) {
      e.printStackTrace();
    }
  }
  @Override
  public void deliverError(VolleyError error) {
    super.deliverError(error);
    if (mListenerReference != null && mListenerReference.get() != null) {
      NetworkListener listener = mListenerReference.get();
      BaseError response = new BaseError();

      if (error.networkResponse != null) {
        response.mStatusCode = error.networkResponse.statusCode;
        response.mErrorMessage = new String(error.networkResponse.data);
      } else if (error instanceof NetworkError || error instanceof NoConnectionError) {
        response.mErrorMessage = "Please check the internet connection";
      } else if (error instanceof TimeoutError) {
        response.mErrorMessage = "Server is busy try again later";
      } else if (error instanceof AuthFailureError) {
        response.mErrorMessage = "Auth Failure";
      } else if (error instanceof ServerError) {
        response.mErrorMessage = "ServerError";
      } else if (error instanceof ParseError) {
        response.mErrorMessage = "Error in parsing server data";
      }

      listener.onError(response);
    }
  }
 protected final void aXk() {
   Object localObject;
   if (!mav) {
     if (maw == null) {
       v.w("MicroMsg.InputTextBoundaryCheck", "edit text view is null");
       return;
     }
     if (!be.bz(maA)) {
       break label123;
     }
     localObject = new i(may, lWP);
     ((EditText) maw.get()).setFilters(new InputFilter[] {localObject});
   }
   while (maB != null) {
     switch (aXj()) {
       default:
         return;
       case 0:
         maB.ng(eAL);
         return;
         label123:
         maA.add(new i(may, lWP));
         localObject = (InputFilter[]) maA.toArray(new InputFilter[maA.size()]);
         ((EditText) maw.get()).setFilters((InputFilter[]) localObject);
     }
   }
   maB.Px();
   return;
   maB.Py();
 }
Example #13
0
 public static synchronized Context getInstance() {
   if (instanceRef == null || instanceRef.get() == null) {
     return BaseApplication.getContext();
   } else {
     return instanceRef.get();
   }
 }
Example #14
0
  public synchronized void cleanupCurrentThread() {
    final long id = Thread.currentThread().getId();
    for (final ConcreteResource res : new HashSet<ConcreteResource>(lock.keySet())) {
      final WeakReference<Thread> ref = lock.get(res);
      if (ref != null) {
        boolean rm = false;
        if (ref.get() == null) {
          logger.debug(
              "Cleaning up lock: {} for thread: {}", res, Thread.currentThread().getName());
          rm = true;
        } else if (ref.get().getId() == id) {
          logger.debug(
              "Cleaning up lock: {} for thread: {}", res, Thread.currentThread().getName());
          rm = true;
        }

        if (rm) {
          synchronized (lock) {
            lock.remove(res);
            lock.notifyAll();
          }
        }
      }
    }
  }
Example #15
0
  @Override
  public void drawData(Canvas c) {

    int width = (int) mViewPortHandler.getChartWidth();
    int height = (int) mViewPortHandler.getChartHeight();

    if (mDrawBitmap == null
        || (mDrawBitmap.get().getWidth() != width)
        || (mDrawBitmap.get().getHeight() != height)) {

      if (width > 0 && height > 0) {

        mDrawBitmap =
            new WeakReference<Bitmap>(Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444));
        mBitmapCanvas = new Canvas(mDrawBitmap.get());
      } else return;
    }

    mDrawBitmap.get().eraseColor(Color.TRANSPARENT);

    PieData pieData = mChart.getData();

    for (IPieDataSet set : pieData.getDataSets()) {

      if (set.isVisible() && set.getEntryCount() > 0) drawDataSet(c, set);
    }
  }
 protected void onSignOut(Activity currentActivity) {
   if (currentActivity == null) {
     Log.e(TAGERROR, "Activity can not be null");
   } else {
     changeCurrentState(StatusFacebookConn.DISCONNECTED);
     Log.i(TAGINFO, "Disconnected");
     LoginManager.getInstance().logOut();
     activityWeakReference
         .get()
         .getSharedPreferences("FacebookSession", Context.MODE_PRIVATE)
         .edit()
         .putBoolean("FacebookLogged", false)
         .commit();
     activityWeakReference
         .get()
         .getSharedPreferences("FacebookSession", Context.MODE_PRIVATE)
         .edit()
         .putString("FacebookEmail", null)
         .commit();
     currentActivity.startActivity(new Intent(currentActivity, LoginActivity.class));
     activityWeakReference.get().finish();
     currentActivity.finish();
     clearInstanceReference();
   }
 }
  private void fetchComments() {
    try {
      final URL newUrl = new URL(book.get().getCommentsUrl());

      // sax stuff
      final SAXParserFactory factory = SAXParserFactory.newInstance();
      final SAXParser parser = factory.newSAXParser();

      final XMLReader reader = parser.getXMLReader();

      // initialize our parser logic
      final CommentsHandler commentsHandler = new CommentsHandler(book.get().getComments());
      reader.setContentHandler(commentsHandler);

      // get the xml feed
      reader.parse(new InputSource(newUrl.openStream()));
    } catch (MalformedURLException e) {
      COMMENTS_ERROR = MALFORMED_URL;
      Log.e(TAG, "MalformedURLException: " + e + "\nIn fetchComments()");
    } catch (ParserConfigurationException pce) {
      COMMENTS_ERROR = PARSER_CONFIG_ERROR;
      Log.e(TAG, "ParserConfigurationException: " + pce + "\nIn fetchComments()");
    } catch (SAXException se) {
      COMMENTS_ERROR = SAX_ERROR;
      Log.e(TAG, "SAXException: " + se + "\nIn fetchComments()");
    } catch (IOException ioe) {
      COMMENTS_ERROR = IO_ERROR;
      Log.e(TAG, "IOException: " + ioe + "\nIn fetchComments()");
    }
  }
 @Override
 protected void deliverResponse(T response) {
   if (mListenerReference != null && mListenerReference.get() != null) {
     NetworkListener listener = mListenerReference.get();
     listener.onSuccess(response);
   }
 }
    @Override
    public void handleMessage(Message msg) {
      switch (msg.what) {
        default:
          super.handleMessage(msg);
          RangingData data = (RangingData) msg.obj;
          Log.d(TAG, "Got a ranging callback with data: " + data);
          Log.d(TAG, "Got a ranging callback with " + data.getIBeacons().size() + " iBeacons");
          if (data.getIBeacons() != null) {
            Iterator<IBeaconData> iterator = data.getIBeacons().iterator();
            while (iterator.hasNext()) {
              IBeaconData iBeaconData = iterator.next();
              if (iBeaconData == null) {
                Log.d(TAG, "null ibeacon found");
              } else {
                iBeaconManager.get().rangingTracker.addIBeacon(iBeaconData);
              }
            }

            IBeaconManager manager = iBeaconManager.get();
            if (manager.rangeNotifier != null) {
              Log.d(TAG, "Calling ranging notifier on :" + manager.rangeNotifier);
              manager.rangeNotifier.didRangeBeaconsInRegion(
                  iBeaconManager.get().rangingTracker.getIBeacons(), data.getRegion());
            }
          }
      }
    }
  /**
   * Called after an operation executing in the background is completed. It sets the bitmap image to
   * an image view and dismisses the progress dialog.
   *
   * @param image The bitmap image
   */
  protected void onPostExecute(Bitmap image) {
    // Dismiss the progress dialog.
    mActivity.get().dismissDialog();

    // Display the downloaded image to the user.
    mActivity.get().displayBitmap(image);
  }
  @Ignore // RT-26710: javafx.scene.web.LeakTest hangs
  @Test
  public void testGarbageCollectability() throws InterruptedException {
    final BlockingQueue<WeakReference<WebPage>> webPageRefQueue =
        new LinkedBlockingQueue<WeakReference<WebPage>>();
    submit(
        () -> {
          WebView webView = new WebView();
          WeakReference<WebView> webViewRef = new WeakReference<WebView>(webView);
          WeakReference<WebEngine> webEngineRef = new WeakReference<WebEngine>(webView.getEngine());
          webPageRefQueue.add(new WeakReference<WebPage>(webView.getEngine().getPage()));

          webView = null;
          System.gc();
          assertNull("WebView has not been GCed", webViewRef.get());
          assertNull("WebEngine has not been GCed", webEngineRef.get());
        });

    WeakReference<WebPage> webPageRef = webPageRefQueue.take();
    long endTime = System.currentTimeMillis() + 5000;
    while (true) {
      System.gc();
      if (webPageRef.get() == null) {
        break;
      }
      if (System.currentTimeMillis() > endTime) {
        fail("WebPage has not been GCed");
      }
      Thread.sleep(100);
    }
  }
Example #22
0
 @Override
 public void onItemClicked(ItemAdapter itemAdapter, RssItem rssItem) {
   int positionToExpand = -1;
   int positionToContract = -1;
   if (itemAdapter.getExpandedItem() != null) {
     positionToContract = currentItems.indexOf(itemAdapter.getExpandedItem());
     View viewToContract = recyclerView.getLayoutManager().findViewByPosition(positionToContract);
     if (viewToContract == null) {
       positionToContract = -1;
     }
   }
   if (itemAdapter.getExpandedItem() != rssItem) {
     positionToExpand = currentItems.indexOf(rssItem);
     itemAdapter.setExpandedItem(rssItem);
   } else {
     itemAdapter.setExpandedItem(null);
   }
   if (positionToContract > -1) {
     itemAdapter.notifyItemChanged(positionToContract);
   }
   if (positionToExpand > -1) {
     itemAdapter.notifyItemChanged(positionToExpand);
     delegate.get().onItemExpanded(this, itemAdapter.getExpandedItem());
   } else {
     delegate.get().onItemContracted(this, rssItem);
     return;
   }
   View viewToExpand = recyclerView.getLayoutManager().findViewByPosition(positionToExpand);
   int lessToScroll = 0;
   if (positionToContract > -1 && positionToContract < positionToExpand) {
     lessToScroll = itemAdapter.getExpandedItemHeight() - itemAdapter.getCollapsedItemHeight();
   }
   recyclerView.smoothScrollBy(0, viewToExpand.getTop() - lessToScroll);
 }
 @Override
 protected void onPostExecute(Bitmap bitmap) {
   if (isCancelled()) {
     bitmap = null;
   }
   if (imageViewReference != null && bitmap != null) {
     final ImageView imageView = imageViewReference.get();
     final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
     if (this == bitmapWorkerTask && imageView != null) {
       imageView.setImageBitmap(bitmap);
     }
   } else {
     Savelog.e(TAG, "Unable to load " + key);
     if (hostFragmentReference != null) {
       ViewerFragment hostFragment = hostFragmentReference.get();
       Activity activity = hostFragment.getActivity();
       if (activity != null) {
         if (bitmap == null) {
           Savelog.e(TAG, "bitmap is null. Possibly due to OOM error");
           Toast.makeText(
                   hostFragment.getActivity(),
                   "Try to refresh this page by scrolling slowly.",
                   Toast.LENGTH_SHORT)
               .show();
         } else {
           Savelog.d(TAG, debug, "bitmap is not null for key " + key);
         }
       }
     }
   }
 }
Example #24
0
 public static synchronized Activity getActivity() {
   Activity result = null;
   if (instanceRef != null && instanceRef.get() != null) {
     result = instanceRef.get();
   }
   return result;
 }
  @Override
  public void handleMessage(Message msg) {
    super.handleMessage(msg);

    switch (msg.what) {
      case 0:
        Activity activity = mActivity.get();
        BaseLoopView loopView = mLoopView.get();
        if (activity != null && loopView != null) {
          if (!loopView.isAutoScroll()) return;
          int change = (loopView.getDirection() == BaseLoopView.LEFT) ? -1 : 1;
          loopView
              .getViewPager()
              .setCurrentItem(loopView.getViewPager().getCurrentItem() + change, true);
          loopView.sendScrollMessage(loopView.getInterval());
        } else {
          removeMessages(0);
          if (loopView != null) {
            loopView.releaseResources();
          }
        }
      default:
        break;
    }
  }
Example #26
0
  /**
   * Returns the color space specified by the given color space constant.
   *
   * <p>For standard Java color spaces, the built-in instance is returned. Otherwise, color spaces
   * are looked up from cache and created on demand.
   *
   * @param colorSpace the color space constant.
   * @return the {@link ColorSpace} specified by the color space constant.
   * @throws IllegalArgumentException if {@code colorSpace} is not one of the defined color spaces
   *     ({@code CS_*}).
   * @see ColorSpace
   * @see ColorSpaces#CS_ADOBE_RGB_1998
   * @see ColorSpaces#CS_GENERIC_CMYK
   */
  public static ColorSpace getColorSpace(int colorSpace) {
    ICC_Profile profile;

    switch (colorSpace) {
      case CS_ADOBE_RGB_1998:
        synchronized (ColorSpaces.class) {
          profile = adobeRGB1998.get();

          if (profile == null) {
            // Try to get system default or user-defined profile
            profile = readProfileFromPath(Profiles.getPath("ADOBE_RGB_1998"));

            if (profile == null) {
              // Fall back to the bundled ClayRGB1998 public domain Adobe RGB 1998 compatible
              // profile,
              // which is identical for all practical purposes
              profile = readProfileFromClasspathResource("/profiles/ClayRGB1998.icc");

              if (profile == null) {
                // Should never happen given we now bundle fallback profile...
                throw new IllegalStateException("Could not read AdobeRGB1998 profile");
              }
            }

            adobeRGB1998 = new WeakReference<ICC_Profile>(profile);
          }
        }

        return createColorSpace(profile);

      case CS_GENERIC_CMYK:
        synchronized (ColorSpaces.class) {
          profile = genericCMYK.get();

          if (profile == null) {
            // Try to get system default or user-defined profile
            profile = readProfileFromPath(Profiles.getPath("GENERIC_CMYK"));

            if (profile == null) {
              if (DEBUG) {
                System.out.println("Using fallback profile");
              }

              // Fall back to generic CMYK ColorSpace, which is *insanely slow* using
              // ColorConvertOp... :-P
              return CMYKColorSpace.getInstance();
            }

            genericCMYK = new WeakReference<ICC_Profile>(profile);
          }
        }

        return createColorSpace(profile);

      default:
        // Default cases for convenience
        return ColorSpace.getInstance(colorSpace);
    }
  }
Example #27
0
 /**
  * Get a reference to a particular future.
  *
  * @param id Get a reference to the future with this ID.
  * @return This method returns the reference to the future with this ID.
  */
 public static Future fromID(long id) {
   synchronized (TABLE) {
     if (!TABLE.containsKey(id)) throw new RuntimeException("future not mapped");
     WeakReference<Future> w = TABLE.get(id);
     if (w.get() == null) throw new RuntimeException("future has been collected");
     return w.get();
   }
 }
  /**
   * This method is called each time a Being acquires a Palantir. Since each Being is a Java Thread,
   * it will be called concurrently from different threads. This method increments the number of
   * threads gazing and checks that the number of threads gazing does not exceed the number of
   * Palantiri in the simulation using an AtomicLong object instantiated above (mGazingThreads). If
   * the number of gazing threads exceeds the number of Palantiri, this thread will call shutdown
   * and return false.
   *
   * @return false if the number of gazing threads is greater than the number of Palantiri,
   *     otherwise true.
   */
  private boolean incrementGazingCountAndCheck() {
    final long numberOfGazingThreads = mPresenter.get().mGazingTasks.incrementAndGet();

    if (numberOfGazingThreads > Options.instance().numberOfPalantiri()) {
      mPresenter.get().shutdown();
      return false;
    } else return true;
  }
 @Override
 public void handleMessage(Message msg) {
   super.handleMessage(msg);
   if (mWeakRef.get() != null) {
     mWeakRef.get().invalidate();
     sendEmptyMessageDelayed(0, refreshPeriod);
   }
 }
 public final WeakReference<EntityPlayer> getTXPlayer(WorldServer world) {
   if (player.get() == null) {
     player = createNewPlayer(world);
   } else {
     player.get().worldObj = world;
   }
   return player;
 }