public RankingModelImpl(Workspace workspace) { this.workspace = workspace; this.listeners = Collections.synchronizedList(new ArrayList<RankingListener>()); this.autoRankings = Collections.synchronizedList(new ArrayList<AutoRanking>()); this.interpolator = Interpolator.LINEAR; this.autoTransformer = new RankingAutoTransformer(this); }
private void hantei() { double treeLen = totalTreeLength(); // if the current tree length is less than the previous minimum tree, // then copy the current tree to the min tree if (treeLen < minTreeLen) { // the current tree is now the minimum tree numBetterTreesFound++; minTreeLen = treeLen; synchronized (this) { // copy all the x,y coords and whether they're steiner min nodes this.minPoints = Collections.synchronizedList(new ArrayList<Point>()); for (Point p : this.points) { this.minPoints.add(p.copy()); } // update the number of nodes in SMT numNodesInSMT = this.points.size(); // copy over all the edges this.minEdges = Collections.synchronizedList(new ArrayList<Edge>()); for (int i = 0; i < this.points.size() - 1; i++) { this.minEdges.add(this.edges.get(i).copy()); } } // repaint this em effin' tree repaintIfNecessary(true); } } // hantei
/** Default constructor. */ protected SIPTransactionStack() { super(); this.transactionTableSize = -1; // a set of methods that result in dialog creation. this.dialogCreatingMethods = new HashSet<String>(); // Standard set of methods that create dialogs. this.dialogCreatingMethods.add(Request.REFER); this.dialogCreatingMethods.add(Request.INVITE); this.dialogCreatingMethods.add(Request.SUBSCRIBE); // Notify may or may not create a dialog. This is handled in // the code. // Create the transaction collections clientTransactions = Collections.synchronizedList(new ArrayList<SIPClientTransaction>()); serverTransactions = Collections.synchronizedList(new ArrayList<SIPServerTransaction>()); // Dialog dable. this.dialogTable = new Hashtable<String, SIPDialog>(); clientTransactionTable = new Hashtable<String, SIPTransaction>(); serverTransactionTable = new Hashtable<String, SIPTransaction>(); // Start the timer event thread. this.timer = new Timer(); this.pendingRecordScanner = new Thread(new PendingRecordScanner(this)); this.pendingRecordScanner.setDaemon(true); this.pendingTransactions = new HashSet<SIPServerTransaction>(); pendingRecords = Collections.synchronizedList(new ArrayList<PendingRecord>()); pendingRecordScanner.setName("PendingRecordScanner"); pendingRecordScanner.start(); // endif // }
public DataNode(Communicator communicator) { super(communicator); mapTasks = Collections.synchronizedList(new ArrayList<MapTask>()); reduceTasks = Collections.synchronizedList(new ArrayList<ReduceTask>()); jobExecutors = new HashMap<Integer, List<ExecutorService>>(); mapLock = new ReentrantLock(); reduceLock = new ReentrantLock(); }
/** * Creates a new instance of Sender, a packet sending queue. * * @param group ThreadGroup of this Session * @param socket Connection to the outside world */ public Sender(ThreadGroup group, DatagramSocket socket) { super(group, group.getName() + "-Sender"); m_socket = socket; m_packetsSent = 0; m_packets = Collections.synchronizedList(new LinkedList<DatagramPacket>()); m_highPriorityPackets = Collections.synchronizedList(new LinkedList<DatagramPacket>()); start(); }
private void init(final String groupName, final boolean collapsed) { this.groupName = groupName; this.collapsed = collapsed; this.collapseable = true; this.rowMembers = Collections.synchronizedList(new ArrayList<T>()); this.staticRowMembers = Collections.synchronizedList(new ArrayList<T>()); this.childGroups = Collections.synchronizedList(new ArrayList<IRowGroup<T>>()); this.data = new HashMap<String, Object>(); }
/** Initialize variables to default values. */ public AbstractConnection() { internalQueue = Collections.synchronizedList(new LinkedList<KtnDatagram>()); externalQueue = Collections.synchronizedList(new LinkedList<KtnDatagram>()); isReceiving = false; nextSequenceNo = (int) (Math.random() * 10000 + 1); disconnectRequest = null; lastDataPacketSent = null; lastValidPacketReceived = null; state = State.CLOSED; }
/** * @param flags * @param id * @param multicast */ protected DNSMessage(int flags, int id, boolean multicast) { super(); _flags = flags; _id = id; _multicast = multicast; _questions = Collections.synchronizedList(new LinkedList<DNSQuestion>()); _answers = Collections.synchronizedList(new LinkedList<DNSRecord>()); _authoritativeAnswers = Collections.synchronizedList(new LinkedList<DNSRecord>()); _additionals = Collections.synchronizedList(new LinkedList<DNSRecord>()); }
public GameData() { this.mode = GameData.MODE_LOAD; this.figures = Collections.synchronizedList(new ArrayList<GameFigure>()); this.lines = Collections.synchronizedList(new ArrayList<Line>()); // this.figures.add(new Tank(50, 50, Color.blue)); this.tank = new Tank(50, 50, Color.blue, this); // this.field = new FieldSection[23][23]; this.field = new Field(); this.fieldLoaded = false; }
public PostProcessingManager(RajawaliRenderer renderer, int width, int height) { mRenderer = renderer; if (width == -1 && height == -1) { width = mRenderer.getViewportWidth(); height = mRenderer.getViewportHeight(); } mWidth = width; mHeight = height; mScreenQuad = new ScreenQuad(); mScene = new RajawaliScene(mRenderer, GRAPH_TYPE.NONE); mRenderTarget1 = new RenderTarget( "rt1" + hashCode(), width, height, 0, 0, false, false, GLES20.GL_TEXTURE_2D, Config.ARGB_8888, FilterType.LINEAR, WrapType.CLAMP); mRenderTarget2 = new RenderTarget( "rt2" + hashCode(), width, height, 0, 0, false, false, GLES20.GL_TEXTURE_2D, Config.ARGB_8888, FilterType.LINEAR, WrapType.CLAMP); mWriteBuffer = mRenderTarget1; mReadBuffer = mRenderTarget2; mCopyPass = new EffectPass(new CopyPass()); mComponents = Collections.synchronizedList(new CopyOnWriteArrayList<IPostProcessingComponent>()); mPasses = Collections.synchronizedList(new CopyOnWriteArrayList<IPass>()); mRenderer.addRenderTarget(mWriteBuffer); mRenderer.addRenderTarget(mReadBuffer); mScene.addChild(mScreenQuad); mRenderer.addScene(mScene); }
/* * (non-Javadoc) * @see rajawali.scenegraph.AD_AABBTree#init() */ @Override protected void init() { // Pre-allocate storage here to favor modification speed CHILD_COUNT = 8; mChildren = new Octree[CHILD_COUNT]; mMembers = Collections.synchronizedList(new CopyOnWriteArrayList<IGraphNodeMember>()); if (mParent == null) // mOutside should not be used for children, thus we want to force the Null // pointer. mOutside = Collections.synchronizedList(new CopyOnWriteArrayList<IGraphNodeMember>()); mChildLengths = new Vector3(); }
public SendToModel(List<File> fileList) { super(); if (fileList == null) throw new NullPointerException("files cannot be null"); else { this.fileList = Collections.synchronizedList(fileList); rendererList = Collections.synchronizedList(new ArrayList<Renderer>()); milliSecondWait = 10000; commandList = new ArrayList<Command>(); } }
/** * Generates a compatibility graph between two molecules * * @param source * @param target * @param shouldMatchBonds * @param shouldMatchRings * @param matchAtomType * @throws java.io.IOException */ public GenerateCompatibilityGraph( IAtomContainer source, IAtomContainer target, boolean shouldMatchBonds, boolean shouldMatchRings, boolean matchAtomType) throws IOException { this.shouldMatchRings = shouldMatchRings; this.shouldMatchBonds = shouldMatchBonds; this.matchAtomType = matchAtomType; this.source = source; this.target = target; compGraphNodes = new ArrayList<>(); compGraphNodesCZero = new ArrayList<>(); cEdges = Collections.synchronizedList(new ArrayList<Integer>()); dEdges = Collections.synchronizedList(new ArrayList<Integer>()); /* Generate all possible graphs when no ring match or atom type is required */ /* Modification for AAM only */ if ((!shouldMatchBonds || !matchAtomType) && source.getAtomCount() > 30 && target.getAtomCount() > 30) { compatibilityGraphNodesIfCEdgeIsZero(); compatibilityGraphCEdgeZero(); clearCompGraphNodesCZero(); } else { // System.out.println("compatibilityGraphNodes "); compatibilityGraphNodes(); // System.out.println("compatibilityGraph "); compatibilityGraph(); // System.out.println("c-edges " + getCEgdes().size()); // System.out.println("d-edges " + getDEgdes().size()); if (getCEdgesSize() == 0) { clearCompGraphNodes(); clearCEgdes(); clearDEgdes(); resetCEdgesSize(); resetDEdgesSize(); compatibilityGraphNodesIfCEdgeIsZero(); compatibilityGraphCEdgeZero(); clearCompGraphNodesCZero(); } } }
public class MainApp implements Runnable, ShutdownHooks { volatile boolean keepRunning = true; volatile Thread sleepingThread = null; List<Runnable> jobs = Collections.synchronizedList(new ArrayList<>()); List<Runnable> cleanUpJobs = Collections.synchronizedList(new ArrayList<>()); public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public synchronized void run() { work(); while (keepRunning) { System.out.println("I am Running."); sleepingThread = Thread.currentThread(); sleep(3_000); } } public boolean isRunning() { return keepRunning; } public void work() { for (Runnable job : jobs) { job.run(); } } public void cleanup() { for (Runnable job : cleanUpJobs) { job.run(); } } @Override public void closeInside() { if (sleepingThread != null) if (sleepingThread != Thread.currentThread()) { this.sleepingThread.interrupt(); } this.keepRunning = false; } }
public SubscriptionRecordQueue(String id, int queueRecordCapacity, int queueTimeCapacity) { this.consumers = new ConcurrentHashMap<String, Integer>(10, 0.75f, 4); this.producers = new ConcurrentHashMap<String, Integer>(10, 0.75f, 4); if (queueRecordCapacity <= 0) { this.subscriptionRecordQueue = Collections.synchronizedList(new LinkedList<Record>()); } else { this.subscriptionRecordQueue = Collections.synchronizedList(new ArrayList<Record>(queueRecordCapacity)); } this.queueRecordCapacity = queueRecordCapacity; this.queueTimeCapacity = queueTimeCapacity; this.id = id; }
/** * Constructs a new <code>Session</code>. * * @param changed <code>true</code> if the session has changed, <code>false</code> otherwise. */ public Session(File descriptorFile, boolean changed) { this.descriptorFile = descriptorFile; this.changed = changed; sessionListeners = Collections.synchronizedList(new ArrayList<SessionListener>()); sessionElementListeners = Collections.synchronizedList(new ArrayList<SessionElementListener>()); objectSelectionChangeListeners = Collections.synchronizedList(new ArrayList<ObjectSelectionChangeListener>()); descriptors = Collections.synchronizedList(new ArrayList<SessionElementDescriptor>()); selectedObjects = new SessionElementDescriptor[0]; pcs = new PropertyChangeSupport(this); clientProperties = Collections.synchronizedMap(new HashMap<String, String>()); persistentClientProperties = Collections.synchronizedMap(new HashMap<String, String>()); }
public FileDownloader( Context context, FileDownloaderListener listener, File rootDirectory, List<DownloadableObject> downloadableObjects) { super(); this.context = context; this.listener = listener; this.rootDirectory = rootDirectory; // lets make sure the List is synchronized this.downloadableObjects = Collections.synchronizedList(downloadableObjects); arDownloadSize = Collections.synchronizedList(new ArrayList<String>(300)); }
public Model(GameActivity gameActivity, Surface view) { m_view = view; m_gameActivity = gameActivity; m_view.addModel(this); m_barriers = Collections.synchronizedList(new ArrayList<Barrier>()); m_balls = Collections.synchronizedList(new ArrayList<Ball>()); m_bonusBalls = Collections.synchronizedList(new ArrayList<BonusBall>()); m_newScorePoints = Collections.synchronizedList(new ArrayList<ScorePoint>()); m_run = true; m_speed = m_defaultSpeed = 1; m_spaceBetweenRectangles = 0; m_score = 0; m_sleep = m_defaultSleep = 10; m_points = 2; m_nameToMediaPlayer = Collections.synchronizedMap(new HashMap<String, MediaPlayer>()); mStartScore = 0; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(m_gameActivity.getApplicationContext()); m_playSounds = !prefs.getBoolean("MuteSound", true); if (m_playSounds) { m_nameToMediaPlayer.put( "bomb", MediaPlayer.create(m_gameActivity.getBaseContext(), R.raw.bomb_bonus)); m_nameToMediaPlayer.put( "color", MediaPlayer.create(m_gameActivity.getBaseContext(), R.raw.color_bonus)); m_nameToMediaPlayer.put( "gameover", MediaPlayer.create(m_gameActivity.getBaseContext(), R.raw.gameover)); m_nameToMediaPlayer.put( "points", MediaPlayer.create(m_gameActivity.getBaseContext(), R.raw.new_point)); m_nameToMediaPlayer.put( "time", MediaPlayer.create(m_gameActivity.getBaseContext(), R.raw.time_bonus)); m_nameToMediaPlayer.put( "win", MediaPlayer.create(m_gameActivity.getBaseContext(), R.raw.win)); } prefs = PreferenceManager.getDefaultSharedPreferences(gameActivity.getApplicationContext()); m_dificulty = prefs.getString("Dificulty", "Easy"); if (m_dificulty.equalsIgnoreCase("Normal")) { m_points = 2; mStartScore = 701; } else if (m_dificulty.equalsIgnoreCase("Hard")) { m_points = 3; mStartScore = 1401; } m_defBallSpeed = m_ballSpeed = prefs.getInt("BallSpeed", 3); }
public List<HoldingResult> Direction6() { List<HoldingResult> templist = Collections.synchronizedList(new ArrayList<HoldingResult>()); // limitation for the shifts int ShiftX = this.n1 - this.X2max; int ShiftY = 0; int[][] matrixTemp = new int[this.n1][this.m]; int[][] matrixPadded = new int[this.n1][this.m]; if (this.n2 < this.n1) matrixPadded = this.SetingMaticesToSameDimension(); else matrixPadded = this.discreteLane2; ZeroPadding zp = new ZeroPadding(); Overlaping over = new Overlaping(); boolean shift = true; // it is true by default -> if it is false then there is no overlapping of patterns // all possible not overlapping solutions (x,y shifts) List<Point> listOfEmbeding = Collections.synchronizedList(new ArrayList<Point>()); for (int i = 0; i < ShiftX; i++) { // zero padding for appropriate shift matrixTemp = zp.Shifting(matrixPadded, i, 0, this.n1, this.m, 6); // checking if at this shift we have overlapping of patterns from both lanes shift = over.CheckOverlapingOfTwoDiscretizedLanes( this.discreteLane1, matrixTemp, this.X1min, this.X1max, this.X2min + i, this.X2max + i, this.Y1min, this.Y1max, this.Y2min, this.Y2max); if (shift == false) { HoldingResult temp = new HoldingResult(); temp.setRepassing(true); temp.setDirection(6); temp.setShiftX(i); temp.setShiftY(0); templist.add(temp); } shift = true; } return templist; }
static PsiElement[] getOccurrences(GrIntroduceParameterSettings settings) { final GrParametersOwner scope = settings.getToReplaceIn(); final GrExpression expression = settings.getExpression(); if (expression != null) { final PsiElement expr = PsiUtil.skipParentheses(expression, false); if (expr == null) return PsiElement.EMPTY_ARRAY; final PsiElement[] occurrences = GroovyRefactoringUtil.getExpressionOccurrences(expr, scope); if (occurrences == null || occurrences.length == 0) { throw new GrRefactoringError(GroovyRefactoringBundle.message("no.occurrences.found")); } return occurrences; } else { final GrVariable var = settings.getVar(); LOG.assertTrue(var != null); final List<PsiElement> list = Collections.synchronizedList(new ArrayList<PsiElement>()); ReferencesSearch.search(var, new LocalSearchScope(scope)) .forEach( new Processor<PsiReference>() { @Override public boolean process(PsiReference psiReference) { final PsiElement element = psiReference.getElement(); if (element != null) { list.add(element); } return true; } }); return list.toArray(new PsiElement[list.size()]); } }
public SingleConnectionFactory() { super(); setRequestedHeartbeat(CONNECTION_HEARTBEAT_IN_SEC); setConnectionTimeout(CONNECTION_TIMEOUT_IN_MS); connectionListeners = Collections.synchronizedList(new LinkedList<ConnectionListener>()); connectionShutdownListener = new ConnectionShutDownListener(); }
public class TTSService extends Service implements TextToSpeech.OnInitListener { private TextToSpeech textToSpeech; private List<String> textQ = Collections.synchronizedList( new ArrayList<String>()); // Just in two Service (two sms ) arrives too fast @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); } @Override public void onDestroy() { if (textToSpeech != null) { textToSpeech.stop(); textToSpeech.shutdown(); } super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e(SpeedCopConstants.TAG, "INSIDE ONSTART OF TEH SERVUCE"); String textToRead = intent != null ? intent.getStringExtra(SpeedCopConstants.INTENT_EXTRA_TEXT_TO_READ_OUT) : null; if (textToRead == null) textToRead = "Empty Message"; textQ.add(textToRead); textToSpeech = new TextToSpeech(this, this); Log.e(SpeedCopConstants.TAG, "END FROM SERVICE"); return super.onStartCommand(intent, flags, startId); } @Override public void onInit(int status) { Log.e(SpeedCopConstants.TAG, "INSIDE THE ONINIT"); if (status != TextToSpeech.SUCCESS) { Log.e(SpeedCopConstants.TAG, "Could not initialize TextToSpeech."); } else { synchronized (textQ) { for (int i = 0; i < textQ.size(); i++) readText(textQ.get(i)); Log.e(SpeedCopConstants.TAG, "TEXT Q SIZE-->" + textQ.size()); textQ.clear(); } } Log.e(SpeedCopConstants.TAG, "DONE THE ONINIT"); } private void readText(String text) { Log.e(SpeedCopConstants.TAG, "called and now inside the readTEXT...==>" + text); textToSpeech.speak(text, TextToSpeech.QUEUE_ADD, null); Log.e(SpeedCopConstants.TAG, "DONE the readTEXT..."); } }
public static void main(String args[]) { Semaphore s = new Semaphore(5); NumberServer n = new NumberServer(); ExecutorService executorService = Executors.newFixedThreadPool(10); List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>()); for (int i = 0; i < 10; i++) { try { s.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } executorService.execute( new Runnable() { public void run() { list.add(n.getNumber()); s.release(); } }); } executorService.shutdown(); try { s.acquire(5); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int i = 0; i < 10; i++) { System.out.println(list.get(i)); } }
private static class BlockingReceiver extends ReceiverAdapter { final CountDownLatch latch; final List<Integer> msgs = Collections.synchronizedList(new LinkedList<Integer>()); public BlockingReceiver(CountDownLatch latch) { this.latch = latch; } public List<Integer> getMsgs() { return msgs; } public void receive(Message msg) { if (!msg.isFlagSet(Message.OOB)) { try { System.out.println(Thread.currentThread() + ": waiting on latch"); latch.await(25000, TimeUnit.MILLISECONDS); System.out.println(Thread.currentThread() + ": DONE waiting on latch"); } catch (InterruptedException e) { e.printStackTrace(); } } msgs.add((Integer) msg.getObject()); } }
public static void reload() { LogLocation = tekkitrestrict.config.getString("LogLocation"); LogNameFormat = tekkitrestrict.config.getString("LogNameFormat"); LogStringFormat = tekkitrestrict.config.getString("LogStringFormat"); LogIsEnabled = tekkitrestrict.config.getBoolean("LogIsEnabled"); LogChat = tekkitrestrict.config.getBoolean("LogChat"); LogChunkRemoval = tekkitrestrict.config.getBoolean("LogChunkUnload"); LogLowPerformance = tekkitrestrict.config.getBoolean("LogLowPerformance"); LogDupes = tekkitrestrict.config.getBoolean("LogDupes"); LogAmulets = tekkitrestrict.config.getBoolean("LogAmulets"); LogRings = tekkitrestrict.config.getBoolean("LogRings"); LogGemPowers = tekkitrestrict.config.getBoolean("LogGemPowers"); LogDMTools = tekkitrestrict.config.getBoolean("LogDMTools"); LogRMTools = tekkitrestrict.config.getBoolean("LogRMTools"); LogOpenAlc = tekkitrestrict.config.getBoolean("LogOpenAlc"); LogEEMisc = tekkitrestrict.config.getBoolean("LogEEMisc"); LogEEDestructive = tekkitrestrict.config.getBoolean("LogEEDestructive"); LogDebug = tekkitrestrict.config.getBoolean("LogDebug"); BroadcastDupes = tekkitrestrict.config.getStringList("BroadcastDupes"); for (int i = 0; i < BroadcastDupes.size(); i++) { BroadcastDupes.set(i, BroadcastDupes.get(i).toLowerCase()); } BroadcastDupeString = tekkitrestrict.config.getString("BroadcastDupeString"); hacks = Collections.synchronizedList(tekkitrestrict.config.getStringList("BroadcastHacks")); BroadcastHackString = tekkitrestrict.config.getString("BroadcastHackString"); LogFlyHack = tekkitrestrict.config.getBoolean("LogFlyHack"); LogForcefieldHack = tekkitrestrict.config.getBoolean("LogForcefieldHack"); LogSpeedHack = tekkitrestrict.config.getBoolean("LogSpeedHack"); }
public static ActFmSyncThread initializeSyncComponents( TaskDao taskDao, TagDataDao tagDataDao, UserActivityDao userActivityDao, TaskAttachmentDao taskAttachmentDao, TaskListMetadataDao taskListMetadataDao) { if (instance == null) { synchronized (ActFmSyncThread.class) { if (instance == null) { List<ClientToServerMessage<?>> syncQueue = Collections.synchronizedList(new LinkedList<ClientToServerMessage<?>>()); ActFmSyncMonitor monitor = ActFmSyncMonitor.getInstance(); ActFmSyncWaitingPool waitingPool = ActFmSyncWaitingPool.getInstance(); instance = new ActFmSyncThread(syncQueue, monitor); taskDao.addListener(new SyncDatabaseListener<Task>(instance, ModelType.TYPE_TASK)); tagDataDao.addListener(new SyncDatabaseListener<TagData>(instance, ModelType.TYPE_TAG)); userActivityDao.addListener( new SyncDatabaseListener<UserActivity>(instance, ModelType.TYPE_ACTIVITY)); taskAttachmentDao.addListener( new SyncDatabaseListener<TaskAttachment>(instance, ModelType.TYPE_ATTACHMENT)); taskListMetadataDao.addListener( new TaskListMetadataSyncDatabaseListener( instance, waitingPool, ModelType.TYPE_TASK_LIST_METADATA)); instance.startSyncThread(); } } } return instance; }
public PopupAgent( ControlPanel cp, FactoryFrame ff, Integer index, Transducer t, TChannel channelType) // ArrayList<Robot> inputRobots { super("popupAgent"); this.cp = cp; factoryFrame = ff; myIndex = index; glasses = Collections.synchronizedList(new ArrayList<MyGlass>()); nextFamilyAvailable = true; transducer = t; myChannel = channelType; if (myChannel == TChannel.DRILL) expectationTime = 29; else if (myChannel == TChannel.CROSS_SEAMER) expectationTime = 13; else if (myChannel == TChannel.GRINDER) expectationTime = 32; // for(Robot r: inputRobots) // { // robots.add(new MyRobot(r)); // } robots.add(new MyRobot()); robots.add(new MyRobot()); t.register(this, TChannel.CONVEYOR); t.register(this, TChannel.SENSOR); t.register(this, TChannel.POPUP); // need to listen to another work station t.register(this, myChannel); }
/** * Construct a provider holder with a given set of providers. This will maintain the current order * as long as it does not violate the rules for {@link OrderedService}s. * * @param currentProviders the current set of providers to register in this stack */ public ProviderStack(T[] currentProviders) { providers = Collections.synchronizedList(new ArrayList<ProviderHolder<T>>()); ArrayList<T> tList = new ArrayList<T>(); // first add in the ordered ones for (int i = 0; i < currentProviders.length; i++) { T t = currentProviders[i]; if (t instanceof NotProvider) { continue; // skip all the NotProviders } if (t instanceof OrderedService) { tList.add(t); } } // sort the ordered ones Collections.sort(tList, new OrderedServiceComparator()); // now add in the rest in the order given for (int i = 0; i < currentProviders.length; i++) { T t = currentProviders[i]; if (!(t instanceof OrderedService)) { if (t instanceof NotProvider) { continue; // skip all the NotProviders } tList.add(t); } } // now put these into holders for (T t : tList) { providers.add(new ProviderHolder<T>(t)); } tList.clear(); }
class DisplayListener extends SimpleImageLoadingListener { final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>()); @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { if (loadedImage != null) { ImageView imageView = (ImageView) view; int h = dp2px.dip2px(98); int w = h * loadedImage.getWidth() / loadedImage.getHeight(); FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(w, h); // imageView.setLayoutParams(lp); imageView.setScaleType(ScaleType.CENTER_CROP); boolean firstDisplay = !displayedImages.contains(imageUri); if (firstDisplay) { FadeInBitmapDisplayer.animate(imageView, 500); displayedImages.add(imageUri); } } else { ImageView imageView = (ImageView) view; int h = imageView.getHeight(); FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(h, h); lp.setMargins(dp2px.dip2px(10), dp2px.dip2px(10), 0, dp2px.dip2px(10)); imageView.setLayoutParams(lp); imageView.setImageResource(R.drawable.img_default); } } }
/** 初始化DownloadManager */ public synchronized void init(DownloaderManagerConfiguration configuration) { FileDownloader.init(configuration.getContext(), configuration.getOkHttpClientCustomMaker()); FileDownloader.getImpl().bindService(); ILogger.DEBUG = configuration.isDebug(); FileDownloadLog.NEED_LOG = ILogger.DEBUG; this.mConfiguration = configuration; this.mExtFieldMap = configuration.getDbExtField(); mDbController = new FileDownloaderDBController( configuration.getContext(), configuration.getDbVersion(), mExtFieldMap, configuration.getDbUpgradeListener()); mAllTasks = mDbController.getAllTasks(); mConnectListenerList = new ArrayList<>(); mListenerManager = new ListenerManager(); mAutoRetryTimes = configuration.getAutoRetryTimes(); mHeaders = configuration.getHeaders(); // 设置下载保存目录 if (!StringUtils.isEmpty(configuration.getDownloadStorePath())) { FileDownloadUtils.setDefaultSaveRootPath(configuration.getDownloadStorePath()); } mWaitQueue = new LinkedList<>(); mDownloadingList = Collections.synchronizedList(new ArrayList<FileDownloaderModel>()); mDownloadManager = this; ShellUtils.execCommand("chmod 777 " + configuration.getDownloadStorePath(), false); }