_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q169900 | MethodRegistry.addMethod | validation | public static String addMethod(Method m) {
if (methods == null) {
methods = new HashMap<String, Method>();
}
String hashCode = String.valueOf(m.hashCode());
if (!methods.containsKey(hashCode)) {
methods.put(hashCode, m);
}
return String.valueOf(m.hashCode());
} | java | {
"resource": ""
} |
q169901 | FilterProxy.doFilter | validation | public int doFilter(Workspace ws, DataBinder binder, ExecutionContext ctx) throws DataException, ServiceException {
Object returnVal = null;
try {
String methodID = (String) ctx.getCachedObject("filterParameter");
Method m = MethodRegistry.getMethod(methodID);
ParameterMarshaller marshaller = new ParameterMarshaller(m);
Object[] params = marshaller.getValueArray(ws, binder, ctx);
Object context = m.getDeclaringClass().newInstance();
returnVal = m.invoke(context, params);
} catch (IllegalArgumentException e) {
throw new DataException(e.getMessage(), e);
} catch (Exception e) {
throw new ServiceException(e.getMessage(), e);
}
if (returnVal != null && returnVal instanceof Integer) {
return ((Integer) returnVal).intValue();
}
return CONTINUE;
} | java | {
"resource": ""
} |
q169902 | DbCreator.reduceDatabaseConnection | validation | public void reduceDatabaseConnection() {
synchronized (LOCK) {
int numberOfOpenConnections = OPEN_CONNECTIONS.decrementAndGet();
if (numberOfOpenConnections == 0 && dbConnection != null) {
dbConnection.close();
dbConnection = null;
}
}
} | java | {
"resource": ""
} |
q169903 | DbCreator.consumeDatabase | validation | public void consumeDatabase(DbConsumer dbConsumer) {
SQLiteDatabase db = getDatabaseConnection();
try {
dbConsumer.consume(db);
} finally {
reduceDatabaseConnection();
}
} | java | {
"resource": ""
} |
q169904 | DbCreator.query | validation | public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) {
SQLiteDatabase db = getDatabaseConnection();
return new DbClosingCursor(db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy), this);
} | java | {
"resource": ""
} |
q169905 | DbCreator.rawQuery | validation | public Cursor rawQuery(String sql) {
SQLiteDatabase db = getDatabaseConnection();
return new DbClosingCursor(db.rawQuery(sql, null), this);
} | java | {
"resource": ""
} |
q169906 | CliGitRm.buildCommandLine | validation | private List<String> buildCommandLine(GitRmOptions options, File path, List<File> paths) {
List<String> cmdline = new ArrayList<String>();
cmdline.add(JavaGitConfiguration.getGitCommand());
cmdline.add("rm");
if (null != options) {
if (options.isOptCached()) {
cmdline.add("--cached");
}
if (options.isOptF()) {
cmdline.add("-f");
}
if (options.isOptN()) {
cmdline.add("-n");
}
if (options.isOptQ()) {
cmdline.add("-q");
}
if (options.isOptR()) {
cmdline.add("-r");
}
}
if (null != path) {
cmdline.add(path.getPath());
} else {
for (File f : paths) {
cmdline.add(f.getPath());
}
}
return cmdline;
} | java | {
"resource": ""
} |
q169907 | GitCheckoutResponse.getAddedFile | validation | public File getAddedFile(int index) {
CheckUtilities.checkIntIndexInListRange(addedFiles, index);
return addedFiles.get(index);
} | java | {
"resource": ""
} |
q169908 | GitCheckoutResponse.getDeletedFile | validation | public File getDeletedFile(int index) {
CheckUtilities.checkIntIndexInListRange(deletedFiles, index);
return deletedFiles.get(index);
} | java | {
"resource": ""
} |
q169909 | GitCheckoutResponse.getModifiedFile | validation | public File getModifiedFile(int index) {
CheckUtilities.checkIntIndexInListRange(modifiedFiles, index);
return modifiedFiles.get(index);
} | java | {
"resource": ""
} |
q169910 | GitFile.getStatus | validation | public Status getStatus() throws IOException, JavaGitException {
GitStatus gitStatus = new GitStatus();
// run git-status command
return gitStatus.getFileStatus(workingTree.getPath(), relativePath);
} | java | {
"resource": ""
} |
q169911 | AbstractInjector.getHead | validation | protected static HeadElement getHead() {
if (head == null) {
final Element element = Document.get().getElementsByTagName("head").getItem(0);
assert element != null : "HTML Head element required";
final HeadElement head = HeadElement.as(element);
AbstractInjector.head = head;
}
return AbstractInjector.head;
} | java | {
"resource": ""
} |
q169912 | Dropzone.getFiles | validation | public ArrayList<File> getFiles() {
//TODO Why ArrayList, change to list when in a proper IDE
final JsArray<FileJS> filesJS = getFilesNative(getElement());
final ArrayList<File> files = new ArrayList<File>();
if (filesJS != null) {
for (int i = 0; i < filesJS.length(); i++) {
files.add(filesJS.get(i));
}
}
return files;
} | java | {
"resource": ""
} |
q169913 | Dropzone.getFilesCount | validation | public int getFilesCount() {
final JsArray<FileJS> files = getFilesNative(getElement());
return files != null ? files.length() : 0;
} | java | {
"resource": ""
} |
q169914 | Glob.matches | validation | public boolean matches(String string) {
String src = string;
final boolean result;
if (_compiledPattern.length == 1) {
// Shortcut for pattern '*', '?' and patterns not containing any wildcard
final GlobPattern pattern = _compiledPattern[0];
if (pattern.getType() == GLOB_MULTIPLE) {
result = true;
} else if (pattern.getType() == GLOB_SINGLE) {
result = src.length() == 1;
} else {
if (_caseInSensitive) {
result = src.equalsIgnoreCase(pattern.getText());
} else {
result = src.equals(pattern.getText());
}
}
} else if (_compiledPattern.length == 2) {
// Shortcuts for common patterns '*something' and 'something*'
final GlobPattern pattern1 = _compiledPattern[0];
final GlobPattern pattern2 = _compiledPattern[1];
if (_caseInSensitive) {
src = src.toLowerCase();
}
if (pattern1.getType() == TEXT) {
result = src.startsWith(pattern1.getText()) && (pattern2.getType() == GLOB_MULTIPLE || src.length() == pattern1.getTextLength()+1);
} else {
result = src.endsWith(pattern2.getText()) && (pattern1.getType() == GLOB_MULTIPLE || src.length() == pattern2.getTextLength()+1);
}
} else {
result = matches(src.toCharArray());
}
return result;
} | java | {
"resource": ""
} |
q169915 | LruCache.updateListAfterHit | validation | @Override
protected void updateListAfterHit(CacheEntry<K, V> entry) {
if (entry != null && !entry.equals(_first)) {
if (entry.equals(_last)) {
setLast(entry.getPrevious());
} else {
final CacheEntry<K, V> previous = entry.getPrevious();
final CacheEntry<K, V> next = entry.getNext();
previous.setNext(next);
next.setPrevious(previous);
}
_first.setPrevious(entry);
entry.setNext(_first);
setFirst(entry);
}
} | java | {
"resource": ""
} |
q169916 | InMemoryBasedCacheSupport.removeLast | validation | protected void removeLast() {
final CacheEntry<K, V> entry;
synchronized (_lock) {
if (_last != null) {
entry = _entries.remove(_last.getKey());
setLast(_last.getPrevious());
} else {
entry = null;
}
if (size() == 0) {
_first = null;
_last = null;
}
}
if (entry != null) {
handleRemove(entry);
}
} | java | {
"resource": ""
} |
q169917 | InMemoryBasedCacheSupport.cleanUpLifetimeExpired | validation | @SuppressWarnings("UnnecessaryUnboxing")
public void cleanUpLifetimeExpired() {
final long currentTime = currentTimeMillis();
// Test whether there could be an element that has to be removed
if (_nearstExpiringTime > 0 && _nearstExpiringTime <= currentTime) {
// Go through all elements and remove elements that are outdated
final List<K> keysToRemove = new ArrayList<>();
synchronized (_lock) {
_nearstExpiringTime = 0;
for (final CacheEntry<K, V> cacheEntry : _entries.values()) {
final Long expire = cacheEntry.getExpire();
if (expire != null) {
final long unboxedExpire = expire.longValue();
if (unboxedExpire <= currentTime) {
keysToRemove.add(cacheEntry.getKey());
} else if (_nearstExpiringTime == 0 || unboxedExpire < _nearstExpiringTime) {
_nearstExpiringTime = unboxedExpire;
}
}
}
for (final K key : keysToRemove) {
removeInternal(key);
}
}
}
} | java | {
"resource": ""
} |
q169918 | LfuCache.updateListAfterHit | validation | @Override
protected void updateListAfterHit(CacheEntry<K, V> entry) {
if (entry != null && !entry.equals(_first)) {
if (entry.getHits() > entry.getPrevious().getHits()) {
// Swap the positions
final CacheEntry<K, V> beforePrevious = entry.getPrevious().getPrevious();
final CacheEntry<K, V> previous = entry.getPrevious();
final CacheEntry<K, V> next = entry.getNext();
if (beforePrevious != null) {
beforePrevious.setNext(entry);
} else {
_first = entry;
}
entry.setPrevious(beforePrevious);
previous.setPrevious(entry);
previous.setNext(next);
entry.setNext(previous);
if (next == null) {
setLast(previous);
} else {
next.setPrevious(previous);
}
}
}
} | java | {
"resource": ""
} |
q169919 | StringUtils.startsWith | validation | public static boolean startsWith(char[] src, char[] find, int startAt) {
int startPos = startAt;
boolean result = true;
// Check ranges
if (src.length < startPos + find.length) {
result = false;
} else {
final int max = find.length;
for (int a = 0; a < max && result; a++) {
if (src[startPos] != find[a]) {
result = false;
}
startPos++;
}
}
return result;
} | java | {
"resource": ""
} |
q169920 | GlobusOAuth20ServiceImpl.getAccessToken | validation | @Override
public Token getAccessToken(Token requestToken, Verifier verifier) {
OAuthRequest request
= new ProxyOAuthRequest(this.api.getAccessTokenVerb(),
this.api.getAccessTokenEndpoint(), this.proxyHost, this.proxyPort);
String userpass = this.config.getApiKey() + ":" + this.config.getApiSecret();
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
request.addHeader("Authorization", basicAuth);
request.addBodyParameter("grant_type", "authorization_code");
request.addBodyParameter("code", verifier.getValue());
request.addBodyParameter("redirect_uri", config.getCallback());
Response response = request.send();
String body = response.getBody();
JsonNode json = JsonHelper.getFirstNode(body);
if (json != null) {
return new Token((String) JsonHelper.get(json, "access_token"), "", body);
} else {
return null;
}
} | java | {
"resource": ""
} |
q169921 | GlobusOAuth20ServiceImpl.signRequest | validation | @Override
public void signRequest(Token accessToken, OAuthRequest request) {
request.addHeader("Authorization", "Bearer " + accessToken.getToken());
} | java | {
"resource": ""
} |
q169922 | GlobusApi.getAuthorizationUrl | validation | @Override
public String getAuthorizationUrl(OAuthConfig config) {
Preconditions.checkValidUrl(config.getCallback(),
"Must provide a valid url as callback.");
return String.format(AUTHORIZE_URL, config.getApiKey(),
OAuthEncoder.encode(config.getCallback()), SCOPES);
} | java | {
"resource": ""
} |
q169923 | ProjectWizard.performFinish | validation | public boolean performFinish() {
final String containerName = getProjectName();
final IPath location = projectPage.useDefaults() ? null : projectPage.getLocationPath();
IRunnableWithProgress op = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
doFinish(containerName, location, monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
};
try {
getContainer().run(true, false, op);
} catch (InterruptedException e) {
return false;
} catch (InvocationTargetException e) {
Throwable realException = e.getTargetException();
MessageDialog.openError(getShell(), "Error", realException.getMessage());
return false;
}
return true;
} | java | {
"resource": ""
} |
q169924 | ProjectWizard.doFinish | validation | private void doFinish(String containerName, IPath location, IProgressMonitor monitor) throws CoreException {
// create a sample file
monitor.beginTask("Creating " + containerName, 2);
monitor.worked(1);
final Archetype archetype = new Archetype();
archetype.setGroupId("org.glassmaker");
archetype.setArtifactId("org.glassmaker.archetype.basic");
archetype.setVersion("0.0.1");
ProjectParameters params = parametersPage.getParams();
final String groupId = params.getGroupId();
final String artifactId = params.getArtifactId();
final String version = params.getVersion();
final String javaPackage = params.getPackageName();
final Properties properties = params.getProperties();
properties.setProperty("oauth2callbackurl", properties.getProperty(ProjectWizardParametersPage.O_AUTH_CALLBACK));
properties.setProperty("clientid", properties.getProperty(ProjectWizardParametersPage.CLIENT_ID));
properties.setProperty("clientsecret", properties.getProperty(ProjectWizardParametersPage.CLIENT_SECRET));
List<IProject> projects = MavenPlugin.getProjectConfigurationManager().createArchetypeProjects(location, archetype, groupId, artifactId, version, javaPackage, properties, importConfiguration, monitor);
} | java | {
"resource": ""
} |
q169925 | ProjectWizardParametersPage.createControl | validation | public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NULL);
composite.setLayout(new GridLayout(3, false));
createArtifactGroup(composite);
createPropertiesGroup(composite);
setArchetype() ;
validate();
setControl(composite);
} | java | {
"resource": ""
} |
q169926 | ProjectWizardParametersPage.getDefaultJavaPackage | validation | protected String getDefaultJavaPackage() {
return ProjectWizardParametersPage.getDefaultJavaPackage(groupIdCombo.getText().trim(), artifactIdCombo.getText().trim());
} | java | {
"resource": ""
} |
q169927 | ProjectWizardParametersPage.setVisible | validation | public void setVisible(boolean visible) {
super.setVisible(visible);
boolean shouldValidate = false;
if (visible) {
if (groupIdCombo.getText().length() == 0 && groupIdCombo.getItemCount() > 0) {
groupIdCombo.setText(groupIdCombo.getItem(0));
packageCombo.setText(getDefaultJavaPackage());
packageCustomized = false;
}
if (shouldValidate) {
validate();
}
}
} | java | {
"resource": ""
} |
q169928 | CriteriaQueryBuilder.createQueryDebugString | validation | public String createQueryDebugString() {
// create query
String queryString = createQueryString();
// create list of parameters
List<Object> parameterValues = getQueryParametersAsList();
// create debug string
return QueryLogHelper.createQueryLogMessage(queryString, parameterValues);
} | java | {
"resource": ""
} |
q169929 | CriteriaQueryBuilder.getQueryParametersAsList | validation | private List<Object> getQueryParametersAsList() {
// iterate over all restrictions of this criteria
Iterator<MetaEntry<Criterion>> iter = rootCriteria.getCriterionList().iterator();
// result list
List<Object> result = new ArrayList<Object>();
// loop over all criterion
while(iter.hasNext()) {
// the current criterion
Criterion criterion = iter.next().getEntry();
// get the values to set
Object[] parameterValues = criterion.getParameterValues();
// null should be ignores
if(parameterValues == null) {
continue;
}
// set all parameters
for(Object value : parameterValues) {
result.add( value );
}
}
return result;
} | java | {
"resource": ""
} |
q169930 | PaletteView.createPartControl | validation | public void createPartControl(Composite parent) {
viewer = new PaletteViewer();
viewer.createControl(parent);
PaletteRoot root = new PaletteRoot();
String[] category = getCategories();
for(int i=0;i<category.length;i++){
PaletteDrawer group = new PaletteDrawer(category[i]);
IPaletteItem[] items = getPaletteItems(category[i]);
for(int j=0;j<items.length;j++){
HTMLPaletteEntry entry = new HTMLPaletteEntry(items[j].getLabel(),null,items[j].getImageDescriptor());
tools.put(entry,items[j]);
group.add(entry);
}
root.add(group);
}
viewer.setPaletteRoot(root);
viewer.getControl().addMouseListener(new MouseAdapter(){
@Override
public void mouseDoubleClick(MouseEvent e) {
// IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
// IEditorPart editorPart = page.getActiveEditor();
// if(editorPart!=null){
// editorPart.setFocus();
// }
if (e.button == 1) {
EditPart part = PaletteView.this.viewer.findObjectAt(new Point(e.x, e.y));
IPaletteItem item = null;
if (part != null) {
if (part.getModel() instanceof HTMLPaletteEntry)
item = tools.get(part.getModel());
}
if (item != null)
insert(item);
}
}
});
} | java | {
"resource": ""
} |
q169931 | PaletteView.addPaletteItem | validation | private void addPaletteItem(String category,IPaletteItem item){
if(items.get(category)==null){
List<IPaletteItem> list = new ArrayList<IPaletteItem>();
items.put(category,list);
}
List<IPaletteItem> list = items.get(category);
list.add(item);
} | java | {
"resource": ""
} |
q169932 | PaletteView.getPaletteItems | validation | private IPaletteItem[] getPaletteItems(String category){
List<IPaletteItem> list = items.get(category);
if(list==null){
return new IPaletteItem[0];
}
return list.toArray(new IPaletteItem[list.size()]);
} | java | {
"resource": ""
} |
q169933 | NewCardTemplatesWizardPage.configureTableResizing | validation | private void configureTableResizing(final Composite parent, final Table table, final TableColumn column1, final TableColumn column2) {
parent.addControlListener(new ControlAdapter() {
public void controlResized(ControlEvent e) {
Rectangle area = parent.getClientArea();
Point preferredSize = table.computeSize(SWT.DEFAULT, SWT.DEFAULT);
int width = area.width - 2 * table.getBorderWidth();
if (preferredSize.y > area.height) {
// Subtract the scrollbar width from the total column
// width
// if a vertical scrollbar will be required
Point vBarSize = table.getVerticalBar().getSize();
width -= vBarSize.x;
}
Point oldSize = table.getSize();
if (oldSize.x > width) {
// table is getting smaller so make the columns
// smaller first and then resize the table to
// match the client area width
column1.setWidth(width / 2);
column2.setWidth(width / 2);
table.setSize(width, area.height);
}
else {
// table is getting bigger so make the table
// bigger first and then make the columns wider
// to match the client area width
table.setSize(width, area.height);
column1.setWidth(width / 2);
column2.setWidth(width / 2);
}
}
});
} | java | {
"resource": ""
} |
q169934 | NewCardTemplatesWizardPage.getSelectedTemplate | validation | private Template getSelectedTemplate() {
Template template = null;
IStructuredSelection selection = (IStructuredSelection) fTableViewer.getSelection();
if (selection.size() == 1) {
template = (Template) selection.getFirstElement();
}
return template;
} | java | {
"resource": ""
} |
q169935 | NewCardTemplatesWizardPage.getTemplateString | validation | String getTemplateString() {
String templateString = null;
Template template = getSelectedTemplate();
if (template != null) {
TemplateContextType contextType = GlassmakerUIPlugin.getDefault().getTemplateContextRegistry().getContextType(CardContextType.CONTEXT_TYPE);
IDocument document = new Document();
TemplateContext context = new DocumentTemplateContext(contextType, document, 0, 0);
try {
TemplateBuffer buffer = context.evaluate(template);
templateString = buffer.getString();
}
catch (Exception e) {
GlassmakerUIPlugin.logError("Could not create template for new html", e);
}
}
return templateString;
} | java | {
"resource": ""
} |
q169936 | NewCardTemplatesWizardPage.loadLastSavedPreferences | validation | private void loadLastSavedPreferences() {
fLastSelectedTemplateName = ""; //$NON-NLS-1$
boolean setSelection = false;
String templateName = GlassmakerUIPlugin.getDefault().getPreferenceStore().getString(HTMLUIPreferenceNames.NEW_FILE_TEMPLATE_NAME);
if (templateName == null || templateName.length() == 0) {
templateName = GlassmakerUIPlugin.getDefault().getPreferenceStore().getString(HTMLUIPreferenceNames.NEW_FILE_TEMPLATE_ID);
if (templateName != null && templateName.length() > 0) {
Template template = fTemplateStore.findTemplateById(templateName);
if (template != null) {
fLastSelectedTemplateName = template.getName();
setSelection = true;
}
}
}
else {
fLastSelectedTemplateName = templateName;
setSelection = true;
}
fUseTemplateButton.setSelection(setSelection);
enableTemplates();
} | java | {
"resource": ""
} |
q169937 | NewCardTemplatesWizardPage.saveLastSavedPreferences | validation | void saveLastSavedPreferences() {
String templateName = ""; //$NON-NLS-1$
Template template = getSelectedTemplate();
if (template != null) {
templateName = template.getName();
}
GlassmakerUIPlugin.getDefault().getPreferenceStore().setValue("newFileTemplateName", templateName);
GlassmakerUIPlugin.getDefault().savePluginPreferences();
} | java | {
"resource": ""
} |
q169938 | NewCardTemplatesWizardPage.setSelectedTemplate | validation | private void setSelectedTemplate(String templateName) {
Object template = null;
if (templateName != null && templateName.length() > 0) {
// pick the last used template
template = fTemplateStore.findTemplate(templateName, CardContextType.CONTEXT_TYPE);
}
// no record of last used template so just pick first element
if (template == null) {
// just pick first element
template = fTableViewer.getElementAt(0);
}
if (template != null) {
IStructuredSelection selection = new StructuredSelection(template);
fTableViewer.setSelection(selection, true);
}
} | java | {
"resource": ""
} |
q169939 | NewCardTemplatesWizardPage.updateViewerInput | validation | void updateViewerInput() {
Template template = getSelectedTemplate();
if (template != null) {
fPatternViewer.getDocument().set(template.getPattern());
String imageId = "org.glassmaker.ui.templates."+template.getName().replace(" ", "").toLowerCase();
ImageDescriptor desc = imageRegistry.getDescriptor(imageId);
if(desc != null){
fImage.setImage(desc.createImage());
}else{
fImage.setImage(null);
}
}
else {
fPatternViewer.getDocument().set(""); //$NON-NLS-1$
}
} | java | {
"resource": ""
} |
q169940 | Restrictions.in | validation | public static Criterion in(String relativePath, Collection<?> values) {
return new InExpression(relativePath, values.toArray());
} | java | {
"resource": ""
} |
q169941 | Restrictions.memberOf | validation | public static Criterion memberOf(String relativePath, Object value) {
return new MemberOfExpression(relativePath, value, false);
} | java | {
"resource": ""
} |
q169942 | Restrictions.notMemberOf | validation | public static Criterion notMemberOf(String relativePath, Object value) {
return new MemberOfExpression(relativePath, value, true);
} | java | {
"resource": ""
} |
q169943 | LoginPreferencePage.createFieldEditors | validation | public void createFieldEditors() {
addField(new StringFieldEditor(PreferenceConstants.CLIENT_ID, "Google API Client Id:", getFieldEditorParent()));
addField(new StringFieldEditor(PreferenceConstants.CLIENT_SECRET, "Google API Client Secret:", getFieldEditorParent()));
} | java | {
"resource": ""
} |
q169944 | StringUtils.getLastPathComponent | validation | public static String getLastPathComponent(String path) {
// find last '.' character
int pos = path.lastIndexOf('.');
// return the last path component
// or the complete path, if no '.' chars were found
return pos >= 0 ? path.substring(pos + 1) : path;
} | java | {
"resource": ""
} |
q169945 | NewCardFileWizardPage.initialPopulateContainerNameField | validation | protected void initialPopulateContainerNameField() {
super.initialPopulateContainerNameField();
IPath fullPath = getContainerFullPath();
IProject project = getProjectFromPath(fullPath);
IPath root = ProjectUtils.getRootContainerForPath(project, fullPath);
if (root != null) {
return;
}
root = ProjectUtils.getDefaultRootContainer(project);
if (root != null) {
setContainerFullPath(root);
return;
}
} | java | {
"resource": ""
} |
q169946 | NewCardFileWizardPage.validatePage | validation | protected boolean validatePage() {
setMessage(null);
setErrorMessage(null);
if (!super.validatePage()) {
return false;
}
String fileName = getFileName();
IPath fullPath = getContainerFullPath();
if ((fullPath != null) && (fullPath.isEmpty() == false) && (fileName != null)) {
// check that filename does not contain invalid extension
if (!extensionValidForContentType(fileName)) {
setErrorMessage("Filename must end with .card");
return false;
}
// no file extension specified so check adding default
// extension doesn't equal a file that already exists
if (fileName.lastIndexOf('.') == -1) {
String newFileName = addDefaultExtension(fileName);
IPath resourcePath = fullPath.append(newFileName);
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IStatus result = workspace.validatePath(resourcePath.toString(), IResource.FOLDER);
if (!result.isOK()) {
// path invalid
setErrorMessage(result.getMessage());
return false;
}
if ((workspace.getRoot().getFolder(resourcePath).exists() || workspace.getRoot().getFile(resourcePath).exists())) {
setErrorMessage("There is a card with that name");
return false;
}
}
// get the IProject for the selection path
IProject project = getProjectFromPath(fullPath);
// if inside web project, check if inside webContent folder
if (project != null && isWebProject(project)) {
// check that the path is inside the webContent folder
IPath[] webContentPaths = ProjectUtils.getAcceptableRootPaths(project);
boolean isPrefix = false;
for (int i = 0; !isPrefix && i < webContentPaths.length; i++) {
isPrefix |= webContentPaths[i].isPrefixOf(fullPath);
}
if (!isPrefix) {
setMessage("Cards must be inside the web contents", WARNING);
}
}
}
return true;
} | java | {
"resource": ""
} |
q169947 | NewCardFileWizardPage.extensionValidForContentType | validation | private boolean extensionValidForContentType(String fileName) {
boolean valid = false;
IContentType type = getContentType();
// there is currently an extension
if (fileName.lastIndexOf('.') != -1) {
// check what content types are associated with current extension
IContentType[] types = Platform.getContentTypeManager().findContentTypesFor(fileName);
int i = 0;
while (i < types.length && !valid) {
valid = types[i].isKindOf(type);
++i;
}
} else
valid = true; // no extension so valid
return valid;
} | java | {
"resource": ""
} |
q169948 | NewCardFileWizardPage.addDefaultExtension | validation | String addDefaultExtension(String filename) {
StringBuffer newFileName = new StringBuffer(filename);
String ext = "card";
newFileName.append("."); //$NON-NLS-1$
newFileName.append(ext);
return newFileName.toString();
} | java | {
"resource": ""
} |
q169949 | NewCardFileWizardPage.getProjectFromPath | validation | private IProject getProjectFromPath(IPath path) {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IProject project = null;
if (path != null) {
if (workspace.validatePath(path.toString(), IResource.PROJECT).isOK()) {
project = workspace.getRoot().getProject(path.toString());
} else {
project = workspace.getRoot().getFile(path).getProject();
}
}
return project;
} | java | {
"resource": ""
} |
q169950 | OAuth2Util.getUserId | validation | public String getUserId(HttpServletRequest request) {
HttpSession session = request.getSession();
return (String) session.getAttribute("userId");
} | java | {
"resource": ""
} |
q169951 | CardEditor.createPage0 | validation | void createPage0() {
try {
textEditor = new StructuredTextEditor();
int index = addPage(textEditor, getEditorInput());
setPageText(index, "Source");
setPartName(textEditor.getTitle());
} catch (PartInitException e) {
ErrorDialog.openError(getSite().getShell(), "Error creating nested text editor", null, e.getStatus());
}
} | java | {
"resource": ""
} |
q169952 | CardEditor.doSaveAs | validation | public void doSaveAs() {
IEditorPart editor = getEditor(0);
editor.doSaveAs();
setPageText(0, editor.getTitle());
setInput(editor.getEditorInput());
} | java | {
"resource": ""
} |
q169953 | CardEditor.resourceChanged | validation | public void resourceChanged(final IResourceChangeEvent event) {
if (event.getType() == IResourceChangeEvent.PRE_CLOSE) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
IWorkbenchPage[] pages = getSite().getWorkbenchWindow().getPages();
for (int i = 0; i < pages.length; i++) {
if (((FileEditorInput) textEditor.getEditorInput()).getFile().getProject().equals(event.getResource())) {
IEditorPart editorPart = pages[i].findEditor(textEditor.getEditorInput());
pages[i].closeEditor(editorPart, true);
}
}
}
});
}
} | java | {
"resource": ""
} |
q169954 | CardEditor.showPage | validation | void showPage() {
String editorText = getDocumentProvider().getDocument(textEditor.getEditorInput()).get();
deletePreviewFiles();
File file = toPreviewFile(editorText);
if (file != null) {
PREVIEW_FILES_LIST.add(file);
String s = "file://" + file.getAbsolutePath(); //$NON-NLS-1$
browser.setJavascriptEnabled(true);
browser.setUrl(s);
} else {
browser.setText(editorText, true);
}
} | java | {
"resource": ""
} |
q169955 | QueryLogHelper.createQueryLogMessage | validation | public static String createQueryLogMessage(String query, List<Object> parameterValues) {
// builder for log message
StringBuilder builder = new StringBuilder();
// log the JPQL query string
builder.append("Query: \"");
builder.append(query);
builder.append("\"");
// append parameter value list
if(parameterValues != null && parameterValues.size() > 0) {
builder.append(", parameters: { ");
// parameter value iterator
Iterator<Object> parameterIterator = parameterValues.iterator();
// iterate over all parameter values
while (parameterIterator.hasNext()) {
// use private helper to create string representation
builder.append( objectToString( parameterIterator.next() ) );
// append comma if more values follow
if( parameterIterator.hasNext() ) {
builder.append(", ");
}
}
// closing bracket
builder.append(" }");
}
// return result
return builder.toString();
} | java | {
"resource": ""
} |
q169956 | QueryLogHelper.objectToString | validation | private static String objectToString(Object obj) {
// handle 'null'
if(obj == null) {
return "null";
}
// enclose Strings in quotes
if(obj instanceof CharSequence) {
return "\""+obj.toString()+"\"";
}
// use toString() for all other objects
return obj.toString();
} | java | {
"resource": ""
} |
q169957 | MirrorTemplate.insertTimelineItem | validation | public TimelineItem insertTimelineItem(TimelineItem item) throws IOException {
return getMirror().timeline().insert(item).execute();
} | java | {
"resource": ""
} |
q169958 | MirrorTemplate.insertTimelineItem | validation | public void insertTimelineItem(TimelineItem item, String attachmentContentType, byte[] attachmentData) throws IOException {
Mirror.Timeline timeline = getMirror().timeline();
timeline.insert(item, new ByteArrayContent(attachmentContentType, attachmentData)).execute();
} | java | {
"resource": ""
} |
q169959 | MirrorTemplate.insertTimelineItem | validation | public void insertTimelineItem(TimelineItem item, String attachmentContentType, InputStream attachmentInputStream) throws IOException {
insertTimelineItem(item, attachmentContentType, ByteStreams.toByteArray(attachmentInputStream));
} | java | {
"resource": ""
} |
q169960 | DefaultIronCacheProvider.validate | validation | private void validate(final CacheResponse response, final String keyword) {
if (!response.getMessage().toLowerCase(Locale.US).startsWith(keyword)) {
throw new IllegalArgumentException(response.getMessage());
}
} | java | {
"resource": ""
} |
q169961 | Order.toQueryString | validation | public String toQueryString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {
String absolutePath = queryBuilder.getAbsolutePath(criteria, relativePath);
return ascending ? absolutePath : absolutePath+" DESC";
} | java | {
"resource": ""
} |
q169962 | GlassmakerUIPlugin.getTemplateStore | validation | public TemplateStore getTemplateStore() {
if (fTemplateStore == null) {
fTemplateStore = new ContributionTemplateStore(getTemplateContextRegistry(), getPreferenceStore(), "org.eclipse.wst.sse.ui.custom_templates");
try {
fTemplateStore.load();
} catch (IOException e) {
logError("",e);
}
}
return fTemplateStore;
} | java | {
"resource": ""
} |
q169963 | GlassmakerUIPlugin.getTemplateContextRegistry | validation | public ContextTypeRegistry getTemplateContextRegistry() {
if (fContextTypeRegistry == null) {
ContributionContextTypeRegistry registry = new ContributionContextTypeRegistry();
registry.addContextType(CardContextType.CONTEXT_TYPE);
fContextTypeRegistry = registry;
}
return fContextTypeRegistry;
} | java | {
"resource": ""
} |
q169964 | CardEditorContributor.getAction | validation | protected IAction getAction(ITextEditor editor, String actionID) {
return (editor == null ? null : editor.getAction(actionID));
} | java | {
"resource": ""
} |
q169965 | AbstractMigratoryMojo.createDBI | validation | private DBI createDBI() throws Exception
{
if (driver != null) {
Class.forName(driver).newInstance();
}
return new DBI(url, user, password);
} | java | {
"resource": ""
} |
q169966 | JDBCEntityDAOSupport.appendLimitAndOffSet | validation | protected void appendLimitAndOffSet(final StringBuilder sql, final Page page) {
sql.append(" LIMIT ").append(page.getPageSize()).append(" OFFSET ").append(page.getOffset());
} | java | {
"resource": ""
} |
q169967 | Datatree.NamedProperty | validation | public static <N> NamedProperty<N> NamedProperty(final N name, final PropertyValue<N> value) {
return new NamedProperty.Impl<>(name, value);
} | java | {
"resource": ""
} |
q169968 | Datatree.NamedProperty | validation | public static <N> NamedProperty<N> NamedProperty(final N name, final String value) {
return NamedProperty(name, Datatree.<N>Literal(value));
} | java | {
"resource": ""
} |
q169969 | Datatree.NamedProperty | validation | public static <N> NamedProperty<N> NamedProperty(final N name, final NestedDocument<N> value) {
return new NamedProperty.Impl<>(name, value);
} | java | {
"resource": ""
} |
q169970 | Datatree.Literal | validation | public static <N> Literal.StringLiteral<N> Literal(final String value) {
return new Literal.StringLiteral<>(value);
} | java | {
"resource": ""
} |
q169971 | Datatree.Literal | validation | public static <N> Literal.UriLiteral<N> Literal(final URI value) {
return new Literal.UriLiteral<>(value);
} | java | {
"resource": ""
} |
q169972 | Datatree.Literal | validation | public static <N> Literal.TypedLiteral<N> Literal(final String value, final QName type) {
return new Literal.TypedLiteral<>(value, type);
} | java | {
"resource": ""
} |
q169973 | Datatree.QName | validation | public static QName QName(String namespaceURI, String localPart, String prefix) {
return new QName(namespaceURI, localPart, prefix);
} | java | {
"resource": ""
} |
q169974 | CORSFilter.init | validation | public void init(final FilterConfig filterConfig)
throws ServletException {
// Get the init params
Properties props = getFilterInitParameters(filterConfig);
// Extract and parse all required CORS filter properties
try {
config = new CORSConfiguration(props);
} catch (CORSConfigurationException e) {
throw new ServletException(e);
}
handler = new CORSRequestHandler(config);
} | java | {
"resource": ""
} |
q169975 | DomainVersionedEntity.created | validation | public void created(final UUID createdByEntityId) {
if (this.entityId != null) {
throw new IllegalStateException("This entity has already been created: entityId = " + entityId);
}
this.entityId = UUID.randomUUID();
this.entityVersion = 1;
this.createdByEntityId = createdByEntityId;
this.updatedByEntityId = createdByEntityId;
this.entityCreatedOn = System.currentTimeMillis();
this.entityUpdatedOn = this.entityCreatedOn;
} | java | {
"resource": ""
} |
q169976 | DomainVersionedEntity.init | validation | protected void init(JsonParser parser) throws IOException {
LoggerFactory.getLogger(getClass()).warn("init(JsonParser parser) invoked to handle field: {}", parser.getCurrentName());
} | java | {
"resource": ""
} |
q169977 | DomainVersionedEntity.updated | validation | public void updated(final UUID lastupdatedByEntityId) {
if (this.entityId == null) {
throw new IllegalStateException("The entity has not yet been created : entityId == null");
}
Assert.notNull(lastupdatedByEntityId, "lastupdatedByEntityId is required");
entityVersion++;
updatedByEntityId = lastupdatedByEntityId;
entityUpdatedOn = System.currentTimeMillis();
} | java | {
"resource": ""
} |
q169978 | Server.close | validation | public void close( int port ) {
for (Iterator i = _listeners.keySet().iterator(); i.hasNext(); ) {
Object k = i.next();
Object s = _listeners.get(k);
if (s instanceof SocketHandler) {
SocketHandler sh = (SocketHandler)s;
if (port == -1 || sh.isPort( port )) {
sh.interrupt();
sh.close();
_transactions.remove( s );
_listeners.remove( k );
}
}
}
} | java | {
"resource": ""
} |
q169979 | Server.main | validation | public static final void main( String[] args ) {
if (args.length != 1) {
System.err.println("A single argument -- a port -- is required");
System.exit(1);
}
int port = Integer.valueOf( args[0] ).intValue();
System.out.println(Version.VERSION);
try {
new Server( port );
} catch (Exception e) {
System.err.println("Failed to start server");
e.printStackTrace( System.err );
}
} | java | {
"resource": ""
} |
q169980 | Validator.validateOpts | validation | public void validateOpts(Object instance) {
final Set<ConstraintViolation<Object>> set = validator.validate(instance);
final StringBuilder sb = new StringBuilder();
for (ConstraintViolation<Object> violation : set) {
final Path path = violation.getPropertyPath();
final String msg = violation.getMessage();
sb.append(path.toString()).append(" ").append(msg).append(". ");
}
if (sb.length() > 0) {
// is ConstraintViolationException more appropriate,
// letting user choose their error message?
throw new ValidationException(OPT_VIOLATION_MSG + ": " + sb.toString());
}
} | java | {
"resource": ""
} |
q169981 | Validator.validateArgs | validation | public void validateArgs(List<Object> args, Object instance, Method m, Command cmd) {
final Set<ConstraintViolation<Object>> set = validator.validateParameters(instance, m,
args.toArray());
final StringBuilder sb = new StringBuilder();
for (ConstraintViolation<Object> violation : set) {
final Path path = violation.getPropertyPath();
final String msg = violation.getMessage();
String var = path.toString();
try {
int pos = Integer.parseInt("" + var.charAt(var.length() - 1));
Argument arg = cmd.getArguments().get(pos);
sb.append(arg.getName()).append(" ").append(msg).append(". ");
} catch (Exception e) {
sb.append(var).append(" ").append(msg).append(". ");
}
}
if (sb.length() > 0) {
// is ConstraintViolationException more appropriate,
// letting user choose their error message?
throw new ValidationException(ARG_VIOLATION_MSG + ": " + sb.toString());
}
} | java | {
"resource": ""
} |
q169982 | Stomp.subscribe | validation | public void subscribe( String name, Listener listener, Map headers ) {
synchronized (_listeners) {
if (listener != null) {
List list = (List)_listeners.get( name );
if (list == null) {
list = new ArrayList();
_listeners.put( name, list );
}
if (!list.contains( listener )) list.add( listener );
}
}
if (headers == null) headers = new HashMap();
headers.put( "destination", name );
transmit( Command.SUBSCRIBE, headers );
} | java | {
"resource": ""
} |
q169983 | Stomp.unsubscribe | validation | public void unsubscribe( String name, Listener l ) {
synchronized (_listeners) {
List list = (List)_listeners.get( name );
if (list != null) {
list.remove( l );
if (list.size() == 0) {
unsubscribe( name );
}
}
}
} | java | {
"resource": ""
} |
q169984 | Stomp.unsubscribe | validation | public void unsubscribe( String name, Map header ) {
if (header == null) header = new HashMap();
synchronized( _listeners ) { _listeners.remove( name ); }
header.put( "destination", name );
transmit( Command.UNSUBSCRIBE, header );
} | java | {
"resource": ""
} |
q169985 | Stomp.unsubscribeW | validation | public void unsubscribeW( String name, Map header ) throws InterruptedException {
String receipt = addReceipt( header );
unsubscribe( name, (HashMap)null );
waitOnReceipt( receipt );
} | java | {
"resource": ""
} |
q169986 | Stomp.send | validation | public void send( String dest, String mesg, Map header ) {
if (header == null) header = new HashMap();
header.put( "destination", dest );
transmit( Command.SEND, header, mesg );
} | java | {
"resource": ""
} |
q169987 | Stomp.getNext | validation | public Message getNext( String name ) {
synchronized( _queue ) {
for (int idx = 0; idx < _queue.size(); idx++) {
Message m = (Message)_queue.get(idx);
if (m.headers().get( "destination" ).equals(name)) {
_queue.remove(idx);
return m;
}
}
}
return null;
} | java | {
"resource": ""
} |
q169988 | Stomp.hasReceipt | validation | public boolean hasReceipt( String receipt_id ) {
synchronized( _receipts ) {
for (Iterator i=_receipts.iterator(); i.hasNext();) {
String o = (String)i.next();
if (o.equals(receipt_id)) return true;
}
}
return false;
} | java | {
"resource": ""
} |
q169989 | Stomp.clearReceipt | validation | public void clearReceipt( String receipt_id ) {
synchronized( _receipts ) {
for (Iterator i=_receipts.iterator(); i.hasNext();) {
String o = (String)i.next();
if (o.equals(receipt_id)) i.remove();
}
}
} | java | {
"resource": ""
} |
q169990 | EventBusServiceImpl.logDeadEvent | validation | @Subscribe
public void logDeadEvent(final DeadEvent deadEvent) {
final Object event = deadEvent.getEvent();
log.warn("{} : DeadEvent : {} : {}", beanName, event.getClass().getName(), event);
} | java | {
"resource": ""
} |
q169991 | Conversion.convert | validation | public <T> T convert(final Object source, final Class<T> targetclass) {
if (source == null) {
return null;
}
final Class<?> sourceclass = source.getClass();
final SourceTargetPairKey key = new SourceTargetPairKey(sourceclass, targetclass);
Converter converter = cache.get(key);
if (converter != null) {
return (T) converter.convert(source, targetclass);
}
final LinkedList<SourceTargetPairMatch> matches = new LinkedList<SourceTargetPairMatch>();
for (SourceTargetPair pair : converters.values()) {
SourceTargetPairMatch match = pair.match(sourceclass, targetclass);
if (match.matchesSource() && match.matchesTarget()) {
matches.add(match);
}
}
if (matches.size() == 0) {
throw new ConversionException("No suitable converter found for target class ["
+ targetclass.getName() + "] and source value [" + sourceclass.getName()
+ "]. The following converters are available [" + converters.keySet() + "]");
}
Collections.sort(matches, SourceTargetPairMatch.bestTargetMatch());
converter = matches.get(0).pair.converter;
cache.put(key, converter);
return (T) converter.convert(source, targetclass);
} | java | {
"resource": ""
} |
q169992 | AbstractDryParser.getPriority | validation | protected Priority getPriority(final int lines) {
if (lines >= highThreshold) {
return Priority.HIGH;
}
else if (lines >= normalThreshold) {
return Priority.NORMAL;
}
else {
return Priority.LOW;
}
} | java | {
"resource": ""
} |
q169993 | Command.execute | validation | public void execute(GNUishParser p) {
if (instance == null) {
instance = Utils.newInstance(className);
}
final Class<?> clazz = instance.getClass();
final Method[] methods = clazz.getDeclaredMethods();
for (Method m : methods) {
m.setAccessible(true);
if (!m.getName().equals(p.getCommand())) {
continue;
}
final List<Object> args = adjustArgs(p.getArgs(), m);
injectOpts(p, clazz);
try {
validateArgs(args, instance, m, this);
m.invoke(instance, args.toArray());
return;
} catch (InvocationTargetException e) {
final Throwable ex = e.getTargetException();
if (ex instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
} else {
throw new RuntimeException(e.getTargetException());
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
System.out.println(p.getCommand() + ": command not found");
} | java | {
"resource": ""
} |
q169994 | Command.injectOpts | validation | private void injectOpts(GNUishParser p, Class<?> clazz) {
for (Field f : clazz.getDeclaredFields()) {
f.setAccessible(true);
final CliOption anno = f.getAnnotation(CliOption.class);
if (anno == null) {
continue;
}
String value = p.getShortOpt(anno.shortName());
if (value == null) {
value = p.getLongOpt(f.getName());
if (value == null) {
continue;
}
}
try {
f.set(instance, c.convert(value, f.getType()));
} catch (ConversionException e) {
throw CliException.WRONG_OPT_TYPE(f.getName(), f.getType().getName(), value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
validateOpts(instance);
} | java | {
"resource": ""
} |
q169995 | Command.adjustArgs | validation | private List<Object> adjustArgs(List<String> args, Method m) {
final List<Object> result = new ArrayList<Object>();
final Class<?>[] types = m.getParameterTypes();
if (m.isVarArgs()) {
types[types.length - 1] = types[types.length - 1].getComponentType();
if (!String.class.isAssignableFrom(types[types.length - 1])) {
throw new CliException("Only String varargs is supported.");
}
types[types.length - 1] = String.class;
}
List<Object> varargs = new ArrayList<>();
for (int i = 0; i < args.size(); i++) {
try {
if (m.isVarArgs() && i >= types.length - 1) {
varargs.add(c.convert(args.get(i), types[types.length - 1]));
} else {
result.add(c.convert(args.get(i), types[i]));
}
} catch (ConversionException e) {
throw CliException.WRONG_ARG_TYPE(getArguments().get(i).getName(),
types[i].getName(), args.get(i));
}
}
if (m.isVarArgs()) {
result.add(varargs.toArray(new String[0]));
}
return result;
} | java | {
"resource": ""
} |
q169996 | InternalMigrator.migratePersonality | validation | private List<MigrationResult> migratePersonality(final MetadataManager metadataManager, final String personalityName, final Integer targetVersion, final MigratoryOption [] options)
{
final Integer currentVersion = metadataManager.getCurrentVersion(personalityName);
if (currentVersion == null && !migratoryConfig.isCreatePersonalities()) {
throw new MigratoryException(Reason.NEW_PERSONALITIES_DENIED);
}
// Make sure that the current state of the personality is sane.
final List<MetadataInfo> history = metadataManager.getPersonalityHistory(personalityName);
final MigrationManager migrationManager = new MigrationManager(migratoryContext, personalityName);
// if null, this is a new personality.Don't validate it.
if (history != null && !history.isEmpty()) {
// "No verify" option skips this step.
if (!MigratoryOption.containsOption(MigratoryOption.NO_VERIFY, options)) {
final DbValidator dbValidator = new DbValidator(migrationManager);
final ValidationResult validationResult = dbValidator.validate(history);
if (validationResult.getValidationStatus() != ValidationStatus.OK) {
throw new MigratoryException(Reason.VALIDATION_FAILED, "Validation for Personality '%s' failed", personalityName);
}
}
else {
LOG.info("Skipped verification.");
}
}
final MigrationPlanner migrationPlanner = new MigrationPlanner(migrationManager, currentVersion, targetVersion);
migrationPlanner.plan();
LOG.info("{}", migrationPlanner.toString());
switch(migrationPlanner.getDirection()) {
case FORWARD:
if (!migratoryConfig.isAllowRollForward()) {
throw new MigratoryException(Reason.ROLL_FORWARD_DENIED);
}
break;
case BACK:
if (!migratoryConfig.isAllowRollBack()) {
throw new MigratoryException(Reason.ROLL_BACK_DENIED);
}
break;
case DO_NOTHING:
return null;
default:
LOG.warn("Encountered State {}. This should never happen!", migrationPlanner.getDirection());
return null;
}
final DbMigrator migrator = new DbMigrator(migratoryContext, migrationPlanner);
final List<MigrationResult> results = migrator.migrate(options);
LOG.info("Migration finished in '{}' steps, result is {}", results.size(), MigrationResult.determineMigrationState(results));
return results;
} | java | {
"resource": ""
} |
q169997 | CORSRequestHandler.tagRequest | validation | public void tagRequest(final HttpServletRequest request) {
final CORSRequestType type = CORSRequestType.detect(request);
switch (type) {
case ACTUAL:
request.setAttribute("cors.isCorsRequest", true);
request.setAttribute("cors.origin", request.getHeader("Origin"));
request.setAttribute("cors.requestType", "actual");
break;
case PREFLIGHT:
request.setAttribute("cors.isCorsRequest", true);
request.setAttribute("cors.origin", request.getHeader("Origin"));
request.setAttribute("cors.requestType", "preflight");
request.setAttribute("cors.requestHeaders", request.getHeader("Access-Control-Request-Headers"));
break;
case OTHER:
request.setAttribute("cors.isCorsRequest", false);
}
} | java | {
"resource": ""
} |
q169998 | CORSRequestHandler.handleActualRequest | validation | public void handleActualRequest(final HttpServletRequest request, final HttpServletResponse response)
throws InvalidCORSRequestException,
CORSOriginDeniedException,
UnsupportedHTTPMethodException {
if (CORSRequestType.detect(request) != CORSRequestType.ACTUAL)
throw new InvalidCORSRequestException("Invalid simple/actual CORS request");
// Check origin against allow list
Origin requestOrigin = new Origin(request.getHeader("Origin"));
if (! config.isAllowedOrigin(requestOrigin))
throw new CORSOriginDeniedException("CORS origin denied", requestOrigin);
// Check method
HTTPMethod method = null;
try {
method = HTTPMethod.valueOf(request.getMethod());
} catch (Exception e) {
// Parse exception
throw new UnsupportedHTTPMethodException("Unsupported HTTP method: " + request.getMethod());
}
if (! config.isSupportedMethod(method))
throw new UnsupportedHTTPMethodException("Unsupported HTTP method", method);
// Success, append response headers
response.addHeader("Access-Control-Allow-Origin", requestOrigin.toString());
if (config.supportsCredentials)
response.addHeader("Access-Control-Allow-Credentials", "true");
if (! exposedHeaders.isEmpty())
response.addHeader("Access-Control-Expose-Headers", exposedHeaders);
// Tag request
request.setAttribute("cors.origin", requestOrigin.toString());
request.setAttribute("cors.requestType", "actual");
} | java | {
"resource": ""
} |
q169999 | CORSRequestHandler.handlePreflightRequest | validation | public void handlePreflightRequest(final HttpServletRequest request, final HttpServletResponse response)
throws InvalidCORSRequestException,
CORSOriginDeniedException,
UnsupportedHTTPMethodException,
UnsupportedHTTPHeaderException {
if (CORSRequestType.detect(request) != CORSRequestType.PREFLIGHT)
throw new InvalidCORSRequestException("Invalid preflight CORS request");
// Check origin against allow list
Origin requestOrigin = new Origin(request.getHeader("Origin"));
if (! config.isAllowedOrigin(requestOrigin))
throw new CORSOriginDeniedException("CORS origin denied", requestOrigin);
// Parse requested method
// Note: method checking must be done after header parsing, see CORS spec
String requestMethodHeader = request.getHeader("Access-Control-Request-Method");
if (requestMethodHeader == null)
throw new InvalidCORSRequestException("Invalid preflight CORS request: Missing Access-Control-Request-Method header");
HTTPMethod requestedMethod = null;
try {
requestedMethod = HTTPMethod.valueOf(requestMethodHeader.toUpperCase());
} catch (Exception e) {
// Parse exception
throw new UnsupportedHTTPMethodException("Unsupported HTTP method: " + requestMethodHeader);
}
// Parse custom headers
final String[] requestHeaderValues = parseMultipleHeaderValues(request.getHeader("Access-Control-Request-Headers"));
final HeaderFieldName[] requestHeaders = new HeaderFieldName[requestHeaderValues.length];
for (int i=0; i<requestHeaders.length; i++) {
try {
requestHeaders[i] = new HeaderFieldName(requestHeaderValues[i]);
} catch (IllegalArgumentException e) {
// Invalid header name
throw new InvalidCORSRequestException("Invalid preflight CORS request: Bad request header value");
}
}
// Now, do method check
if (! config.isSupportedMethod(requestedMethod))
throw new UnsupportedHTTPMethodException("Unsupported HTTP method", requestedMethod);
// Author request headers check
for (int i=0; i<requestHeaders.length; i++) {
if (! config.supportedHeaders.contains(requestHeaders[i]))
throw new UnsupportedHTTPHeaderException("Unsupported HTTP request header", requestHeaders[i]);
}
// Success, append response headers
if (config.supportsCredentials) {
response.addHeader("Access-Control-Allow-Origin", requestOrigin.toString());
response.addHeader("Access-Control-Allow-Credentials", "true");
}
else {
if (config.allowAnyOrigin)
response.addHeader("Access-Control-Allow-Origin", "*");
else
response.addHeader("Access-Control-Allow-Origin", requestOrigin.toString());
}
if (config.maxAge > 0)
response.addHeader("Access-Control-Max-Age", Integer.toString(config.maxAge));
response.addHeader("Access-Control-Allow-Methods", supportedMethods);
if (! supportedHeaders.isEmpty())
response.addHeader("Access-Control-Allow-Headers", supportedHeaders);
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.