List of usage examples for java.util LinkedList remove
public E remove(int index)
From source file:de.uni_potsdam.hpi.bpt.bp2014.jcore.rest.RestInterface.java
/** * Returns a JSON-Object, which contains information about all * data objects of a specified scenario instance. * The data contains the id, label and state. * * @param scenarioID The ID of the scenario model. * @param instanceID The ID of the scenario instance. * @param filterString A String which specifies a filter. Only Data * Objects with a label containing this string * will be returned. * @return A Response with the outcome of the GET-Request. The Response * will be a 200 (OK) if the specified instance was found. Hence * the JSON-Object will be returned.//from w w w . ja v a 2 s. c o m * It will be a 301 (REDIRECT) if the scenarioID is wrong. * And a 404 if the instance id is wrong. */ @GET @Path("scenario/{scenarioID}/instance/{instanceID}/dataobject") @Produces(MediaType.APPLICATION_JSON) public Response getDataObjects(@Context UriInfo uriInfo, @PathParam("scenarioID") int scenarioID, @PathParam("instanceID") int instanceID, @QueryParam("filter") String filterString) { ExecutionService executionService = new ExecutionService(); //TODO: add link to detail REST call for more information about each dataobject if (!executionService.existScenarioInstance(instanceID)) { return Response.status(Response.Status.NOT_FOUND).type(MediaType.APPLICATION_JSON) .entity("{\"error\":\"There is no instance with the id " + instanceID + "\"}").build(); } else if (!executionService.existScenario(scenarioID)) { try { return Response.seeOther(new URI( "interface/v2/scenario/" + executionService.getScenarioIDForScenarioInstance(instanceID) + "/instance/" + instanceID + "/dataobject")) .build(); } catch (URISyntaxException e) { return Response.serverError().build(); } } executionService.openExistingScenarioInstance(scenarioID, instanceID); LinkedList<Integer> dataObjects = executionService.getAllDataObjectIDs(instanceID); HashMap<Integer, String> states = executionService.getAllDataObjectStates(instanceID); HashMap<Integer, String> labels = executionService.getAllDataObjectNames(instanceID); if (filterString != null && !filterString.isEmpty()) { for (Map.Entry<Integer, String> labelEntry : labels.entrySet()) { if (!labelEntry.getValue().contains(filterString)) { dataObjects.remove(labelEntry.getKey()); states.remove(labelEntry.getKey()); labels.remove(labelEntry.getKey()); } } } JSONObject result = buildListForDataObjects(uriInfo, dataObjects, states, labels); return Response.ok(result.toString(), MediaType.APPLICATION_JSON).build(); }
From source file:com.google.ie.business.service.impl.IdeaServiceImpl.java
/** * Remove idea from the list/* ww w. j a v a2 s .c o m*/ * * @param ideas the list of the ideas * @param ideaKey the key of the idea to be removed * @param keyOfTheList the key of the ideas list as used in the cache * @param expiryDelay the expiry delay for the list in cache */ private void removeIdeaFromList(LinkedList<Idea> ideas, String ideaKey, String keyOfTheList, int expiryDelay) { Iterator<Idea> iterator = ideas.iterator(); Idea idea = null; Idea ideaToBeRemoved = null; while (iterator.hasNext()) { idea = iterator.next(); if (ideaKey.equalsIgnoreCase(idea.getKey())) { ideaToBeRemoved = idea; break; } } if (ideaToBeRemoved != null) { ideas.remove(ideaToBeRemoved); /* Put the updated list back to the cache */ CacheHelper.putObject(CacheConstants.IDEA_NAMESPACE, keyOfTheList, ideas, expiryDelay); } }
From source file:org.jahia.services.render.filter.cache.AggregateCacheFilter.java
@Override public void finalize(RenderContext renderContext, Resource resource, RenderChain chain) { LinkedList<String> userKeysLinkedList = userKeys.get(); if (userKeysLinkedList != null && userKeysLinkedList.size() > 0) { String finalKey = userKeysLinkedList.remove(0); if (finalKey.equals(acquiredSemaphore.get())) { generatorQueue.getAvailableProcessings().release(); acquiredSemaphore.set(null); }/*w w w. ja v a 2s . co m*/ Set<CountDownLatch> latches = processingLatches.get(); Map<String, CountDownLatch> countDownLatchMap = generatorQueue.getGeneratingModules(); CountDownLatch latch = countDownLatchMap.get(finalKey); if (latches != null && latches.contains(latch)) { latch.countDown(); synchronized (countDownLatchMap) { latches.remove(countDownLatchMap.remove(finalKey)); } } } }
From source file:com.tencent.wstt.gt.activity.GTLogFragment.java
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View logLayout = inflater.inflate(R.layout.gt_logactivity, container, false); displayWidth = DeviceUtils.getDisplayWidth(getActivity()); rl_log_filter = (RelativeLayout) logLayout.findViewById(R.id.rl_log_filter); cb_logcatSwitch = (GTCheckBox) logLayout.findViewById(R.id.cb_logcat_switch); cb_logcatSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override/* ww w.ja va2 s.c o m*/ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { // TODO logcat? logcatTask = new LogcatRunnable(); new Thread(logcatTask).start(); } else { logcatTask.killReader(); } } }); btn_delete = (ImageButton) logLayout.findViewById(R.id.gtlog_delete); btn_save = (ImageButton) logLayout.findViewById(R.id.gtlog_save); btn_open = (ImageButton) logLayout.findViewById(R.id.gtlog_open); btn_level_toast = (ImageButton) logLayout.findViewById(R.id.log_level_toast); btn_tag_toast = (ImageButton) logLayout.findViewById(R.id.log_tag_toast); /* * ??ImageView ??filterListViewfilterListView */ img_empty = (ImageView) logLayout.findViewById(R.id.view_empty); img_empty.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { img_empty.setVisibility(View.GONE); filterListView.setVisibility(View.GONE); cancelFilterMsgInput(v); return false; } }); /* * ? */ RelativeLayout rl_save = (RelativeLayout) LayoutInflater.from(getActivity()) .inflate(R.layout.gt_dailog_save, null, false); ImageButton btn_cleanSavePath = (ImageButton) rl_save.findViewById(R.id.save_clean); btn_cleanSavePath.setOnClickListener(this); et_savePath = (EditText) rl_save.findViewById(R.id.save_editor); String lastSaveLog = GTLogInternal.getLastSaveLog(); if (lastSaveLog != null && lastSaveLog.contains(".") && lastSaveLog.endsWith(LogUtils.LOG_POSFIX)) { lastSaveLog = lastSaveLog.substring(0, lastSaveLog.lastIndexOf(".")); } et_savePath.setText(lastSaveLog); dlg_save = new Builder(getActivity()).setTitle(getString(R.string.save_file)).setView(rl_save) .setPositiveButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).setNegativeButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // ?? String path = et_savePath.getText().toString(); try { File f = null; if (FileUtil.isPathStringValid(path)) { String validPath = FileUtil.convertValidFilePath(path, LogUtils.LOG_POSFIX); if (FileUtil.isPath(validPath)) { f = new File(validPath); f.mkdirs(); } else { f = new File(Env.ROOT_LOG_FOLDER, validPath); } GTLogInternal.setLastSaveLog(validPath); } if (f.exists()) { f.delete(); } LogUtils.writeLog(logAdapter.getUIEntryList(), f, false); } catch (Exception e) { e.printStackTrace(); } dialog.dismiss(); } }).create(); btn_save.setOnClickListener(this); // btn_delete.setOnClickListener(this); // btn_open.setOnClickListener(this); // rl_loglist = (RelativeLayout) logLayout.findViewById(R.id.rl_loglist); listView = (ListView) logLayout.findViewById(R.id.loglist); initCurLogAdapter(); logAdapter.setFilter(); listView.setAdapter(logAdapter); // button??? listView.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { rl_log_filter.setVisibility(View.GONE); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (visibleItemCount + firstVisibleItem == totalItemCount) { logAdapter.setAutoRefresh(true); } else { logAdapter.setAutoRefresh(false); } } }); // button? rl_loglist.setOnClickListener(this); listView.setOnTouchListener(logListTouchListener); // ? filterListView = (ListView) logLayout.findViewById(R.id.spinner_list); tagAdapter = new ArrayAdapter<String>(getActivity(), R.layout.gt_simple_dropdown_item); filterListView.setAdapter(tagAdapter); filterListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long arg3) { img_empty.setVisibility(View.GONE); filterListView.setVisibility(View.GONE); if (parent.getAdapter() == tagAdapter) { if (position == 0) GTLogInternal.setCurFilterTag(""); else GTLogInternal.setCurFilterTag((String) parent.getAdapter().getItem(position)); btn_tag.setText(tagAdapter.getItem(position)); } else if (parent.getAdapter() instanceof MsgAdaptor) { String sCurSelectedMsg = (String) parent.getAdapter().getItem(position); LinkedList<String> curShowDownMsgList = GTLogInternal.getCurFilterShowDownMsgList(); LinkedList<String> msgHistory = GTLogInternal.getCurFilterMsgHistory(); GTLogInternal.setCurFilterMsg(sCurSelectedMsg); msgWatched = false; et_Msg.removeTextChangedListener(msg_watcher); String s = curShowDownMsgList.remove(position); curShowDownMsgList.addFirst(s); msgHistory.remove(s); msgHistory.addFirst(s); et_Msg.setText(sCurSelectedMsg); btn_msg_clear.setVisibility(View.VISIBLE); cancelFilterMsgInput(parent); } else { GTLogInternal.setCurFilterLevel(position); btn_level.setText(levelAdapter.getItem(position)); } onLogChanged(); } }); // Activity??? GTLogInternal.addLogListener(this); // ? //btn_search = (ImageButton) findViewById(R.id.log_search); btn_search = (ImageButton) logLayout.findViewById(R.id.gtlog_search); btn_search.setOnClickListener(this); // btn_level = (Button) logLayout.findViewById(R.id.log_level); levelAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.log_level, R.layout.gt_simple_dropdown_item); btn_level.setText(levelAdapter.getItem(GTLogInternal.getCurFilterLevel())); btn_level.setOnClickListener(this); // TAG btn_tag = (Button) logLayout.findViewById(R.id.log_tag); if (GTLogInternal.getCurFilterTag().length() == 0) { btn_tag.setText("TAG"); } else { btn_tag.setText(GTLogInternal.getCurFilterTag()); } btn_tag.setOnClickListener(this); // et_Msg = (EditText) logLayout.findViewById(R.id.log_msg); et_Msg.setText(GTLogInternal.getCurFilterMsg()); et_Msg.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus && !logAdapter.isEmpty())// edit? { msgEtOnFocusOrClick(); } } }); et_Msg.setOnClickListener(this); et_Msg.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_ENTER: // ?showdown? msgWatched = false; et_Msg.removeTextChangedListener(msg_watcher); String word = et_Msg.getText().toString(); if (!word.equals("")) { LinkedList<String> curShowDownMsgList = GTLogInternal.getCurFilterShowDownMsgList(); LinkedList<String> msgHistory = GTLogInternal.getCurFilterMsgHistory(); msgHistory.remove(word); msgHistory.addFirst(word); curShowDownMsgList.remove(word); curShowDownMsgList.addFirst(word); } filterListView.setVisibility(View.GONE); img_empty.setVisibility(View.GONE); cancelFilterMsgInput(v); return true; } return false; } }); // ? btn_msg_clear = (ImageButton) logLayout.findViewById(R.id.log_msg_clear); btn_msg_clear.setOnClickListener(this); if (et_Msg.getText().toString().length() > 0) { btn_msg_clear.setVisibility(View.VISIBLE); } else { btn_msg_clear.setVisibility(View.GONE); } // ? btn_msg_input_cancel = (Button) logLayout.findViewById(R.id.log_msg_cancel); btn_msg_input_cancel.setOnClickListener(this); handler = new Handler(); return logLayout; }
From source file:eu.clarin.cmdi.vlo.importer.MetadataImporter.java
/** * if user specified which data roots should be imported, list of existing * data roots will be filtered with the list from user * * @param dataRoots complete list of DataRoots * @return list of DataRoots without DataRoots excluded by the user *///from ww w .ja v a2s . co m protected List<DataRoot> filterDataRootsWithCLArgs(List<DataRoot> dataRoots) { if (clDatarootsList == null) { return dataRoots; } LOG.info("Filtering configured data root files with command line arguments: \"" + clDatarootsList + "\""); LinkedList<File> fsDataRoots = new LinkedList<>(); List<String> paths = Arrays.asList((clDatarootsList.split("\\s+"))); //Convert String paths to File objects for comparison for (String path : paths) { fsDataRoots.add(new File(path)); } List<DataRoot> filteredDataRoots = new LinkedList<>(); try { //filter data dr: for (DataRoot dataRoot : dataRoots) { for (File fsDataRoot : fsDataRoots) { if (fsDataRoot.getCanonicalPath().equals(dataRoot.getRootFile().getCanonicalPath())) { filteredDataRoots.add(dataRoot); fsDataRoots.remove(fsDataRoot); continue dr; } } LOG.info("Root file " + dataRoot.getRootFile() + " will be omitted from processing"); } } catch (IOException e) { filteredDataRoots = dataRoots; } return filteredDataRoots; }
From source file:net.semanticmetadata.lire.imageanalysis.bovw.LocalFeatureHistogramBuilderFromCodeBook.java
private HashSet<Integer> selectVocabularyDocs() throws IOException { // need to make sure that this is not running forever ... int loopCount = 0; float maxDocs = reader.maxDoc(); int capacity = (int) Math.min(numDocsForVocabulary, maxDocs); if (capacity < 0) capacity = (int) (maxDocs / 2); HashSet<Integer> result = new HashSet<Integer>(capacity); int tmpDocNumber, tmpIndex; LinkedList<Integer> docCandidates = new LinkedList<Integer>(); // three cases: ///* w w w .j av a 2 s . co m*/ // either it's more or the same number as documents if (numDocsForVocabulary >= maxDocs) { for (int i = 0; i < maxDocs; i++) { result.add(i); } return result; } else if (numDocsForVocabulary >= maxDocs - 100) { // or it's slightly less: for (int i = 0; i < maxDocs; i++) { result.add(i); } while (result.size() > numDocsForVocabulary) { result.remove((int) Math.floor(Math.random() * result.size())); } return result; } else { for (int i = 0; i < maxDocs; i++) { docCandidates.add(i); } for (int r = 0; r < capacity; r++) { boolean worksFine = false; do { tmpIndex = (int) Math.floor(Math.random() * (double) docCandidates.size()); tmpDocNumber = docCandidates.get(tmpIndex); docCandidates.remove(tmpIndex); // check if the selected doc number is valid: not null, not deleted and not already chosen. worksFine = (reader.document(tmpDocNumber) != null) && !result.contains(tmpDocNumber); } while (!worksFine); result.add(tmpDocNumber); // need to make sure that this is not running forever ... if (loopCount++ > capacity * 100) throw new UnsupportedOperationException( "Could not get the documents, maybe there are not enough documents in the index?"); } return result; } }
From source file:mase.spec.StochasticHybridExchanger.java
protected Individual[] selectIndividuals(Individual[] pool, int num, MergeSelection mode, EvolutionState state) {/*from ww w .jav a 2 s. co m*/ Individual[] picked = new Individual[num]; if (mode == MergeSelection.truncate) { Individual[] sorted = sortedCopy(pool); System.arraycopy(sorted, 0, picked, 0, num); } else if (mode == MergeSelection.fitnessproportionate) { double total = 0; LinkedList<Individual> poolList = new LinkedList<>(); for (Individual ind : pool) { poolList.add(ind); total += ((SimpleFitness) ind.fitness).fitness(); } int index = 0; while (index < num) { double accum = 0; double rand = state.random[0].nextDouble() * total; Iterator<Individual> iter = poolList.iterator(); while (iter.hasNext()) { Individual ind = iter.next(); accum += ((SimpleFitness) ind.fitness).fitness(); if (accum >= rand) { picked[index++] = ind; iter.remove(); total -= ((SimpleFitness) ind.fitness).fitness(); break; } } } } else if (mode == MergeSelection.random) { LinkedList<Individual> poolList = new LinkedList<>(Arrays.asList(pool)); int index = 0; while (index < num) { int rand = state.random[0].nextInt(poolList.size()); picked[index++] = poolList.get(rand); poolList.remove(rand); } } else { state.output.fatal("Unknown picking mode: " + mode); } return picked; }
From source file:mase.spec.BasicHybridExchanger.java
protected Individual[] pickIndividuals(Individual[] pool, int num, PickMode mode, EvolutionState state) { Individual[] picked = new Individual[num]; if (mode == PickMode.first) { System.arraycopy(pool, 0, picked, 0, num); } else if (mode == PickMode.elite) { Individual[] sorted = sortedCopy(pool); System.arraycopy(sorted, 0, picked, 0, num); } else if (mode == PickMode.probabilistic) { double total = 0; LinkedList<Individual> poolList = new LinkedList<>(); for (Individual ind : pool) { poolList.add(ind);/* w w w.j a v a 2s . c o m*/ total += ((SimpleFitness) ind.fitness).fitness(); } int index = 0; while (index < num) { double accum = 0; double rand = state.random[0].nextDouble() * total; Iterator<Individual> iter = poolList.iterator(); while (iter.hasNext()) { Individual ind = iter.next(); accum += ((SimpleFitness) ind.fitness).fitness(); if (accum >= rand) { picked[index++] = ind; iter.remove(); total -= ((SimpleFitness) ind.fitness).fitness(); break; } } } } else if (mode == PickMode.random) { LinkedList<Individual> poolList = new LinkedList<>(Arrays.asList(pool)); int index = 0; while (index < num) { int rand = state.random[0].nextInt(poolList.size()); picked[index++] = poolList.get(rand); poolList.remove(rand); } } else { state.output.fatal("Unknown picking mode: " + mode); } return picked; }
From source file:org.minig.imap.EncodedWord.java
/** * Takes a text in form of a CharSequence encoded in the given charset (e.g. * ISO-8859-1) and makes it US-ASCII compatible and RFC822 compatible for * the use as e.g. subject with special characters. <br> * This algorithm tries to achieve several goals when decoding: <li>never * encode a single character but try to encode whole words</li> <li>if two * words must be encoded and there a no more than 3 characters inbetween, * encode everything in one single encoded word</li> <li>an encoded word * must never be longer than 76 characters in total</li> <li>ensure that no * encodedWord is in a line-wrap (RFC822 advices to no have more than 78 * characters in a headerline)</li> * //from w ww . ja v a 2 s .com * @param input * the headerline * @param charset * the used charset (e.g. ISO-8859-1) * @param type * the encoding to be used * @return input encoded in EncodedWords */ public static StringBuilder encode(CharSequence input, Charset charset, int type) { StringBuilder result = new StringBuilder(input.length()); LinkedList<int[]> words = new LinkedList<int[]>(); String encodedWordPrototype; int maxLength; if (type == QUOTED_PRINTABLE) { encodedWordPrototype = "=?" + charset.displayName() + "?q?"; maxLength = 75 - encodedWordPrototype.length() - 2; } else { encodedWordPrototype = "=?" + charset.displayName() + "?b?"; maxLength = 75 - encodedWordPrototype.length() - 6; } // First find words which need to be encoded Matcher matcher = wordTokenizerPattern.matcher(input); float encodedChar = type == QUOTED_PRINTABLE ? 3.0f : 4.0f / 3.0f; float normalChar = type == QUOTED_PRINTABLE ? 1.0f : 4.0f / 3.0f; while (matcher.find()) { String word = matcher.group(1); float encodedLength = 0.0f; int start = matcher.start(); int end = matcher.end(); boolean mustEncode = false; for (int i = 0; i < word.length(); i++) { if (word.charAt(i) > 127) { encodedLength += encodedChar; mustEncode = true; } else { encodedLength += normalChar; } // Split if too long if (Math.ceil(encodedLength) > maxLength) { words.add(new int[] { start, start + i, maxLength }); word = word.substring(i); start += i; i = 0; encodedLength = 0.0f; mustEncode = false; } } if (mustEncode) words.add(new int[] { start, end, (int) Math.ceil(encodedLength) }); } // No need to create encodedWords if (words.isEmpty()) { return result.append(input); } // Second group them together if possible (see goals above) int[] last = null; for (int i = 0; i < words.size(); i++) { int[] act = words.get(i); if (last != null && (last[2] + act[2] + (act[0] - last[1]) * normalChar < maxLength) && (act[0] - last[1]) < 10) { words.remove(i--); last[1] = act[1]; last[2] += act[2] + (act[0] - last[1]) * normalChar; } else { last = act; } } // Create encodedWords Iterator<int[]> it = words.iterator(); int lastWordEnd = 0; while (it.hasNext()) { int[] act = it.next(); // create encoded part CharSequence rawWord = input.subSequence(act[0], act[1]); CharSequence encodedPart; if (type == QUOTED_PRINTABLE) { // Replace <space> with _ Matcher wsMatcher = whitespacePattern.matcher(rawWord); rawWord = wsMatcher.replaceAll("_"); encodedPart = QuotedPrintable.encode(rawWord, charset); } else { encodedPart = Base64.encodeBase64String(charset.encode(CharBuffer.wrap(rawWord)).array()); } result.append(input.subSequence(lastWordEnd, act[0])); result.append(encodedWordPrototype); result.append(encodedPart); result.append("?="); lastWordEnd = act[1]; } result.append(input.subSequence(lastWordEnd, input.length())); return result; }
From source file:se.trixon.pacoma.ui.MainFrame.java
private void initListeners() { mActionManager.addAppListener(new ActionManager.AppListener() { @Override/*from ww w . j a v a 2s . c om*/ public void onCancel(ActionEvent actionEvent) { } @Override public void onMenu(ActionEvent actionEvent) { if (actionEvent.getSource() != menuButton) { menuButtonMousePressed(null); } } @Override public void onOptions(ActionEvent actionEvent) { showOptions(); } @Override public void onQuit(ActionEvent actionEvent) { quit(); } @Override public void onRedo(ActionEvent actionEvent) { mCollage.nextHistory(); updateToolButtons(); } @Override public void onStart(ActionEvent actionEvent) { } @Override public void onUndo(ActionEvent actionEvent) { mCollage.prevHistory(); updateToolButtons(); } }); mActionManager.addProfileListener(new ActionManager.ProfileListener() { @Override public void onAdd(ActionEvent actionEvent) { addImages(); } @Override public void onClear(ActionEvent actionEvent) { mCollage.clearFiles(); } @Override public void onClose(ActionEvent actionEvent) { setTitle("pacoma"); mActionManager.setEnabledDocumentActions(false); canvasPanel.close(); } @Override public void onEdit(ActionEvent actionEvent) { editCollage(mCollage); } @Override public void onRegenerate(ActionEvent actionEvent) { //TODO } @Override public void onNew(ActionEvent actionEvent) { editCollage(null); if (mCollage != null && mCollage.getName() != null) { setTitle(mCollage); canvasPanel.open(mCollage); mActionManager.getAction(ActionManager.CLEAR).setEnabled(false); mActionManager.getAction(ActionManager.REGENERATE).setEnabled(false); } } @Override public void onOpen(ActionEvent actionEvent) { initFileDialog(mCollageFileNameExtensionFilter); if (SimpleDialog.openFile()) { try { open(SimpleDialog.getPath()); } catch (IOException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } } } @Override public void onSave(ActionEvent actionEvent) { save(); } @Override public void onSaveAs(ActionEvent actionEvent) { saveAs(); } }); mCollagePropertyChangeListener = () -> { if (mCollage != null) { setTitle(mCollage); mActionManager.getAction(ActionManager.SAVE).setEnabled(true); mActionManager.getAction(ActionManager.CLEAR).setEnabled(mCollage.hasImages()); mActionManager.getAction(ActionManager.REGENERATE).setEnabled(mCollage.hasImages()); } }; mDropTarget = new DropTarget() { @Override public synchronized void drop(DropTargetDropEvent evt) { try { evt.acceptDrop(DnDConstants.ACTION_COPY); LinkedList<File> droppedFiles = new LinkedList<>( (List<File>) evt.getTransferable().getTransferData(DataFlavor.javaFileListFlavor)); List<File> invalidFiles = new LinkedList<>(); droppedFiles.forEach((droppedFile) -> { if (droppedFile.isFile() && FilenameUtils.isExtension( droppedFile.getName().toLowerCase(Locale.getDefault()), Collage.FILE_EXT)) { //all ok } else { invalidFiles.add(droppedFile); } }); invalidFiles.forEach((invalidFile) -> { droppedFiles.remove(invalidFile); }); switch (droppedFiles.size()) { case 0: Message.error(MainFrame.this, Dict.Dialog.TITLE_IO_ERROR.toString(), "Not a valid collage file."); break; case 1: open(droppedFiles.getFirst()); break; default: Message.error(MainFrame.this, Dict.Dialog.TITLE_IO_ERROR.toString(), "Too many files dropped."); break; } } catch (UnsupportedFlavorException | IOException ex) { System.err.println(ex.getMessage()); } } }; canvasPanel.setDropTarget(mDropTarget); }