List of usage examples for java.util Collections synchronizedList
public static <T> List<T> synchronizedList(List<T> list)
From source file:org.jasig.portal.groups.smartldap.SmartLdapGroupStore.java
private GroupsTree buildGroupsTree() { long timestamp = System.currentTimeMillis(); // Prepare the new local indeces... Map<String, IEntityGroup> new_groups = Collections.synchronizedMap(new HashMap<String, IEntityGroup>()); Map<String, List<String>> new_parents = Collections.synchronizedMap(new HashMap<String, List<String>>()); Map<String, List<String>> new_children = Collections.synchronizedMap(new HashMap<String, List<String>>()); Map<String, List<String>> new_keysByUpperCaseName = Collections .synchronizedMap(new HashMap<String, List<String>>()); // Gather IEntityGroup objects from LDAP... RuntimeRequestResponse req = new RuntimeRequestResponse(); Set<LdapRecord> set = new HashSet<LdapRecord>(); req.setAttribute("GROUPS", set); req.setAttribute("smartLdapGroupStore", this); SubQueryCounter queryCounter = new SubQueryCounter(); req.setAttribute("queryCounter", queryCounter); req.setAttribute("baseFilter", spring_context.getBean("filter")); for (String name : spring_context.getBeanDefinitionNames()) { req.setAttribute(name, spring_context.getBean(name)); }/* w ww .ja v a 2 s.c o m*/ runner.run(initTask, req); if (log.isInfoEnabled()) { String msg = "init() found " + set.size() + " records."; log.info(msg); } // Do a first loop to build the main catalog (new_groups)... for (LdapRecord r : set) { // new_groups (me)... IEntityGroup g = r.getGroup(); new_groups.put(g.getLocalKey(), g); } // Do a second loop to build local indeces... for (LdapRecord r : set) { IEntityGroup g = r.getGroup(); // new_parents (I am a parent for all my children)... for (String childKey : r.getKeysOfChildren()) { // NB: We're only interested in relationships between // objects in the main catalog (i.e. new_groups); // discard everything else... if (!new_groups.containsKey(childKey)) { break; } List<String> parentsList = new_parents.get(childKey); if (parentsList == null) { // first parent for this child... parentsList = Collections.synchronizedList(new LinkedList<String>()); new_parents.put(childKey, parentsList); } parentsList.add(g.getLocalKey()); } // new_children... List<String> childrenList = Collections.synchronizedList(new LinkedList<String>()); for (String childKey : r.getKeysOfChildren()) { // NB: We're only interested in relationships between // objects in the main catalog (i.e. new_groups); // discard everything else... if (new_groups.containsKey(childKey)) { childrenList.add(childKey); } } new_children.put(g.getLocalKey(), childrenList); // new_keysByUpperCaseName... List<String> groupsWithMyName = new_keysByUpperCaseName.get(g.getName().toUpperCase()); if (groupsWithMyName == null) { // I am the first group with my name (pretty likely)... groupsWithMyName = Collections.synchronizedList(new LinkedList<String>()); new_keysByUpperCaseName.put(g.getName().toUpperCase(), groupsWithMyName); } groupsWithMyName.add(g.getLocalKey()); } /* * Now load the ROOT_GROUP into the collections... */ // new_groups (me)... new_groups.put(ROOT_GROUP.getLocalKey(), ROOT_GROUP); // new_parents (I am a parent for all groups that have no other parent)... List<String> childrenOfRoot = Collections.synchronizedList(new LinkedList<String>()); // for later... for (String possibleChildKey : new_groups.keySet()) { if (!possibleChildKey.equals(ROOT_GROUP.getLocalKey()) && !new_parents.containsKey(possibleChildKey)) { List<String> p = Collections.synchronizedList(new LinkedList<String>()); p.add(ROOT_GROUP.getLocalKey()); new_parents.put(possibleChildKey, p); childrenOfRoot.add(possibleChildKey); // for later... } } // new_children... new_children.put(ROOT_GROUP.getLocalKey(), childrenOfRoot); // new_keysByUpperCaseName... List<String> groupsWithMyName = new_keysByUpperCaseName.get(ROOT_GROUP.getName().toUpperCase()); if (groupsWithMyName == null) { // I am the first group with my name (pretty likely)... groupsWithMyName = Collections.synchronizedList(new LinkedList<String>()); new_keysByUpperCaseName.put(ROOT_GROUP.getName().toUpperCase(), groupsWithMyName); } groupsWithMyName.add(ROOT_GROUP.getLocalKey()); if (log.isInfoEnabled()) { long benchmark = System.currentTimeMillis() - timestamp; log.info("Refresh of groups tree completed in " + benchmark + " milliseconds"); log.info("Total number of LDAP queries: " + (queryCounter.getCount() + 1)); String msg = "init() :: final size of each collection is as follows..." + "\n\tgroups=" + new_groups.size() + "\n\tparents=" + new_parents.size() + "\n\tchildren=" + new_children.size() + "\n\tkeysByUpperCaseName=" + new_keysByUpperCaseName.size(); log.info(msg); } if (log.isTraceEnabled()) { StringBuilder msg = new StringBuilder(); // new_groups... msg.setLength(0); msg.append("Here are the keys of the new_groups collection:"); for (String s : new_groups.keySet()) { msg.append("\n\t").append(s); } log.trace(msg.toString()); // new_parents... msg.setLength(0); msg.append("Here are the parents of each child in the new_parents collection:"); for (Map.Entry<String, List<String>> y : new_parents.entrySet()) { msg.append("\n\tchild=").append(y.getKey()); for (String s : y.getValue()) { msg.append("\n\t\tparent=").append(s); } } log.trace(msg.toString()); // new_children... msg.setLength(0); msg.append("Here are the children of each parent in the new_children collection:"); for (Map.Entry<String, List<String>> y : new_children.entrySet()) { msg.append("\n\tparent=").append(y.getKey()); for (String s : y.getValue()) { msg.append("\n\t\tchild=").append(s); } } log.trace(msg.toString()); // new_keysByUpperCaseName... msg.append("Here are the groups that have each name in the new_keysByUpperCaseName collection:"); for (Map.Entry<String, List<String>> y : new_keysByUpperCaseName.entrySet()) { msg.append("\n\tname=").append(y.getKey()); for (String s : y.getValue()) { msg.append("\n\t\tgroup=").append(s); } } log.trace(msg.toString()); } return new GroupsTree(new_groups, new_parents, new_children, new_keysByUpperCaseName); }
From source file:com.emc.ecs.sync.storage.CasStorageTest.java
private String summarize(FPPool pool, List<String> clipIds) throws Exception { List<String> summaries = Collections.synchronizedList(new ArrayList<String>()); ExecutorService service = Executors.newFixedThreadPool(CAS_THREADS); System.out.print("Summarizing clips"); for (String clipId : clipIds) { service.submit(new ClipReader(pool, clipId, summaries)); }//from ww w . ja va2 s .co m service.shutdown(); service.awaitTermination(CAS_SETUP_WAIT_MINUTES, TimeUnit.MINUTES); service.shutdownNow(); System.out.println(); Collections.sort(summaries); StringBuilder out = new StringBuilder(); for (String summary : summaries) { out.append(summary); } return out.toString(); }
From source file:com.t3.client.TabletopTool.java
private static void initialize() { // First time AppSetup.install();/*from w w w . ja v a 2 s.c o m*/ // Clean up after ourselves try { FileUtil.delete(AppUtil.getAppHome("tmp"), 2); } catch (IOException ioe) { TabletopTool.showError("While initializing (cleaning tmpdir)", ioe); } // We'll manage our own images ImageIO.setUseCache(false); eventDispatcher = new EventDispatcher(); registerEvents(); soundManager = new SoundManager(); try { soundManager.configure(SOUND_PROPERTIES); soundManager.registerSoundEvent(SND_INVALID_OPERATION, soundManager.getRegisteredSound("Dink")); } catch (IOException ioe) { TabletopTool.showError("While initializing (configuring sound)", ioe); } assetTransferManager = new AssetTransferManager(); assetTransferManager.addConsumerListener(new AssetTransferHandler()); playerList = new ObservableList<Player>(); messageList = new ObservableList<TextMessage>(Collections.synchronizedList(new ArrayList<TextMessage>())); handler = new ClientMethodHandler(); setClientFrame(new T3Frame(menuBar)); serverCommand = new ServerCommandClientImpl(); player = new Player("", Player.Role.GM, ""); try { startPersonalServer(CampaignFactory.createBasicCampaign()); } catch (Exception e) { TabletopTool.showError("While starting personal server", e); } AppActions.updateActions(); ToolTipManager.sharedInstance().setInitialDelay(AppPreferences.getToolTipInitialDelay()); ToolTipManager.sharedInstance().setDismissDelay(AppPreferences.getToolTipDismissDelay()); ChatAutoSave.changeTimeout(AppPreferences.getChatAutosaveTime()); // TODO: make this more formal when we switch to mina new ServerHeartBeatThread().start(); }
From source file:net.rptools.maptool.client.MapTool.java
private static void initialize() { // First time AppSetup.install();/*from ww w. j av a2s . co m*/ // Clean up after ourselves try { FileUtil.delete(AppUtil.getAppHome("tmp"), 2); } catch (IOException ioe) { MapTool.showError("While initializing (cleaning tmpdir)", ioe); } // We'll manage our own images ImageIO.setUseCache(false); eventDispatcher = new EventDispatcher(); registerEvents(); soundManager = new SoundManager(); try { soundManager.configure(SOUND_PROPERTIES); soundManager.registerSoundEvent(SND_INVALID_OPERATION, soundManager.getRegisteredSound("Dink")); } catch (IOException ioe) { MapTool.showError("While initializing (configuring sound)", ioe); } assetTransferManager = new AssetTransferManager(); assetTransferManager.addConsumerListener(new AssetTransferHandler()); playerList = new ObservableList<Player>(); messageList = new ObservableList<TextMessage>(Collections.synchronizedList(new ArrayList<TextMessage>())); handler = new ClientMethodHandler(); setClientFrame(new MapToolFrame(menuBar)); serverCommand = new ServerCommandClientImpl(); player = new Player("", Player.Role.GM, ""); try { startPersonalServer(CampaignFactory.createBasicCampaign()); } catch (Exception e) { MapTool.showError("While starting personal server", e); } AppActions.updateActions(); ToolTipManager.sharedInstance().setInitialDelay(AppPreferences.getToolTipInitialDelay()); ToolTipManager.sharedInstance().setDismissDelay(AppPreferences.getToolTipDismissDelay()); ChatAutoSave.changeTimeout(AppPreferences.getChatAutosaveTime()); // TODO: make this more formal when we switch to mina new ServerHeartBeatThread().start(); }
From source file:ti.modules.titanium.ui.widget.abslistview.TiAbsListView.java
public TiAbsListView(TiViewProxy proxy, Activity activity) { super(proxy); //initializing variables sections = Collections.synchronizedList(new ArrayList<AbsListSectionProxy>()); itemTypeCount = new AtomicInteger(CUSTOM_TEMPLATE_ITEM_TYPE); templatesByBinding = new HashMap<String, TiAbsListViewTemplate>(); defaultTemplateBinding = defaultTemplateKey; templatesByBinding.put(defaultTemplateKey, defaultTemplate); defaultTemplate.setType(BUILT_IN_TEMPLATE_ITEM_TYPE); caseInsensitive = true;/* w ww.j a v a 2 s. c o m*/ ignoreExactMatch = false; //handling marker HashMap preloadMarker = ((AbsListViewProxy) proxy).getPreloadMarker(); if (preloadMarker != null) { setMarker(preloadMarker); } else { resetMarker(); } final KrollProxy fProxy = proxy; //initializing listView listView = createListView(activity); listView.setSelector(android.R.color.transparent); listView.setAreHeadersSticky(false); // listView.setDuplicateParentStateEnabled(true); AbsListView internalListView = getInternalListView(); if (TiC.LOLLIPOP_OR_GREATER) { listView.setNestedScrollingEnabled(true); internalListView.setNestedScrollingEnabled(true); } if (internalListView instanceof ListView) { ((ListView) internalListView).setHeaderDividersEnabled(false); ((ListView) internalListView).setFooterDividersEnabled(false); } if (listView instanceof CustomListView) { ((CustomListView) listView).setOnPullListener(new OnPullListener() { private boolean canUpdate = false; @Override public void onPull(boolean canUpdate) { if (canUpdate != this.canUpdate) { this.canUpdate = canUpdate; if (fProxy.hasListeners(TiC.EVENT_PULL_CHANGED, false)) { KrollDict event = dictForScrollEvent(); event.put("active", canUpdate); fProxy.fireEvent(TiC.EVENT_PULL_CHANGED, event, false, false); } } if (fProxy.hasListeners(TiC.EVENT_PULL, false)) { KrollDict event = dictForScrollEvent(); event.put("active", canUpdate); fProxy.fireEvent(TiC.EVENT_PULL, event, false, false); } } @Override public void onPullEnd(boolean canUpdate) { if (fProxy.hasListeners(TiC.EVENT_PULL_END, false)) { KrollDict event = dictForScrollEvent(); event.put("active", canUpdate); fProxy.fireEvent(TiC.EVENT_PULL_END, event, false, false); } } }); } adapter = new TiBaseAdapter(activity); listView.setOnScrollListener(new OnScrollListener() { private boolean scrollTouch = false; private int lastValidfirstItem = 0; private Timer endTimer = null; public void cancelEndCall() { if (endTimer != null) { endTimer.cancel(); endTimer = null; } } public void delayEndCall() { cancelEndCall(); endTimer = new Timer(); TimerTask action = new TimerTask() { public void run() { scrollTouch = false; if (fProxy.hasListeners(TiC.EVENT_SCROLLEND, false)) { fProxy.fireEvent(TiC.EVENT_SCROLLEND, dictForScrollEvent(), false, false); } } }; this.endTimer.schedule(action, 200); } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { view.requestDisallowInterceptTouchEvent(scrollState != ViewPager.SCROLL_STATE_IDLE); if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { if (scrollTouch) { delayEndCall(); } } else if (scrollState == OnScrollListener.SCROLL_STATE_FLING) { cancelEndCall(); } else if (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { cancelEndCall(); if (hideKeyboardOnScroll && hasFocus()) { blur(); } if (scrollTouch == false) { scrollTouch = true; if (fProxy.hasListeners(TiC.EVENT_SCROLLSTART, false)) { fProxy.fireEvent(TiC.EVENT_SCROLLSTART, dictForScrollEvent(), false, false); } } } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // Log.d(TAG, "onScroll : " + scrollValid, Log.DEBUG_MODE); // boolean fireScroll = scrollValid; // if (!fireScroll && visibleItemCount > 0) { // //Items in a list can be selected with a track ball in which case // //we must check to see if the first visibleItem has changed. // fireScroll = (lastValidfirstItem != firstVisibleItem); // } if (fProxy.hasListeners(TiC.EVENT_SCROLL, false)) { int newScrollOffset = getScroll(); // Log.d(TAG, "newScrollOffset : " + newScrollOffset, Log.DEBUG_MODE); lastValidfirstItem = firstVisibleItem; if (newScrollOffset != currentScrollOffset) { currentScrollOffset = newScrollOffset; fProxy.fireEvent(TiC.EVENT_SCROLL, dictForScrollEvent(currentScrollOffset), false, false); } } } }); listView.setOnStickyHeaderChangedListener(new OnStickyHeaderChangedListener() { @Override public void onStickyHeaderChanged(StickyListHeadersListViewAbstract l, View header, int itemPosition, long headerId) { //for us headerId is the section index int sectionIndex = (int) headerId; if (fProxy.hasListeners(TiC.EVENT_HEADER_CHANGE, false)) { KrollDict data = new KrollDict(); AbsListSectionProxy section = null; synchronized (sections) { if (sectionIndex >= 0 && sectionIndex < sections.size()) { section = sections.get(sectionIndex); } else { return; } } data.put(TiC.PROPERTY_HEADER_VIEW, section.getHoldedProxy(TiC.PROPERTY_HEADER_VIEW)); data.put(TiC.PROPERTY_SECTION, section); data.put(TiC.PROPERTY_SECTION_INDEX, sectionIndex); fProxy.fireEvent(TiC.EVENT_HEADER_CHANGE, data, false, false); } } }); internalListView.setCacheColorHint(Color.TRANSPARENT); listView.setEnabled(true); getLayoutParams().autoFillsHeight = true; getLayoutParams().autoFillsWidth = true; // listView.setFocusable(false); listView.setFocusable(true); listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); // try { // // headerFooterId = TiRHelper.getApplicationResource("layout.titanium_ui_list_header_or_footer"); // // titleId = TiRHelper.getApplicationResource("id.titanium_ui_list_header_or_footer_title"); // isCheck = TiRHelper.getApplicationResource("drawable.btn_check_buttonless_on_64"); // hasChild = TiRHelper.getApplicationResource("drawable.btn_more_64"); // disclosure = TiRHelper.getApplicationResource("drawable.disclosure_64"); // } catch (ResourceNotFoundException e) { // Log.e(TAG, "XML resources could not be found!!!", Log.DEBUG_MODE); // } setNativeView(listView); }
From source file:org.apereo.portal.groups.smartldap.SmartLdapGroupStore.java
private GroupsTree buildGroupsTree() { long timestamp = System.currentTimeMillis(); // Prepare the new local indeces... Map<String, IEntityGroup> new_groups = Collections.synchronizedMap(new HashMap<String, IEntityGroup>()); Map<String, List<String>> new_parents = Collections.synchronizedMap(new HashMap<String, List<String>>()); Map<String, List<String>> new_children = Collections.synchronizedMap(new HashMap<String, List<String>>()); Map<String, List<String>> new_keysByUpperCaseName = Collections .synchronizedMap(new HashMap<String, List<String>>()); // Gather IEntityGroup objects from LDAP... RuntimeRequestResponse req = new RuntimeRequestResponse(); Set<LdapRecord> set = new HashSet<>(); req.setAttribute("GROUPS", set); req.setAttribute("smartLdapGroupStore", this); SubQueryCounter queryCounter = new SubQueryCounter(); req.setAttribute("queryCounter", queryCounter); req.setAttribute("filter", filter); // This one changes iteratively... req.setAttribute("baseFilter", filter); // while this one stays the same. if (StringUtils.isBlank(baseGroupDn)) { throw new IllegalStateException("baseGroupDn property not set"); }/*from w w w . ja va2 s .co m*/ req.setAttribute("baseGroupDn", baseGroupDn); if (ldapContext == null) { throw new IllegalStateException("ldapContext property not set"); } req.setAttribute("ldapContext", ldapContext); req.setAttribute("resolveMemberGroups", resolveMemberGroups); req.setAttribute("resolveDnList", resolveDnList); req.setAttribute("memberOfAttributeName", memberOfAttributeName); req.setAttribute("attributesMapper", attributesMapper); runner.run(initTask, req); log.info("init() found {} records", set.size()); // Do a first loop to build the main catalog (new_groups)... for (LdapRecord r : set) { // new_groups (me)... IEntityGroup g = r.getGroup(); new_groups.put(g.getLocalKey(), g); } // Do a second loop to build local indeces... for (LdapRecord r : set) { IEntityGroup g = r.getGroup(); // new_parents (I am a parent for all my children)... for (String childKey : r.getKeysOfChildren()) { // NB: We're only interested in relationships between // objects in the main catalog (i.e. new_groups); // discard everything else... if (!new_groups.containsKey(childKey)) { break; } List<String> parentsList = new_parents.get(childKey); if (parentsList == null) { // first parent for this child... parentsList = Collections.synchronizedList(new LinkedList<String>()); new_parents.put(childKey, parentsList); } parentsList.add(g.getLocalKey()); } // new_children... List<String> childrenList = Collections.synchronizedList(new LinkedList<String>()); for (String childKey : r.getKeysOfChildren()) { // NB: We're only interested in relationships between // objects in the main catalog (i.e. new_groups); // discard everything else... if (new_groups.containsKey(childKey)) { childrenList.add(childKey); } } new_children.put(g.getLocalKey(), childrenList); // new_keysByUpperCaseName... List<String> groupsWithMyName = new_keysByUpperCaseName.get(g.getName().toUpperCase()); if (groupsWithMyName == null) { // I am the first group with my name (pretty likely)... groupsWithMyName = Collections.synchronizedList(new LinkedList<String>()); new_keysByUpperCaseName.put(g.getName().toUpperCase(), groupsWithMyName); } groupsWithMyName.add(g.getLocalKey()); } /* * Now load the ROOT_GROUP into the collections... */ // new_groups (me)... final IEntityGroup root = getRootGroup(); new_groups.put(root.getLocalKey(), root); // new_parents (I am a parent for all groups that have no other parent)... List<String> childrenOfRoot = Collections.synchronizedList(new LinkedList<String>()); // for later... for (String possibleChildKey : new_groups.keySet()) { if (!possibleChildKey.equals(root.getLocalKey()) && !new_parents.containsKey(possibleChildKey)) { List<String> p = Collections.synchronizedList(new LinkedList<String>()); p.add(root.getLocalKey()); new_parents.put(possibleChildKey, p); childrenOfRoot.add(possibleChildKey); // for later... } } // new_children... new_children.put(root.getLocalKey(), childrenOfRoot); // new_keysByUpperCaseName... List<String> groupsWithMyName = new_keysByUpperCaseName.get(root.getName().toUpperCase()); if (groupsWithMyName == null) { // I am the first group with my name (pretty likely)... groupsWithMyName = Collections.synchronizedList(new LinkedList<String>()); new_keysByUpperCaseName.put(root.getName().toUpperCase(), groupsWithMyName); } groupsWithMyName.add(root.getLocalKey()); final long benchmark = System.currentTimeMillis() - timestamp; log.info("Refresh of groups tree completed in {} milliseconds", benchmark); log.info("Total number of LDAP queries: {}", queryCounter.getCount() + 1); final String msg = "init() :: final size of each collection is as follows..." + "\n\tgroups={}" + "\n\tparents={}" + "\n\tchildren={}" + "\n\tkeysByUpperCaseName={}"; log.info(msg, new_groups.size(), new_parents.size(), new_children.size(), new_keysByUpperCaseName.size()); if (log.isTraceEnabled()) { StringBuilder sbuilder = new StringBuilder(); // new_groups... sbuilder.setLength(0); sbuilder.append("Here are the keys of the new_groups collection:"); for (String s : new_groups.keySet()) { sbuilder.append("\n\t").append(s); } log.trace(sbuilder.toString()); // new_parents... sbuilder.setLength(0); sbuilder.append("Here are the parents of each child in the new_parents collection:"); for (Map.Entry<String, List<String>> y : new_parents.entrySet()) { sbuilder.append("\n\tchild=").append(y.getKey()); for (String s : y.getValue()) { sbuilder.append("\n\t\tparent=").append(s); } } log.trace(sbuilder.toString()); // new_children... sbuilder.setLength(0); sbuilder.append("Here are the children of each parent in the new_children collection:"); for (Map.Entry<String, List<String>> y : new_children.entrySet()) { sbuilder.append("\n\tparent=").append(y.getKey()); for (String s : y.getValue()) { sbuilder.append("\n\t\tchild=").append(s); } } log.trace(sbuilder.toString()); // new_keysByUpperCaseName... sbuilder.append("Here are the groups that have each name in the new_keysByUpperCaseName collection:"); for (Map.Entry<String, List<String>> y : new_keysByUpperCaseName.entrySet()) { sbuilder.append("\n\tname=").append(y.getKey()); for (String s : y.getValue()) { sbuilder.append("\n\t\tgroup=").append(s); } } log.trace(sbuilder.toString()); } return new GroupsTree(new_groups, new_parents, new_children, new_keysByUpperCaseName); }
From source file:org.owasp.esapi.reference.DefaultHTTPUtilities.java
/** * {@inheritDoc}/*from ww w . jav a 2s.c o m*/ */ public List<File> getFileUploads(HttpServletRequest request, File finalDir, List allowedExtensions) throws ValidationException { File tempDir = ESAPI.securityConfiguration().getUploadTempDirectory(); if (!tempDir.exists()) { if (!tempDir.mkdirs()) throw new ValidationUploadException("Upload failed", "Could not create temp directory: " + tempDir.getAbsolutePath()); } if (finalDir != null) { if (!finalDir.exists()) { if (!finalDir.mkdirs()) throw new ValidationUploadException("Upload failed", "Could not create final upload directory: " + finalDir.getAbsolutePath()); } } else { if (!ESAPI.securityConfiguration().getUploadDirectory().exists()) { if (!ESAPI.securityConfiguration().getUploadDirectory().mkdirs()) throw new ValidationUploadException("Upload failed", "Could not create final upload directory: " + ESAPI.securityConfiguration().getUploadDirectory().getAbsolutePath()); } finalDir = ESAPI.securityConfiguration().getUploadDirectory(); } List<File> newFiles = new ArrayList<File>(); try { final HttpSession session = request.getSession(false); if (!ServletFileUpload.isMultipartContent(request)) { throw new ValidationUploadException("Upload failed", "Not a multipart request"); } // this factory will store ALL files in the temp directory, // regardless of size DiskFileItemFactory factory = new DiskFileItemFactory(0, tempDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxBytes); // Create a progress listener ProgressListener progressListener = new ProgressListener() { private long megaBytes = -1; private long progress = 0; public void update(long pBytesRead, long pContentLength, int pItems) { if (pItems == 0) return; long mBytes = pBytesRead / 1000000; if (megaBytes == mBytes) return; megaBytes = mBytes; progress = (long) (((double) pBytesRead / (double) pContentLength) * 100); if (session != null) { session.setAttribute("progress", Long.toString(progress)); } // logger.logSuccess(Logger.SECURITY, " Item " + pItems + " (" + progress + "% of " + pContentLength + " bytes]"); } }; upload.setProgressListener(progressListener); List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (!item.isFormField() && item.getName() != null && !(item.getName().equals(""))) { String[] fparts = item.getName().split("[\\/\\\\]"); String filename = fparts[fparts.length - 1]; if (!ESAPI.validator().isValidFileName("upload", filename, allowedExtensions, false)) { throw new ValidationUploadException( "Upload only simple filenames with the following extensions " + allowedExtensions, "Upload failed isValidFileName check"); } logger.info(Logger.SECURITY_SUCCESS, "File upload requested: " + filename); File f = new File(finalDir, filename); if (f.exists()) { String[] parts = filename.split("\\/."); String extension = ""; if (parts.length > 1) { extension = parts[parts.length - 1]; } String filenm = filename.substring(0, filename.length() - extension.length()); f = File.createTempFile(filenm, "." + extension, finalDir); } item.write(f); newFiles.add(f); // delete temporary file item.delete(); logger.fatal(Logger.SECURITY_SUCCESS, "File successfully uploaded: " + f); if (session != null) { session.setAttribute("progress", Long.toString(0)); } } } } catch (Exception e) { if (e instanceof ValidationUploadException) { throw (ValidationException) e; } throw new ValidationUploadException("Upload failure", "Problem during upload:" + e.getMessage(), e); } return Collections.synchronizedList(newFiles); }
From source file:org.springframework.kafka.listener.ConcurrentMessageListenerContainerTests.java
@Test public void testRebalanceWithSlowConsumer() throws Exception { this.logger.info("Start auto"); Map<String, Object> props = KafkaTestUtils.consumerProps("test101", "false", embeddedKafka); props.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, "20000"); DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(props); ContainerProperties containerProps = new ContainerProperties(topic1); final CountDownLatch latch = new CountDownLatch(8); final Set<String> listenerThreadNames = Collections.synchronizedSet(new HashSet<String>()); List<String> receivedMessages = Collections.synchronizedList(new ArrayList<>()); containerProps.setMessageListener((MessageListener<Integer, String>) message -> { listenerThreadNames.add(Thread.currentThread().getName()); try {// w ww . j ava 2 s . co m Thread.sleep(2000); } catch (InterruptedException e) { // ignore } receivedMessages.add(message.value()); listenerThreadNames.add(Thread.currentThread().getName()); latch.countDown(); }); ConcurrentMessageListenerContainer<Integer, String> container = new ConcurrentMessageListenerContainer<>(cf, containerProps); ConcurrentMessageListenerContainer<Integer, String> container2 = new ConcurrentMessageListenerContainer<>( cf, containerProps); container.setConcurrency(1); container2.setConcurrency(1); container.setBeanName("testAuto"); container2.setBeanName("testAuto2"); container.start(); ContainerTestUtils.waitForAssignment(container, embeddedKafka.getPartitionsPerTopic()); Map<String, Object> senderProps = KafkaTestUtils.producerProps(embeddedKafka); ProducerFactory<Integer, String> pf = new DefaultKafkaProducerFactory<>(senderProps); KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf); template.setDefaultTopic(topic1); template.sendDefault(0, 0, "foo"); template.sendDefault(0, 2, "bar"); template.sendDefault(0, 0, "baz"); template.sendDefault(0, 2, "qux"); template.sendDefault(1, 2, "corge"); template.sendDefault(1, 2, "grault"); template.sendDefault(1, 2, "garply"); template.sendDefault(1, 2, "waldo"); template.flush(); container2.start(); assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue(); assertThat(receivedMessages).containsOnlyOnce("foo", "bar", "baz", "qux", "corge", "grault", "garply", "waldo"); // all messages are received assertThat(receivedMessages).hasSize(8); // messages are received on separate threads assertThat(listenerThreadNames.size()).isGreaterThanOrEqualTo(2); container.stop(); container2.stop(); this.logger.info("Stop auto"); }
From source file:it.wami.map.mongodeploy.OsmSaxHandler.java
/** * //from w ww .j a v a2 s . c o m * @param way the Way */ private void populateWayGeo(Way way) { Runnable r = new WayRunnable(db, way, waysQueue); waysRunnables.add(r); int current = (int) (readWays % WAYS_CHUNK); if (current == WAYS_CHUNK - 1) { int cores = Runtime.getRuntime().availableProcessors(); ExecutorService executorService = Executors.newFixedThreadPool(cores); for (Runnable currentRunnable : waysRunnables) { executorService.execute(currentRunnable); } waysRunnables = Collections.synchronizedList(new ArrayList<Runnable>()); executorService.shutdown(); while (!executorService.isTerminated()) { } saveEntry(waysQueue, COLL_WAYS); } }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java
@Test public void shouldAllowVariableReuseAcrossThreads() throws Exception { final ExecutorService service = Executors.newFixedThreadPool(8, testingThreadFactory); final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create(); final AtomicBoolean failed = new AtomicBoolean(false); final int max = 512; final List<Pair<Integer, List<Integer>>> futures = Collections.synchronizedList(new ArrayList<>(max)); IntStream.range(0, max).forEach(i -> { final int yValue = i * 2; final Bindings b = new SimpleBindings(); b.put("x", i); b.put("y", yValue); final int zValue = i * -1; final String script = "z=" + zValue + ";[x,y,z]"; try {//from ww w . j a v a 2s .c om service.submit(() -> { try { final List<Integer> result = (List<Integer>) gremlinExecutor.eval(script, b).get(); futures.add(Pair.with(i, result)); } catch (Exception ex) { failed.set(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); } }); service.shutdown(); assertThat(service.awaitTermination(60000, TimeUnit.MILLISECONDS), is(true)); // likely a concurrency exception if it occurs - and if it does then we've messed up because that's what this // test is partially designed to protected against. assertThat(failed.get(), is(false)); assertEquals(max, futures.size()); futures.forEach(t -> { assertEquals(t.getValue0(), t.getValue1().get(0)); assertEquals(t.getValue0() * 2, t.getValue1().get(1).intValue()); assertEquals(t.getValue0() * -1, t.getValue1().get(2).intValue()); }); }