List of usage examples for org.apache.commons.lang3 StringUtils defaultString
public static String defaultString(final String str)
Returns either the passed in String, or if the String is null , an empty String ("").
StringUtils.defaultString(null) = "" StringUtils.defaultString("") = "" StringUtils.defaultString("bat") = "bat"
From source file:ca.uhn.fhir.jpa.entity.ResourceIndexedSearchParamString.java
public void setValueNormalized(String theValueNormalized) { if (StringUtils.defaultString(theValueNormalized).length() > MAX_LENGTH) { throw new IllegalArgumentException("Value is too long: " + theValueNormalized.length()); }/*from ww w . j a v a 2 s.com*/ myValueNormalized = theValueNormalized; }
From source file:de.blizzy.documentr.web.access.UserController.java
@RequestMapping(value = "/save", method = RequestMethod.POST) @PreAuthorize("hasApplicationPermission(ADMIN)") public String saveUser(@ModelAttribute @Valid UserForm form, BindingResult bindingResult, Authentication authentication) throws IOException { User user = userStore.getUser(authentication.getName()); if (StringUtils.isNotBlank(form.getOriginalLoginName()) && !form.getOriginalLoginName().equals(UserStore.ANONYMOUS_USER_LOGIN_NAME) && StringUtils.equals(form.getLoginName(), UserStore.ANONYMOUS_USER_LOGIN_NAME)) { bindingResult.rejectValue("loginName", "user.loginName.invalid"); //$NON-NLS-1$ //$NON-NLS-2$ return "/user/edit"; //$NON-NLS-1$ }// w w w. j av a2 s . c o m if (!form.getLoginName().equals(UserStore.ANONYMOUS_USER_LOGIN_NAME)) { if (StringUtils.isNotBlank(form.getLoginName()) && (StringUtils.isBlank(form.getOriginalLoginName()) || !form.getLoginName().equals(form.getOriginalLoginName()))) { try { if (userStore.getUser(form.getLoginName()) != null) { bindingResult.rejectValue("loginName", "user.loginName.exists"); //$NON-NLS-1$ //$NON-NLS-2$ } } catch (UserNotFoundException e) { // okay } } if (StringUtils.isBlank(form.getOriginalLoginName()) && StringUtils.isBlank(form.getPassword1())) { bindingResult.rejectValue("password1", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$ } if (StringUtils.isBlank(form.getOriginalLoginName()) && StringUtils.isBlank(form.getPassword2())) { bindingResult.rejectValue("password2", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$ } if (StringUtils.isBlank(form.getPassword1()) && StringUtils.isNotBlank(form.getPassword2())) { bindingResult.rejectValue("password1", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$ } if (StringUtils.isNotBlank(form.getPassword1()) && StringUtils.isBlank(form.getPassword2())) { bindingResult.rejectValue("password2", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$ } if (StringUtils.isNotBlank(form.getPassword1()) && StringUtils.isNotBlank(form.getPassword2()) && !StringUtils.equals(form.getPassword1(), form.getPassword2())) { bindingResult.rejectValue("password1", "user.password.passwordsNotEqual"); //$NON-NLS-1$ //$NON-NLS-2$ bindingResult.rejectValue("password2", "user.password.passwordsNotEqual"); //$NON-NLS-1$ //$NON-NLS-2$ } if (bindingResult.hasErrors()) { return "/user/edit"; //$NON-NLS-1$ } User existingUser = null; String password = null; if (StringUtils.isNotBlank(form.getOriginalLoginName())) { try { existingUser = userStore.getUser(form.getOriginalLoginName()); password = existingUser.getPassword(); } catch (UserNotFoundException e) { // okay } } if (StringUtils.isNotBlank(form.getPassword1())) { password = passwordEncoder.encodePassword(form.getPassword1(), form.getLoginName()); } if (StringUtils.isBlank(password)) { bindingResult.rejectValue("password1", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$ bindingResult.rejectValue("password2", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$ } if (bindingResult.hasErrors()) { return "/user/edit"; //$NON-NLS-1$ } String newUserName = form.getOriginalLoginName(); if (StringUtils.isBlank(newUserName)) { newUserName = form.getLoginName(); } User newUser = new User(newUserName, password, form.getEmail(), form.isDisabled()); if (existingUser != null) { for (OpenId openId : existingUser.getOpenIds()) { newUser.addOpenId(openId); } } userStore.saveUser(newUser, user); if (StringUtils.isNotBlank(form.getOriginalLoginName()) && !StringUtils.equals(form.getLoginName(), form.getOriginalLoginName())) { userStore.renameUser(form.getOriginalLoginName(), form.getLoginName(), user); } } String[] authorityStrs = StringUtils.defaultString(form.getAuthorities()).split("\\|"); //$NON-NLS-1$ Set<RoleGrantedAuthority> authorities = Sets.newHashSet(); for (String authorityStr : authorityStrs) { if (StringUtils.isNotBlank(authorityStr)) { String[] parts = authorityStr.split(":"); //$NON-NLS-1$ Assert.isTrue(parts.length == 3); Type type = Type.valueOf(parts[0]); String targetId = parts[1]; String roleName = parts[2]; authorities.add(new RoleGrantedAuthority(new GrantedAuthorityTarget(targetId, type), roleName)); } } userStore.saveUserAuthorities(form.getLoginName(), authorities, user); return "redirect:/users"; //$NON-NLS-1$ }
From source file:com.netsteadfast.greenstep.support.ExpressionJobExecuteCallable.java
private void sendMail() { try {/*from w w w . j av a 2 s .com*/ if (ExpressionJobConstants.CONTACT_MODE_NO.equals(this.jobObj.getSysExprJob().getContactMode())) { return; } if (ExpressionJobConstants.CONTACT_MODE_ONLY_FAULT.equals(this.jobObj.getSysExprJob().getContactMode()) && !ExpressionJobConstants.RUNSTATUS_FAULT.equals(this.jobObj.getSysExprJob().getRunStatus())) { return; } if (ExpressionJobConstants.CONTACT_MODE_ONLY_SUCCESS .equals(this.jobObj.getSysExprJob().getContactMode()) && !ExpressionJobConstants.RUNSTATUS_SUCCESS .equals(this.jobObj.getSysExprJob().getRunStatus())) { return; } String contact = StringUtils.defaultString(this.jobObj.getSysExprJob().getContact()).trim(); if (StringUtils.isBlank(contact)) { return; } String subject = this.jobObj.getSysExprJob().getId() + " - " + this.jobObj.getSysExprJob().getName(); String content = subject + Constants.HTML_BR; content += "Run status: " + this.jobObj.getSysExprJob().getRunStatus() + Constants.HTML_BR; content += "Start: " + this.jobObj.getSysExprJobLog().getBeginDatetime().toString() + Constants.HTML_BR; content += "End: " + this.jobObj.getSysExprJobLog().getEndDatetime().toString() + Constants.HTML_BR; if (ExpressionJobConstants.RUNSTATUS_FAULT.equals(this.jobObj.getSysExprJob().getRunStatus())) { content += Constants.HTML_BR; content += "Fault: " + Constants.HTML_BR; content += this.jobObj.getSysExprJobLog().getFaultMsg(); } @SuppressWarnings("unchecked") ISysMailHelperService<SysMailHelperVO, TbSysMailHelper, String> sysMailHelperService = (ISysMailHelperService<SysMailHelperVO, TbSysMailHelper, String>) AppContext .getBean("core.service.SysMailHelperService"); String mailId = SimpleUtils.getStrYMD(""); SysMailHelperVO mailHelper = new SysMailHelperVO(); mailHelper.setMailId(sysMailHelperService.findForMaxMailIdComplete(mailId)); mailHelper.setMailFrom(MailClientUtils.getDefaultFrom()); mailHelper.setMailTo(contact); mailHelper.setSubject(subject); mailHelper.setText(content.getBytes("utf8")); mailHelper.setRetainFlag(YesNo.NO); mailHelper.setSuccessFlag(YesNo.NO); sysMailHelperService.saveObject(mailHelper); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.netsteadfast.greenstep.bsc.mobile.action.ScorecardQueryContentAction.java
private void checkDateRange() throws ControllerException, Exception { String date1 = ""; String date2 = ""; String ver = super.defaultString(this.getFields().get("ver")); if (!"newVer".equals(ver)) { // mm/dd/yyyy to yyyy/mm/dd String date1Tmp[] = super.defaultString(this.getFields().get("date1")).split("/"); String date2Tmp[] = super.defaultString(this.getFields().get("date2")).split("/"); if (date1Tmp == null || date1Tmp.length != 3 || date2Tmp == null || date2Tmp.length != 3) { throw new ControllerException(this.getText("MESSAGE.ScorecardQueryContentAction_01")); }//from w ww . j av a 2 s .com date1 = date1Tmp[2] + "/" + date1Tmp[0] + "/" + date1Tmp[1]; date2 = date2Tmp[2] + "/" + date2Tmp[0] + "/" + date2Tmp[1]; if (!SimpleUtils.isDate(date1) || !SimpleUtils.isDate(date2)) { throw new ControllerException(this.getText("MESSAGE.ScorecardQueryContentAction_01")); } } else { // NEW version page ? , yyyy/MM/dd date1 = StringUtils.defaultString(this.getFields().get("date1")).replaceAll("-", "/"); date2 = StringUtils.defaultString(this.getFields().get("date2")).replaceAll("-", "/"); if (!SimpleUtils.isDate(date1) || !SimpleUtils.isDate(date2)) { throw new ControllerException(this.getText("MESSAGE.ScorecardQueryContentAction_01")); } if (Integer.parseInt(date1.replaceAll("-", "").replaceAll("/", "")) > Integer .parseInt(date2.replaceAll("-", "").replaceAll("/", ""))) { throw new ControllerException("Date range: " + date1 + " to " + date2 + " error!"); } } this.getFields().put("startDate", date1); this.getFields().put("endDate", date2); // copy from KpiReportContentQueryAction.java String frequency = this.getFields().get("frequency"); String startDate = this.defaultString(this.getFields().get("startDate")).replaceAll("/", "-"); String endDate = this.defaultString(this.getFields().get("endDate")).replaceAll("/", "-"); if (BscMeasureDataFrequency.FREQUENCY_DAY.equals(frequency) || BscMeasureDataFrequency.FREQUENCY_WEEK.equals(frequency) || BscMeasureDataFrequency.FREQUENCY_MONTH.equals(frequency)) { DateTime dt1 = new DateTime(startDate); DateTime dt2 = new DateTime(endDate); int betweenMonths = Months.monthsBetween(dt1, dt2).getMonths(); if (betweenMonths >= 12) { throw new ControllerException(this.getText("MESSAGE.ScorecardQueryContentAction_02")); } return; } DateTime dt1 = new DateTime(startDate.substring(0, 4) + "-01-01"); DateTime dt2 = new DateTime(endDate.substring(0, 4) + "-01-01"); int betweenYears = Years.yearsBetween(dt1, dt2).getYears(); if (BscMeasureDataFrequency.FREQUENCY_QUARTER.equals(frequency)) { if (betweenYears >= 3) { throw new ControllerException(this.getText("MESSAGE.ScorecardQueryContentAction_03")); } } if (BscMeasureDataFrequency.FREQUENCY_HALF_OF_YEAR.equals(frequency)) { if (betweenYears >= 4) { throw new ControllerException(this.getText("MESSAGE.ScorecardQueryContentAction_04")); } } if (BscMeasureDataFrequency.FREQUENCY_YEAR.equals(frequency)) { if (betweenYears >= 6) { throw new ControllerException(this.getText("MESSAGE.ScorecardQueryContentAction_05")); } } }
From source file:io.wcm.handler.commons.dom.AbstractElement.java
/** * Sets the content of the element to be the text given. All existing text content and non-text context is removed. * If this element should have both textual content and nested elements, use <code>{@link #setContent}</code> instead. * Setting a null text value is equivalent to setting an empty string value. * @param text new text content for the element * @return the target element/* w ww. ja v a 2s .c o m*/ * @throws org.jdom2.IllegalDataException if the assigned text contains an illegal character such as a * vertical tab (as determined by {@link org.jdom2.Verifier#checkCharacterData}) */ @Override public org.jdom2.Element setText(String text) { return super.setText(cleanUpString(StringUtils.defaultString(text))); }
From source file:eionet.webq.service.CDREnvelopeServiceImpl.java
/** * Prepares parameters for saveXml remote method. * * @param file file to be saved.// w w w. j a va 2 s. com * @return http entity representing request */ HttpEntity<MultiValueMap<String, Object>> prepareXmlSaveRequestParameters(UserFile file) { HttpHeaders authorization = getAuthorizationHeader(file); HttpHeaders fileHeaders = new HttpHeaders(); fileHeaders.setContentDispositionFormData("file", file.getName()); fileHeaders.setContentType(MediaType.TEXT_XML); MultiValueMap<String, Object> request = new LinkedMultiValueMap<String, Object>(); byte[] content = file.getContent(); if (StringUtils.isNotEmpty(file.getConversionId())) { content = conversionService.convert(file, file.getConversionId()).getBody(); } request.add("file", new HttpEntity<byte[]>(content, fileHeaders)); request.add("file_id", new HttpEntity<String>(file.getName())); request.add("title", new HttpEntity<String>(StringUtils.defaultString(file.getTitle()))); if (file.isApplyRestriction()) { request.add("applyRestriction", new HttpEntity<String>("1")); request.add("restricted", new HttpEntity<String>(file.isRestricted() ? "1" : "0")); } return new HttpEntity<MultiValueMap<String, Object>>(request, authorization); }
From source file:de.blizzy.backup.settings.SettingsDialog.java
@Override protected Control createDialogArea(Composite parent) { Settings settings = BackupApplication.getSettingsManager().getSettings(); Composite composite = (Composite) super.createDialogArea(parent); ((GridLayout) composite.getLayout()).numColumns = 1; ((GridLayout) composite.getLayout()).verticalSpacing = 10; Group foldersComposite = new Group(composite, SWT.NONE); foldersComposite.setText(Messages.Title_FoldersToBackup); foldersComposite.setLayout(new GridLayout(2, false)); foldersComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); foldersViewer = new ListViewer(foldersComposite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); foldersViewer.setContentProvider(new ArrayContentProvider()); foldersViewer.setLabelProvider(new FoldersLabelProvider()); foldersViewer.setSorter(new ViewerSorter() { @Override//from www . j a va 2s . c o m public int compare(Viewer viewer, Object e1, Object e2) { return ((ILocation) e1).getDisplayName().compareToIgnoreCase(((ILocation) e2).getDisplayName()); } }); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); gd.widthHint = convertWidthInCharsToPixels(60); gd.heightHint = convertHeightInCharsToPixels(10); foldersViewer.getControl().setLayoutData(gd); foldersViewer.setInput(new HashSet<>(settings.getLocations())); Composite folderButtonsComposite = new Composite(foldersComposite, SWT.NONE); GridLayout layout = new GridLayout(1, false); layout.marginWidth = 0; layout.marginHeight = 0; folderButtonsComposite.setLayout(layout); folderButtonsComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); for (final LocationProviderDescriptor descriptor : BackupPlugin.getDefault().getLocationProviders()) { Button button = new Button(folderButtonsComposite, SWT.PUSH); button.setText(NLS.bind(Messages.Button_AddX, descriptor.getName())); button.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { addFolder(descriptor.getLocationProvider()); } }); } final Button removeFolderButton = new Button(folderButtonsComposite, SWT.PUSH); removeFolderButton.setText(Messages.Button_Remove); removeFolderButton.setEnabled(false); removeFolderButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); Label label = new Label(foldersComposite, SWT.NONE); label.setText(Messages.DropFoldersHelp); gd = new GridData(SWT.LEFT, SWT.CENTER, false, false); gd.horizontalSpan = 2; label.setLayoutData(gd); Group outputFolderComposite = new Group(composite, SWT.NONE); outputFolderComposite.setText(Messages.Title_OutputFolder); outputFolderComposite.setLayout(new GridLayout(3, false)); outputFolderComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); label = new Label(outputFolderComposite, SWT.NONE); label.setText(Messages.Label_BackupOutputFolder + ":"); //$NON-NLS-1$ label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); outputFolderText = new Text(outputFolderComposite, SWT.BORDER | SWT.READ_ONLY); outputFolderText.setText(StringUtils.defaultString(settings.getOutputFolder())); outputFolderText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); Button browseOutputFolderButton = new Button(outputFolderComposite, SWT.PUSH); browseOutputFolderButton.setText(Messages.Button_Browse + "..."); //$NON-NLS-1$ browseOutputFolderButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false)); Group scheduleComposite = new Group(composite, SWT.NONE); scheduleComposite.setText(Messages.Title_WhenToBackup); scheduleComposite.setLayout(new GridLayout(2, false)); scheduleComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); runHourlyRadio = new Button(scheduleComposite, SWT.RADIO); runHourlyRadio.setText(Messages.Label_RunHourly); gd = new GridData(SWT.LEFT, SWT.CENTER, false, false); gd.horizontalSpan = 2; runHourlyRadio.setLayoutData(gd); final Button runDailyRadio = new Button(scheduleComposite, SWT.RADIO); runDailyRadio.setText(Messages.Label_RunDaily + ":"); //$NON-NLS-1$ runDailyRadio.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); dailyTime = new DateTime(scheduleComposite, SWT.TIME | SWT.SHORT); runHourlyRadio.setSelection(settings.isRunHourly()); runDailyRadio.setSelection(!settings.isRunHourly()); dailyTime.setHours(settings.getDailyHours()); dailyTime.setMinutes(settings.getDailyMinutes()); dailyTime.setEnabled(!settings.isRunHourly()); Group fileComparisonComposite = new Group(composite, SWT.NONE); fileComparisonComposite.setText(Messages.Title_FileComparison); fileComparisonComposite.setLayout(new GridLayout(1, false)); fileComparisonComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); fileCompareMetadataRadio = new Button(fileComparisonComposite, SWT.RADIO); fileCompareMetadataRadio.setText(Messages.CompareFilesMetadata); fileCompareMetadataRadio.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); fileCompareChecksumRadio = new Button(fileComparisonComposite, SWT.RADIO); fileCompareChecksumRadio.setText(Messages.CompareFilesChecksum); fileCompareChecksumRadio.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); fileCompareMetadataRadio.setSelection(!settings.isUseChecksums()); fileCompareChecksumRadio.setSelection(settings.isUseChecksums()); Group maxAgeComposite = new Group(composite, SWT.NONE); maxAgeComposite.setText(Messages.Title_MaximumBackupAge); maxAgeComposite.setLayout(new GridLayout(2, false)); maxAgeComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); Button maxAgeUnlimitedRadio = new Button(maxAgeComposite, SWT.RADIO); maxAgeUnlimitedRadio.setText(Messages.Label_KeepAll); gd = new GridData(SWT.LEFT, SWT.CENTER, false, false); gd.horizontalSpan = 2; maxAgeUnlimitedRadio.setLayoutData(gd); maxAgeDaysRadio = new Button(maxAgeComposite, SWT.RADIO); maxAgeDaysRadio.setText(Messages.Label_DeleteAfterDays + ":"); //$NON-NLS-1$ maxAgeDaysRadio.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); maxAgeDaysSpinner = new Spinner(maxAgeComposite, SWT.BORDER); maxAgeDaysSpinner.setMinimum(14); maxAgeDaysSpinner.setMaximum(365); maxAgeUnlimitedRadio.setSelection(settings.getMaxAgeDays() < 0); maxAgeDaysRadio.setSelection(settings.getMaxAgeDays() > 0); maxAgeDaysSpinner.setEnabled(settings.getMaxAgeDays() > 0); maxAgeDaysSpinner.setSelection(settings.getMaxAgeDays() > 0 ? settings.getMaxAgeDays() : 90); Group maxDiskFillRateComposite = new Group(composite, SWT.NONE); maxDiskFillRateComposite.setText(Messages.Title_MaximumDiskFillRate); maxDiskFillRateComposite.setLayout(new GridLayout(3, false)); maxDiskFillRateComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); label = new Label(maxDiskFillRateComposite, SWT.NONE); label.setText(Messages.Label_DiskFillRate + ":"); //$NON-NLS-1$ label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); maxDiskFillRateSpinner = new Spinner(maxDiskFillRateComposite, SWT.BORDER); maxDiskFillRateSpinner.setMinimum(5); maxDiskFillRateSpinner.setMaximum(95); maxDiskFillRateSpinner.setSelection(settings.getMaxDiskFillRate()); label = new Label(maxDiskFillRateComposite, SWT.NONE); label.setText("%"); //$NON-NLS-1$ label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); Group scheduleExplanationComposite = new Group(composite, SWT.NONE); scheduleExplanationComposite.setText(Messages.Title_ScheduleExplanation); scheduleExplanationComposite.setLayout(new GridLayout(1, false)); scheduleExplanationComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); scheduleExplanationLabel = new Label(scheduleExplanationComposite, SWT.NONE); scheduleExplanationLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); updateExplanationLabel(); foldersViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent e) { removeFolderButton.setEnabled(!e.getSelection().isEmpty()); } }); removeFolderButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { removeFolder(); } }); browseOutputFolderButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { browseOutputFolder(); } }); runDailyRadio.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { dailyTime.setEnabled(runDailyRadio.getSelection()); updateExplanationLabel(); } }); dailyTime.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { updateExplanationLabel(); } }); fileCompareChecksumRadio.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { showWarnings(fileCompareChecksumRadio); } }); maxAgeDaysRadio.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { maxAgeDaysSpinner.setEnabled(maxAgeDaysRadio.getSelection()); updateExplanationLabel(); } }); maxAgeDaysSpinner.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { maxAgeDaysSpinner.setEnabled(maxAgeDaysRadio.getSelection()); updateExplanationLabel(); } }); maxDiskFillRateSpinner.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { updateExplanationLabel(); } }); DropTarget dropTarget = new DropTarget(foldersViewer.getControl(), DND.DROP_LINK); dropTarget.setTransfer(new Transfer[] { FileTransfer.getInstance() }); dropTarget.addDropListener(new DropTargetListener() { @Override public void dragEnter(DropTargetEvent event) { if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) { event.detail = DND.DROP_LINK; event.feedback = DND.FEEDBACK_SCROLL; } else { event.detail = DND.DROP_NONE; } } @Override public void dragLeave(DropTargetEvent event) { } @Override public void dragOver(DropTargetEvent event) { if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) { event.detail = DND.DROP_LINK; event.feedback = DND.FEEDBACK_SCROLL; } else { event.detail = DND.DROP_NONE; } } @Override public void dropAccept(DropTargetEvent event) { if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) { event.detail = DND.DROP_LINK; event.feedback = DND.FEEDBACK_SCROLL; } else { event.detail = DND.DROP_NONE; } } @Override public void drop(DropTargetEvent event) { if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) { if (event.data != null) { for (String file : (String[]) event.data) { if (new File(file).isDirectory()) { addFolder( FileSystemLocationProvider.location(Utils.toCanonicalFile(new File(file)))); } } } else { event.detail = DND.DROP_NONE; } } else { event.detail = DND.DROP_NONE; } } @Override public void dragOperationChanged(DropTargetEvent event) { if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) { event.detail = DND.DROP_LINK; event.feedback = DND.FEEDBACK_SCROLL; } else { event.detail = DND.DROP_NONE; } } }); return composite; }
From source file:com.versatus.jwebshield.filter.SecurityFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Assume its HTTP HttpServletRequest httpReq = (HttpServletRequest) request; String reqInfo = "J-WebShield Alert: CSRF attack detected! request URL=" + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr(); logger.debug("doFilter: IP address=" + httpReq.getRemoteAddr()); logger.debug("doFilter: pathInfo=" + httpReq.getPathInfo()); logger.debug("doFilter: queryString=" + httpReq.getQueryString()); logger.debug("doFilter: requestURL=" + httpReq.getRequestURL().toString()); logger.debug("doFilter: method=" + httpReq.getMethod()); logger.debug("doFilter: Origin=" + httpReq.getHeader("Origin")); logger.info("doFilter: Referer=" + httpReq.getHeader("Referer")); logger.info("doFilter: " + csrfHeaderName + "=" + httpReq.getHeader(csrfHeaderName)); UrlExclusionList exclList = (UrlExclusionList) request.getServletContext() .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME); HttpSession session = httpReq.getSession(false); if (session == null) { chain.doFilter(request, response); return;//from w w w . ja va2 s . com } logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list " + exclList.getExclusionMap()); try { if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) { chain.doFilter(request, response); return; } } catch (Exception e) { logger.error("doFilter", e); } // check CSRF cookie/header boolean csrfHeaderPassed = false; String rawCsrfHeaderVal = httpReq.getHeader(csrfHeaderName); if (useCsrfToken && StringUtils.isNotBlank(rawCsrfHeaderVal)) { String csrfHeader = StringUtils.strip(httpReq.getHeader(csrfHeaderName), "\""); logger.debug("doFilter: csrfHeader after decoding" + csrfHeader); Cookie[] cookies = httpReq.getCookies(); for (Cookie c : cookies) { String name = c.getName(); if (StringUtils.isNotBlank(csrfCookieName) && csrfCookieName.equals(name)) { logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value=" + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly=" + c.isHttpOnly()); logger.debug("doFilter: string comp:" + StringUtils.difference(csrfHeader, c.getValue())); if (StringUtils.isNotBlank(csrfHeader) && csrfHeader.equals(c.getValue())) { csrfHeaderPassed = true; logger.info("Header " + csrfHeaderName + " value matches the cookie " + csrfCookieName); break; } else { logger.info( "Header " + csrfHeaderName + " value does not match the cookie " + csrfCookieName); } } } // String csrfCookieVal = (String) session // .getAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM); // if (csrfCookieVal != null && csrfCookieVal.equals(csrfHeader)) { // // chain.doFilter(request, response); // // return; // csrfHeaderPassed = true; // } else { // // logger.info(reqInfo); // // sendSecurityReject(response); // } } if (useCsrfToken && csrfHeaderPassed) { chain.doFilter(request, response); return; } // Validate that the salt is in the cache Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME); if (csrfPreventionSaltCache != null) { // Get the salt sent with the request String saltName = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME); logger.debug("doFilter: csrf saltName=" + saltName); if (saltName != null) { String salt = httpReq.getParameter(saltName); logger.debug("doFilter: csrf salt=" + salt); if (salt != null) { SecurityInfo si = new SecurityInfo(saltName, salt); logger.debug("doFilter: csrf token=" + csrfPreventionSaltCache.getIfPresent(si)); SecurityInfo cachedSi = csrfPreventionSaltCache.getIfPresent(si); if (cachedSi != null) { // csrfPreventionSaltCache.invalidate(si); if (SecurityTokenFilter.checkReferer) { String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer")); logger.debug("doFilter: refHeader=" + refHeader); if (StringUtils.isNotBlank(refHeader)) { try { URL refUrl = new URL(refHeader); refHeader = refUrl.getHost(); } catch (MalformedURLException mex) { logger.debug("doFilter: parsing referer header failed", mex); } } if (!cachedSi.getRefererHost().isEmpty() && !refHeader.equalsIgnoreCase(cachedSi.getRefererHost())) { logger.info("Potential CSRF detected - Referer host does not match orignal! " + refHeader + " != " + cachedSi.getRefererHost()); sendSecurityReject(response); } } chain.doFilter(request, response); } else { logger.info(reqInfo); sendSecurityReject(response); } } else if (httpMethodMatch(httpReq.getMethod())) { // let flow through chain.doFilter(request, response); } else { logger.info(reqInfo); sendSecurityReject(response); } } } else { chain.doFilter(request, response); } }
From source file:com.sonicle.webtop.core.util.NotificationHelper.java
/** * Builds notification template.//from www .j a va2 s.c om * This uses the default body that specifies a simple message. */ public static String buildDefaultBodyTpl(Locale locale, String source, String recipientEmail, String bodyHeader, String bodyMessage, String becauseString) throws IOException, TemplateException { MapItem notMap = new MapItem(); notMap.putAll(createDefaultBodyTplStrings(locale, source, recipientEmail, bodyHeader, bodyMessage, becauseString)); MapItem map = new MapItem(); map.put("recipientEmail", StringUtils.defaultString(recipientEmail)); return builTpl(notMap, map); }
From source file:io.github.robwin.swagger2markup.builder.document.DefinitionsDocument.java
private String propertyDescription(String definitionName, String propertyName, Property property) throws IOException { String description;//w w w .java2s .c om if (handWrittenDescriptionsEnabled) { description = handWrittenPathDescription( definitionName.toLowerCase() + "/" + propertyName.toLowerCase(), DESCRIPTION_FILE_NAME); if (StringUtils.isBlank(description)) { if (logger.isInfoEnabled()) { logger.info( "Hand-written description file cannot be read. Trying to use description from Swagger source."); } description = StringUtils.defaultString(property.getDescription()); } } else { description = StringUtils.defaultString(property.getDescription()); } return description; }