_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q17100
ContextManager.setCCOWEnabled
train
public void setCCOWEnabled(boolean ccowEnabled) { this.ccowEnabled = ccowEnabled; if (!ccowEnabled && ccowContextManager != null) { ccowContextManager.suspend(); ccowContextManager = null; } updateCCOWStatus(); }
java
{ "resource": "" }
q17101
ContextManager.getMarshaledContext
train
public ContextItems getMarshaledContext() { ContextItems marshaledContext = new ContextItems(); for (IManagedContext<?> managedContext : managedContexts) { marshaledContext.addItems(managedContext.getContextItems(false)); } return marshaledContext; }
java
{ "resource": "" }
q17102
ContextManager.getCCOWStatus
train
private CCOWStatus getCCOWStatus() { if (ccowContextManager == null) { return ccowEnabled ? CCOWStatus.NONE : CCOWStatus.DISABLED; } else if (ccowTransaction) { return CCOWStatus.CHANGING; } else { switch (ccowContextManager.getState()) { case csParticipating: return CCOWStatus.JOINED; case csSuspended: return CCOWStatus.BROKEN; default: return CCOWStatus.NONE; } } }
java
{ "resource": "" }
q17103
ContextManager.updateCCOWStatus
train
private void updateCCOWStatus() { if (ccowEnabled && eventManager != null) { eventManager.fireLocalEvent("CCOW", Integer.toString(getCCOWStatus().ordinal())); } }
java
{ "resource": "" }
q17104
ContextManager.registerObject
train
@Override public void registerObject(Object object) { if (object instanceof IManagedContext) { managedContexts.add((IManagedContext<?>) object); } }
java
{ "resource": "" }
q17105
ContextManager.unregisterObject
train
@Override public void unregisterObject(Object object) { if (object instanceof IContextEvent) { for (IManagedContext<?> managedContext : managedContexts) { managedContext.removeSubscriber((IContextEvent) object); } } if (object instanceof IManagedContext) { managedContexts.remove(object); } }
java
{ "resource": "" }
q17106
ContextManager.localChangeEnd
train
private void localChangeEnd(IManagedContext<?> managedContext, boolean silent, boolean deferCommit, ISurveyCallback callback) throws ContextException { if (pendingStack.isEmpty() || pendingStack.peek() != managedContext) { throw new ContextException("Illegal context change nesting."); } if (!managedContext.isPending()) { pendingStack.pop(); return; } commitStack.push(managedContext); managedContext.surveySubscribers(silent, response -> { boolean accept = !response.rejected(); if (!accept && log.isDebugEnabled()) { log.debug("Survey of managed context " + managedContext.getContextName() + " returned '" + response + "'."); } pendingStack.remove(managedContext); if (!deferCommit && (!accept || pendingStack.isEmpty())) { commitContexts(accept, accept); } execCallback(callback, response); }); }
java
{ "resource": "" }
q17107
ContextManager.resetItem
train
private void resetItem(IManagedContext<?> item, boolean silent, ISurveyCallback callback) { try { localChangeBegin(item); item.reset(); localChangeEnd(item, silent, true, callback); } catch (ContextException e) { execCallback(callback, e); } }
java
{ "resource": "" }
q17108
ContextManager.ccowPending
train
@Override public void ccowPending(CCOWContextManager sender, ContextItems contextItems) { ccowTransaction = true; updateCCOWStatus(); setMarshaledContext(contextItems, false, response -> { if (response.rejected()) { sender.setSurveyResponse(response.toString()); } ccowTransaction = false; updateCCOWStatus(); }); }
java
{ "resource": "" }
q17109
HelpView.initTopicTree
train
private void initTopicTree() { try { Object data = view.getViewData(); if (!(data instanceof TopicTree)) { return; } TopicTree topicTree = (TopicTree) data; HelpTopicNode baseNode; if (helpViewType == HelpViewType.TOC) { HelpTopic topic = new HelpTopic(null, hs.getName(), hs.getName()); baseNode = new HelpTopicNode(topic); rootNode.addChild(baseNode); } else { baseNode = rootNode; } initTopicTree(baseNode, topicTree.getRoot()); } catch (IOException e) { return; } }
java
{ "resource": "" }
q17110
PluginXmlParser.parseResources
train
private void parseResources(Element element, BeanDefinitionBuilder builder, ManagedList<AbstractBeanDefinition> resourceList) { NodeList resources = element.getChildNodes(); for (int i = 0; i < resources.getLength(); i++) { Node node = resources.item(i); if (!(node instanceof Element)) { continue; } Element resource = (Element) resources.item(i); Class<? extends IPluginResource> resourceClass = null; switch (getResourceType(getNodeName(resource))) { case button: resourceClass = PluginResourceButton.class; break; case help: resourceClass = PluginResourceHelp.class; break; case menu: resourceClass = PluginResourceMenu.class; break; case property: resourceClass = PluginResourcePropertyGroup.class; break; case css: resourceClass = PluginResourceCSS.class; break; case bean: resourceClass = PluginResourceBean.class; break; case command: resourceClass = PluginResourceCommand.class; break; case action: resourceClass = PluginResourceAction.class; break; } if (resourceClass != null) { BeanDefinitionBuilder resourceBuilder = BeanDefinitionBuilder.genericBeanDefinition(resourceClass); addProperties(resource, resourceBuilder); resourceList.add(resourceBuilder.getBeanDefinition()); } } }
java
{ "resource": "" }
q17111
PluginXmlParser.parseAuthorities
train
private void parseAuthorities(Element element, BeanDefinitionBuilder builder, ManagedList<AbstractBeanDefinition> authorityList) { NodeList authorities = element.getChildNodes(); for (int i = 0; i < authorities.getLength(); i++) { Node node = authorities.item(i); if (!(node instanceof Element)) { continue; } Element authority = (Element) node; BeanDefinitionBuilder authorityBuilder = BeanDefinitionBuilder .genericBeanDefinition(PluginDefinition.Authority.class); addProperties(authority, authorityBuilder); authorityList.add(authorityBuilder.getBeanDefinition()); } }
java
{ "resource": "" }
q17112
PluginXmlParser.parseProperties
train
private void parseProperties(Element element, BeanDefinitionBuilder builder, ManagedList<AbstractBeanDefinition> propertyList) { NodeList properties = element.getChildNodes(); for (int i = 0; i < properties.getLength(); i++) { Node node = properties.item(i); if (!(node instanceof Element)) { continue; } Element property = (Element) node; BeanDefinitionBuilder propertyBuilder = BeanDefinitionBuilder.genericBeanDefinition(PropertyInfo.class); addProperties(property, propertyBuilder); parseConfig(property, propertyBuilder); propertyList.add(propertyBuilder.getBeanDefinition()); } }
java
{ "resource": "" }
q17113
PluginXmlParser.parseConfig
train
private void parseConfig(Element property, BeanDefinitionBuilder propertyBuilder) { Element config = (Element) getTagChildren("config", property).item(0); if (config != null) { Properties properties = new Properties(); NodeList entries = getTagChildren("entry", config); for (int i = 0; i < entries.getLength(); i++) { Element entry = (Element) entries.item(i); String key = entry.getAttribute("key"); String value = entry.getTextContent().trim(); properties.put(key, value); } propertyBuilder.addPropertyValue("config", properties); } }
java
{ "resource": "" }
q17114
PluginXmlParser.getResourceType
train
private ResourceType getResourceType(String resourceTag) { if (resourceTag == null || !resourceTag.endsWith("-resource")) { return ResourceType.unknown; } try { return ResourceType.valueOf(resourceTag.substring(0, resourceTag.length() - 9)); } catch (Exception e) { return ResourceType.unknown; } }
java
{ "resource": "" }
q17115
DefaultSystemUnderDevelopment.getFixture
train
public Fixture getFixture( String name, String... params ) throws Throwable { Type<?> type = loadType( name ); Object target = type.newInstanceUsingCoercion( params ); return new DefaultFixture( target ); }
java
{ "resource": "" }
q17116
BinaryTransform.readWord
train
protected int readWord(InputStream inputStream) throws IOException { byte[] bytes = new byte[2]; boolean success = inputStream.read(bytes) == 2; return !success ? -1 : readWord(bytes, 0); }
java
{ "resource": "" }
q17117
BinaryTransform.readWord
train
protected int readWord(byte[] data, int offset) { int low = data[offset] & 0xff; int high = data[offset + 1] & 0xff; return high << 8 | low; }
java
{ "resource": "" }
q17118
BinaryTransform.getString
train
protected String getString(byte[] data, int offset) { if (offset < 0) { return ""; } int i = offset; while (data[i++] != 0x00) { ; } return getString(data, offset, i - offset - 1); }
java
{ "resource": "" }
q17119
BinaryTransform.getString
train
protected String getString(byte[] data, int offset, int length) { return new String(data, offset, length, CS_WIN1252); }
java
{ "resource": "" }
q17120
BinaryTransform.loadBinaryFile
train
protected byte[] loadBinaryFile(String file) throws IOException { try (InputStream is = resource.getInputStream(file)) { return IOUtils.toByteArray(is); } }
java
{ "resource": "" }
q17121
QueryUtil.abortResult
train
public static <T> IQueryResult<T> abortResult(String reason) { return packageResult(null, CompletionStatus.ABORTED, reason == null ? null : Collections.singletonMap("reason", (Object) reason)); }
java
{ "resource": "" }
q17122
QueryUtil.errorResult
train
public static <T> IQueryResult<T> errorResult(Throwable exception) { return packageResult(null, CompletionStatus.ERROR, exception == null ? null : Collections.singletonMap("exception", (Object) exception)); }
java
{ "resource": "" }
q17123
QueryFilterSet.filter
train
public List<T> filter(List<T> results) { if (filters.isEmpty() || results == null) { return results; } List<T> include = new ArrayList<>(); for (T result : results) { if (include(result)) { include.add(result); } } return results.size() == include.size() ? results : include; }
java
{ "resource": "" }
q17124
ElementTabPane.updateVisibility
train
@Override protected void updateVisibility(boolean visible, boolean activated) { tab.setVisible(visible); tab.setSelected(visible && activated); }
java
{ "resource": "" }
q17125
PropertyTypeRegistry.init
train
private void init() { add("text", PropertySerializer.STRING, PropertyEditorText.class); add("color", PropertySerializer.STRING, PropertyEditorColor.class); add("choice", PropertySerializer.STRING, PropertyEditorChoiceList.class); add("action", PropertySerializer.STRING, PropertyEditorAction.class); add("icon", PropertySerializer.STRING, PropertyEditorIcon.class); add("integer", PropertySerializer.INTEGER, PropertyEditorInteger.class); add("double", PropertySerializer.DOUBLE, PropertyEditorDouble.class); add("boolean", PropertySerializer.BOOLEAN, PropertyEditorBoolean.class); add("date", PropertySerializer.DATE, PropertyEditorDate.class); }
java
{ "resource": "" }
q17126
RequestUtils.computeInputParatemeter
train
private void computeInputParatemeter(final EntryPoint entryPoint, final String[] parameterNames, final Set<Class<?>> consolidatedTypeBlacklist, final Set<String> consolidatedNameBlacklist, MethodParameter methodParameter) { // If the type is part of the blacklist, we discard it if (consolidatedTypeBlacklist.contains(methodParameter.getParameterType())) { LOGGER.debug("Ignoring parameter type [{}]. It is on the blacklist.", methodParameter.getParameterType()); return; } // If we have a simple parameter type (primitives, wrappers, collections, arrays of primitives), we just get the name and we are done if (ExternalEntryPointHelper.isSimpleRequestParameter(methodParameter.getParameterType())) { // We need to look for @RequestParam in order to define its name final String parameterRealName = parameterNames[methodParameter.getParameterIndex()]; LOGGER.debug("Parameter Real Name [{}]", parameterRealName); // If the real name is part of the blacklist, we don't need to go any further if (consolidatedNameBlacklist.contains(parameterRealName)) { LOGGER.debug("Ignoring parameter name [{}]. It is on the blacklist.", parameterRealName); return; } final EntryPointParameter entryPointParameter = new EntryPointParameter(); entryPointParameter.setName(parameterRealName); entryPointParameter.setType(methodParameter.getParameterType()); // Look for a change of names and the required attribute, true by default if (methodParameter.hasParameterAnnotation(RequestParam.class)) { final RequestParam requestParam = methodParameter.getParameterAnnotation(RequestParam.class); final String definedName = StringUtils.trimToEmpty(requestParam.value()); // If the defined name is part of the blacklist, we don't need to go any further if (consolidatedNameBlacklist.contains(definedName)) { LOGGER.debug("Ignoring parameter @RequestParam defined name [{}]. It is on the blacklist.", definedName); return; } entryPointParameter.setName(StringUtils.isNotBlank(definedName) ? definedName : entryPointParameter.getName()); entryPointParameter.setRequired(requestParam.required()); entryPointParameter.setDefaultValue(StringUtils.equals(ValueConstants.DEFAULT_NONE, requestParam.defaultValue()) ? "" : requestParam.defaultValue()); } entryPoint.getParameters().add(entryPointParameter); } else if (!methodParameter.getParameterType().isArray()) { // Here we have an object, that we need to deep dive and get all its attributes, object arrays are not supported entryPoint.getParameters().addAll(ExternalEntryPointHelper.getInternalEntryPointParametersRecursively(methodParameter.getParameterType(), consolidatedTypeBlacklist, consolidatedNameBlacklist, maxDeepLevel)); } }
java
{ "resource": "" }
q17127
PropertyUtil.findSetter
train
public static Method findSetter(String methodName, Object instance, Class<?> valueClass) throws NoSuchMethodException { return findMethod(methodName, instance, valueClass, true); }
java
{ "resource": "" }
q17128
PropertyUtil.findGetter
train
public static Method findGetter(String methodName, Object instance, Class<?> valueClass) throws NoSuchMethodException { return findMethod(methodName, instance, valueClass, false); }
java
{ "resource": "" }
q17129
PropertyUtil.findMethod
train
private static Method findMethod(String methodName, Object instance, Class<?> valueClass, boolean setter) throws NoSuchMethodException { if (methodName == null) { return null; } int paramCount = setter ? 1 : 0; for (Method method : instance.getClass().getMethods()) { if (method.getName().equals(methodName) && method.getParameterTypes().length == paramCount) { Class<?> targetClass = setter ? method.getParameterTypes()[0] : method.getReturnType(); if (valueClass == null || TypeUtils.isAssignable(targetClass, valueClass)) { return method; } } } throw new NoSuchMethodException("Compatible method not found: " + methodName); }
java
{ "resource": "" }
q17130
PHS398ModularBudgetBaseGenerator.getTotalCost
train
protected ScaleTwoDecimal getTotalCost(BudgetModularContract budgetModular) { ScaleTwoDecimal totalCost = ScaleTwoDecimal.ZERO; if (budgetModular.getTotalDirectCost() != null) { totalCost = budgetModular.getTotalDirectCost(); } for (BudgetModularIdcContract budgetModularIdc : budgetModular .getBudgetModularIdcs()) { if (budgetModularIdc.getFundsRequested() != null) { totalCost = totalCost.add(budgetModularIdc.getFundsRequested()); } } return totalCost; }
java
{ "resource": "" }
q17131
PHS398ModularBudgetBaseGenerator.getCognizantFederalAgency
train
protected String getCognizantFederalAgency(RolodexContract rolodex) { StringBuilder agency = new StringBuilder(); if(rolodex.getOrganization()!=null){ agency.append(rolodex.getOrganization()); }agency.append(COMMA_SEPERATOR); if(rolodex.getFirstName()!=null){ agency.append(rolodex.getFirstName()); }agency.append(EMPTY_STRING); if(rolodex.getLastName()!=null){ agency.append(rolodex.getLastName()); }agency.append(EMPTY_STRING); if(rolodex.getPhoneNumber()!=null){ agency.append(rolodex.getPhoneNumber()); }return agency.toString(); }
java
{ "resource": "" }
q17132
HelpProcessor.transform
train
@Override public boolean transform(IResource resource) throws Exception { String path = resource.getSourcePath(); if (path.startsWith("META-INF/")) { return false; } if (hsFile == null && loader.isHelpSetFile(path)) { hsFile = getResourceBase() + resource.getTargetPath(); } return super.transform(resource); }
java
{ "resource": "" }
q17133
AbstractVcsModule.loadConfiguration
train
@Provides public VCSConfiguration loadConfiguration(Gson gson) { try { URL resource = ResourceUtils.getResourceAsURL(VCS_CONFIG_JSON); if (null == resource) { throw new IncorrectConfigurationException("Unable to find VCS configuration"); } return gson.fromJson(Resources.asCharSource(resource, Charsets.UTF_8).openStream(), VCSConfiguration.class); } catch (IOException e) { throw new IncorrectConfigurationException("Unable to read VCS configuration", e); } }
java
{ "resource": "" }
q17134
KafkaQueue.takeFromQueue
train
protected IQueueMessage<ID, DATA> takeFromQueue() { KafkaMessage kMsg = kafkaClient.consumeMessage(consumerGroupId, true, topicName, 1000, TimeUnit.MILLISECONDS); return kMsg != null ? deserialize(kMsg.content()) : null; }
java
{ "resource": "" }
q17135
ChatService.createSessionListener
train
public ParticipantListener createSessionListener(String sessionId, ISessionUpdate callback) { return SessionService.create(self, sessionId, eventManager, callback); }
java
{ "resource": "" }
q17136
ChatService.createSession
train
public void createSession(String sessionId) { boolean newSession = sessionId == null; sessionId = newSession ? newSessionId() : sessionId; SessionController controller = sessions.get(sessionId); if (controller == null) { controller = SessionController.create(sessionId, newSession); sessions.put(sessionId, controller); } }
java
{ "resource": "" }
q17137
ChatService.setActive
train
public void setActive(boolean active) { if (this.active != active) { this.active = active; inviteListener.setActive(active); acceptListener.setActive(active); participants.clear(); participants.add(self); participantListener.setActive(active); } }
java
{ "resource": "" }
q17138
ChatService.invite
train
public void invite(String sessionId, Collection<IPublisherInfo> invitees, boolean cancel) { if (invitees == null || invitees.isEmpty()) { return; } List<Recipient> recipients = new ArrayList<>(); for (IPublisherInfo invitee : invitees) { recipients.add(new Recipient(RecipientType.SESSION, invitee.getSessionId())); } String eventData = sessionId + (cancel ? "" : "^" + self.getUserName()); Recipient[] recips = new Recipient[recipients.size()]; eventManager.fireRemoteEvent(EVENT_INVITE, eventData, recipients.toArray(recips)); }
java
{ "resource": "" }
q17139
PropertiesIO.store
train
public static void store(String absolutePath, Properties configs) throws IOException { OutputStream outStream = null; try { outStream = new FileOutputStream(new File(absolutePath)); configs.store(outStream, null); } finally { try { if (outStream != null) { outStream.close(); } } catch (IOException ignore) { // do nothing. } } }
java
{ "resource": "" }
q17140
CareWebStartup.registerObject
train
@Override public void registerObject(Object object) { if (object instanceof ICareWebStartup) { startupRoutines.add((ICareWebStartup) object); } }
java
{ "resource": "" }
q17141
CareWebStartup.execute
train
public void execute() { List<ICareWebStartup> temp = new ArrayList<>(startupRoutines); for (ICareWebStartup startupRoutine : temp) { try { if (startupRoutine.execute()) { unregisterObject(startupRoutine); } } catch (Throwable t) { log.error("Error executing startup routine.", t); unregisterObject(startupRoutine); } } }
java
{ "resource": "" }
q17142
ElementImage.setStretch
train
public void setStretch(boolean stretch) { this.stretch = stretch; image.setWidth(stretch ? "100%" : null); image.setHeight(stretch ? "100%" : null); }
java
{ "resource": "" }
q17143
SpringUtil.getBean
train
public static <T> T getBean(Class<T> clazz) { ApplicationContext appContext = getAppContext(); try { return appContext == null ? null : appContext.getBean(clazz); } catch (Exception e) { return null; } }
java
{ "resource": "" }
q17144
SpringUtil.getProperty
train
public static String getProperty(String name) { if (propertyProvider == null) { initPropertyProvider(); } return propertyProvider.getProperty(name); }
java
{ "resource": "" }
q17145
SpringUtil.getResource
train
public static Resource getResource(String location) { Resource resource = resolver.getResource(location); return resource.exists() ? resource : null; }
java
{ "resource": "" }
q17146
SpringUtil.getResources
train
public static Resource[] getResources(String locationPattern) { try { return resolver.getResources(locationPattern); } catch (IOException e) { throw MiscUtil.toUnchecked(e); } }
java
{ "resource": "" }
q17147
CareWebUtil.setShell
train
protected static void setShell(CareWebShell shell) { if (getShell() != null) { throw new RuntimeException("A CareWeb shell instance has already been registered."); } ExecutionContext.getPage().setAttribute(Constants.SHELL_INSTANCE, shell); }
java
{ "resource": "" }
q17148
CareWebUtil.showMessage
train
public static void showMessage(String message, String caption) { getShell().getMessageWindow().showMessage(message, caption); }
java
{ "resource": "" }
q17149
CareWebUtil.showHelpTopic
train
public static void showHelpTopic(String module, String topic, String label) { getShell().getHelpViewer(); HelpUtil.show(module, topic, label); }
java
{ "resource": "" }
q17150
SecurityUtil.getUrlMapping
train
public static String getUrlMapping(String url, Map<String, String> urlMappings) { if (urlMappings != null) { for (String pattern : urlMappings.keySet()) { if (urlMatcher.match(pattern, url)) { return urlMappings.get(pattern); } } } return null; }
java
{ "resource": "" }
q17151
SecurityUtil.generateRandomPassword
train
public static String generateRandomPassword(int minLength, int maxLength, String[] constraints) { if (constraints == null || constraints.length == 0 || minLength <= 0 || maxLength < minLength) { throw new IllegalArgumentException(); } int pwdLength = RandomUtils.nextInt(maxLength - minLength + 1) + minLength; int[] min = new int[constraints.length]; String[] chars = new String[constraints.length]; char[] pwd = new char[pwdLength]; int totalRequired = 0; for (int i = 0; i < constraints.length; i++) { String[] pcs = constraints[i].split("\\,", 2); min[i] = Integer.parseInt(pcs[0]); chars[i] = pcs[1]; totalRequired += min[i]; } if (totalRequired > maxLength) { throw new IllegalArgumentException("Maximum length and constraints in conflict."); } int grp = 0; while (pwdLength-- > 0) { if (min[grp] <= 0) { grp = totalRequired > 0 ? grp + 1 : RandomUtils.nextInt(constraints.length); } int i = RandomUtils.nextInt(pwd.length); while (pwd[i] != 0) { i = ++i % pwd.length; } pwd[i] = chars[grp].charAt(RandomUtils.nextInt(chars[grp].length())); min[grp]--; totalRequired--; } return new String(pwd); }
java
{ "resource": "" }
q17152
S2SException.getMessageWithParams
train
public String[] getMessageWithParams() { String[] messageWithParams = new String[getParams().length+1]; messageWithParams[0]=errorMessage; System.arraycopy(params, 0, messageWithParams, 1, messageWithParams.length - 1); return messageWithParams; }
java
{ "resource": "" }
q17153
LayoutService.validateName
train
@Override public boolean validateName(String name) { return name != null && !name.isEmpty() && StringUtils.isAlphanumericSpace(name.replace('_', ' ')); }
java
{ "resource": "" }
q17154
LayoutService.layoutExists
train
@Override public boolean layoutExists(LayoutIdentifier layout) { return getLayouts(layout.shared).contains(layout.name); }
java
{ "resource": "" }
q17155
LayoutService.saveLayout
train
@Override public void saveLayout(LayoutIdentifier layout, String content) { propertyService.saveValue(getPropertyName(layout.shared), layout.name, layout.shared, content); }
java
{ "resource": "" }
q17156
LayoutService.renameLayout
train
@Override public void renameLayout(LayoutIdentifier layout, String newName) { String text = getLayoutContent(layout); saveLayout(new LayoutIdentifier(newName, layout.shared), text); deleteLayout(layout); }
java
{ "resource": "" }
q17157
LayoutService.cloneLayout
train
@Override public void cloneLayout(LayoutIdentifier layout, LayoutIdentifier layout2) { String text = getLayoutContent(layout); saveLayout(layout2, text); }
java
{ "resource": "" }
q17158
LayoutService.getLayoutContent
train
@Override public String getLayoutContent(LayoutIdentifier layout) { return propertyService.getValue(getPropertyName(layout.shared), layout.name); }
java
{ "resource": "" }
q17159
LayoutService.getLayoutContentByAppId
train
@Override public String getLayoutContentByAppId(String appId) { String value = propertyService.getValue(PROPERTY_LAYOUT_ASSOCIATION, appId); return value == null ? null : getLayoutContent(new LayoutIdentifier(value, true)); }
java
{ "resource": "" }
q17160
LayoutService.getLayouts
train
@Override public List<String> getLayouts(boolean shared) { List<String> layouts = propertyService.getInstances(getPropertyName(shared), shared); Collections.sort(layouts, String.CASE_INSENSITIVE_ORDER); return layouts; }
java
{ "resource": "" }
q17161
CWFAuthenticationDetailsSource.buildDetails
train
@Override public CWFAuthenticationDetails buildDetails(HttpServletRequest request) { log.trace("Building details"); CWFAuthenticationDetails details = new CWFAuthenticationDetails(request); return details; }
java
{ "resource": "" }
q17162
BaseMojo.init
train
protected void init(String classifier, String moduleBase) throws MojoExecutionException { this.classifier = classifier; this.moduleBase = moduleBase; stagingDirectory = new File(buildDirectory, classifier + "-staging"); configTemplate = new ConfigTemplate(classifier + "-spring.xml"); exclusionFilter = exclusions == null || exclusions.isEmpty() ? null : new WildcardFileFilter(exclusions); archiveConfig.setAddMavenDescriptor(false); }
java
{ "resource": "" }
q17163
BaseMojo.getModuleVersion
train
protected String getModuleVersion() { StringBuilder sb = new StringBuilder(); int pcs = 0; for (String pc : projectVersion.split("\\.")) { if (pcs++ > 3) { break; } else { appendVersionPiece(sb, pc); } } appendVersionPiece(sb, buildNumber); return sb.toString(); }
java
{ "resource": "" }
q17164
BaseMojo.newStagingFile
train
public File newStagingFile(String entryName, long modTime) { File file = new File(stagingDirectory, entryName); if (modTime != 0) { file.setLastModified(modTime); } file.getParentFile().mkdirs(); return file; }
java
{ "resource": "" }
q17165
BaseMojo.throwMojoException
train
public void throwMojoException(String msg, Throwable e) throws MojoExecutionException { if (failOnError) { throw new MojoExecutionException(msg, e); } else { getLog().error(msg, e); } }
java
{ "resource": "" }
q17166
BaseMojo.assembleArchive
train
protected void assembleArchive() throws Exception { getLog().info("Assembling " + classifier + " archive"); if (resources != null && !resources.isEmpty()) { getLog().info("Copying additional resources."); new ResourceProcessor(this, moduleBase, resources).transform(); } if (configTemplate != null) { getLog().info("Creating config file."); configTemplate.addEntry("info", pluginDescriptor.getName(), pluginDescriptor.getVersion(), new Date().toString()); configTemplate.createFile(stagingDirectory); } try { File archive = createArchive(); if ("war".equalsIgnoreCase(mavenProject.getPackaging()) && this.warInclusion) { webappLibDirectory.mkdirs(); File webappLibArchive = new File(this.webappLibDirectory, archive.getName()); Files.copy(archive, webappLibArchive); } } catch (Exception e) { throw new RuntimeException("Exception occurred assembling archive.", e); } }
java
{ "resource": "" }
q17167
BaseMojo.createArchive
train
private File createArchive() throws Exception { getLog().info("Creating archive."); Artifact artifact = mavenProject.getArtifact(); String clsfr = noclassifier ? "" : ("-" + classifier); String archiveName = artifact.getArtifactId() + "-" + artifact.getVersion() + clsfr + ".jar"; File jarFile = new File(mavenProject.getBuild().getDirectory(), archiveName); MavenArchiver archiver = new MavenArchiver(); jarArchiver.addDirectory(stagingDirectory); archiver.setArchiver(jarArchiver); archiver.setOutputFile(jarFile); archiver.createArchive(mavenSession, mavenProject, archiveConfig); if (noclassifier) { artifact.setFile(jarFile); } else { projectHelper.attachArtifact(mavenProject, jarFile, classifier); } FileUtils.deleteDirectory(stagingDirectory); return jarFile; }
java
{ "resource": "" }
q17168
ThreadUtil.startThread
train
public static void startThread(Thread thread) { if (log.isDebugEnabled()) { log.debug("Starting background thread: " + thread); } ExecutorService executor = getTaskExecutor(); if (executor != null) { executor.execute(thread); } else { thread.start(); } }
java
{ "resource": "" }
q17169
SessionService.create
train
protected static SessionService create(IPublisherInfo self, String sessionId, IEventManager eventManager, ISessionUpdate callback) { String sendEvent = StrUtil.formatMessage(EVENT_SEND, sessionId); String joinEvent = StrUtil.formatMessage(EVENT_JOIN, sessionId); String leaveEvent = StrUtil.formatMessage(EVENT_LEAVE, sessionId); return new SessionService(self, sendEvent, joinEvent, leaveEvent, eventManager, callback); }
java
{ "resource": "" }
q17170
SessionService.sendMessage
train
public ChatMessage sendMessage(String text) { if (text != null && !text.isEmpty()) { ChatMessage message = new ChatMessage(self, text); eventManager.fireRemoteEvent(sendEvent, message); return message; } return null; }
java
{ "resource": "" }
q17171
HelpSearchHit.compareTo
train
@Override public int compareTo(HelpSearchHit hit) { int result = -NumUtil.compare(confidence, hit.confidence); return result != 0 ? result : topic.compareTo(hit.topic); }
java
{ "resource": "" }
q17172
FormPrintServiceImpl.toUnsignedByte
train
protected static byte toUnsignedByte(int intVal) { byte byteVal; if (intVal > 127) { int temp = intVal - 256; byteVal = (byte) temp; } else { byteVal = (byte) intVal; } return byteVal; }
java
{ "resource": "" }
q17173
CipherUtil.getKeyStore
train
public static KeyStore getKeyStore(String keystoreLocation, String keystoreType) throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException { KeyStore keystore = KeyStore.getInstance(keystoreType); InputStream is = CipherUtil.class.getResourceAsStream(keystoreLocation); if (is == null) { is = new FileInputStream(keystoreLocation); } keystore.load(is, null); return keystore; }
java
{ "resource": "" }
q17174
CipherUtil.verify
train
public static boolean verify(PublicKey key, String base64Signature, String content, String timestamp, int duration) throws Exception { if (key == null || base64Signature == null || content == null || timestamp == null) { return false; } try { if (timestamp != null && duration > 0) { validateTime(timestamp, duration); } Signature signature = Signature.getInstance(SIGN_ALGORITHM); signature.initVerify(key); signature.update(content.getBytes()); byte[] signatureBytes = Base64.decodeBase64(base64Signature); return signature.verify(signatureBytes); } catch (Exception e) { log.error("Authentication Exception:verifySignature", e); throw e; } }
java
{ "resource": "" }
q17175
CipherUtil.sign
train
public static String sign(PrivateKey key, String content) throws Exception { Signature signature = Signature.getInstance(SIGN_ALGORITHM); signature.initSign(key); signature.update(content.getBytes()); return Base64.encodeBase64String(signature.sign()); }
java
{ "resource": "" }
q17176
CipherUtil.validateTime
train
public static void validateTime(String timestamp, int duration) throws Exception { Date date = getTimestampFormatter().parse(timestamp); long sign_time = date.getTime(); long now_time = System.currentTimeMillis(); long diff = now_time - sign_time; long min_diff = diff / (60 * 1000); if (min_diff >= duration) { throw new GeneralSecurityException("Authorization token has expired."); } }
java
{ "resource": "" }
q17177
CipherUtil.getTimestamp
train
public static String getTimestamp(Date time) { return getTimestampFormatter().format(time == null ? new Date() : time); }
java
{ "resource": "" }
q17178
CipherUtil.encrypt
train
public static String encrypt(Key key, String content) throws Exception { try { Cipher cipher = Cipher.getInstance(CRYPTO_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key); return Base64.encodeBase64String(cipher.doFinal(content.getBytes())); } catch (Exception e) { log.error("Error while encrypting", e); throw e; } }
java
{ "resource": "" }
q17179
CipherUtil.decrypt
train
public static String decrypt(Key key, String content) throws Exception { try { Cipher cipher = Cipher.getInstance(CRYPTO_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key); return new String(cipher.doFinal(Base64.decodeBase64(content))); } catch (Exception e) { log.error("Error while decrypting", e); throw e; } }
java
{ "resource": "" }
q17180
ManifestUtils.getManifestAttribute
train
public String getManifestAttribute(String attributeName) { if (attributeName != null) { Map<Object,Object> mf = getManifestAttributes(); for (Object att : mf.keySet()) { if (attributeName.equals(att.toString())) { return mf.get(att).toString(); } } } //In case not found return null; return null; }
java
{ "resource": "" }
q17181
ManifestUtils.getManifestAttributes
train
public Map<Object, Object> getManifestAttributes() { Map<Object, Object> manifestAttributes = null; manifestAttributes = getExplodedWarManifestAttributes(); if (manifestAttributes == null) { manifestAttributes = getPackagedWarManifestAttributes(); } if (manifestAttributes == null) { manifestAttributes = getClassPathManifestAttributes(); } if (manifestAttributes == null) { manifestAttributes = new HashMap<>(); } return manifestAttributes; }
java
{ "resource": "" }
q17182
ManifestUtils.getExplodedWarManifestAttributes
train
private Map<Object, Object> getExplodedWarManifestAttributes() { Map<Object, Object> manifestAttributes = null; FileInputStream fis = null; try { if (servletContext != null) { final String appServerHome = servletContext.getRealPath(""); final File manifestFile = new File(appServerHome, MANIFEST); LOGGER.debug("Using Manifest file:{}", manifestFile.getPath()); fis = new FileInputStream(manifestFile); Manifest mf = new Manifest(fis); manifestAttributes = mf.getMainAttributes(); } } catch (Exception e) { LOGGER.warn("Unable to read the manifest file from the servlet context."); LOGGER.debug("Unable to read the manifest file", e); } finally { IOUtils.closeQuietly(fis); } return manifestAttributes; }
java
{ "resource": "" }
q17183
ManifestUtils.getPackagedWarManifestAttributes
train
private Map<Object, Object> getPackagedWarManifestAttributes() { Map<Object, Object> manifestAttributes = null; try { LOGGER.debug("Using Manifest file:{}", servletContext.getResource(MANIFEST).getPath()); Manifest manifest = new Manifest(servletContext.getResourceAsStream(MANIFEST)); manifestAttributes = manifest.getMainAttributes(); } catch (Exception e) { LOGGER.warn("Unable to read the manifest from the packaged war"); LOGGER.debug("Unable to read the manifest from the packaged", e); } return manifestAttributes; }
java
{ "resource": "" }
q17184
S2SLocationServiceImpl.getCountryFromCode
train
@Override public CountryContract getCountryFromCode(String countryCode) { if(StringUtils.isBlank(countryCode)) return null; CountryContract country = getKcCountryService().getCountryByAlternateCode(countryCode); if(country==null){ country = getKcCountryService().getCountry(countryCode); } return country; }
java
{ "resource": "" }
q17185
S2SLocationServiceImpl.getStateFromName
train
@Override public StateContract getStateFromName(String countryAlternateCode, String stateName) { CountryContract country = getCountryFromCode(countryAlternateCode); return getKcStateService().getState(country.getCode(), stateName); }
java
{ "resource": "" }
q17186
SegmentationHelper.isSegmented
train
public static boolean isSegmented(Name name, byte marker) { return name.size() > 0 && name.get(-1).getValue().buf().get(0) == marker; }
java
{ "resource": "" }
q17187
SegmentationHelper.parseSegment
train
public static long parseSegment(Name name, byte marker) throws EncodingException { if (name.size() == 0) { throw new EncodingException("No components to parse."); } return name.get(-1).toNumberWithMarker(marker); }
java
{ "resource": "" }
q17188
SegmentationHelper.removeSegment
train
public static Name removeSegment(Name name, byte marker) { return isSegmented(name, marker) ? name.getPrefix(-1) : new Name(name); }
java
{ "resource": "" }
q17189
SegmentationHelper.segment
train
public static List<Data> segment(Data template, InputStream bytes) throws IOException { return segment(template, bytes, DEFAULT_SEGMENT_SIZE); }
java
{ "resource": "" }
q17190
SegmentationHelper.readAll
train
public static byte[] readAll(InputStream bytes) throws IOException { ByteArrayOutputStream builder = new ByteArrayOutputStream(); int read = bytes.read(); while (read != -1) { builder.write(read); read = bytes.read(); } builder.flush(); bytes.close(); return builder.toByteArray(); }
java
{ "resource": "" }
q17191
PropertyEditorAction.init
train
@Override protected void init(Object target, PropertyInfo propInfo, PropertyGrid propGrid) { propInfo.getConfig().setProperty("readonly", Boolean.toString(!SecurityUtil.hasDebugRole())); super.init(target, propInfo, propGrid); List<IAction> actions = new ArrayList<>(ActionRegistry.getRegisteredActions(ActionScope.BOTH)); Collections.sort(actions, ActionUtil.comparator); for (IAction action : actions) { appendItem(action.toString(), action.getId()); } }
java
{ "resource": "" }
q17192
GlobalLibraryV2_0Generator.getCountryCodeDataType
train
public CountryCodeDataType.Enum getCountryCodeDataType(String countryCode) { CountryCodeDataType.Enum countryCodeDataType = null; CountryContract country = s2SLocationService.getCountryFromCode(countryCode); if (country != null) { StringBuilder countryDetail = new StringBuilder(); countryDetail.append(country.getAlternateCode()); countryDetail.append(": "); countryDetail.append(country.getName().toUpperCase()); countryCodeDataType = CountryCodeDataType.Enum .forString(countryDetail.toString()); } return countryCodeDataType; }
java
{ "resource": "" }
q17193
GlobalLibraryV2_0Generator.getStateCodeDataType
train
public StateCodeDataType.Enum getStateCodeDataType(String countryAlternateCode, String stateName) { StateCodeDataType.Enum stateCodeDataType = null; StateContract state = s2SLocationService.getStateFromName(countryAlternateCode, stateName); if (state != null) { StringBuilder stateDetail = new StringBuilder(); stateDetail.append(state.getCode()); stateDetail.append(": "); String stateNameCapital = WordUtils.capitalizeFully(state.getName()); stateNameCapital = stateNameCapital.replace(" Of ", " of "); stateNameCapital = stateNameCapital.replace(" The ", " the "); stateNameCapital = stateNameCapital.replace(" And ", " and "); stateDetail.append(stateNameCapital); stateCodeDataType = StateCodeDataType.Enum.forString(stateDetail .toString()); } return stateCodeDataType; }
java
{ "resource": "" }
q17194
GlobalLibraryV2_0Generator.getAddressDataType
train
public AddressDataType getAddressDataType(RolodexContract rolodex) { AddressDataType addressDataType = AddressDataType.Factory.newInstance(); if (rolodex != null) { String street1 = rolodex.getAddressLine1(); addressDataType.setStreet1(street1); String street2 = rolodex.getAddressLine2(); if (street2 != null && !street2.equals("")) { addressDataType.setStreet2(street2); } String city = rolodex.getCity(); addressDataType.setCity(city); String county = rolodex.getCounty(); if (county != null && !county.equals("")) { addressDataType.setCounty(county); } String postalCode = rolodex.getPostalCode(); if (postalCode != null && !postalCode.equals("")) { addressDataType.setZipPostalCode(postalCode); } String country = rolodex.getCountryCode(); CountryCodeDataType.Enum countryCodeDataType = getCountryCodeDataType(country); addressDataType.setCountry(countryCodeDataType); String state = rolodex.getState(); if (state != null && !state.equals("")) { if (countryCodeDataType != null) { if (countryCodeDataType .equals(CountryCodeDataType.USA_UNITED_STATES)) { addressDataType.setState(getStateCodeDataType(country, state)); } else { addressDataType.setProvince(state); } } } } return addressDataType; }
java
{ "resource": "" }
q17195
GlobalLibraryV2_0Generator.getHumanNameDataType
train
public HumanNameDataType getHumanNameDataType(ProposalPersonContract person) { HumanNameDataType humanName = HumanNameDataType.Factory.newInstance(); if (person != null) { humanName.setFirstName(person.getFirstName()); humanName.setLastName(person.getLastName()); String middleName = person.getMiddleName(); if (middleName != null && !middleName.equals("")) { humanName.setMiddleName(middleName); } } return humanName; }
java
{ "resource": "" }
q17196
GlobalLibraryV2_0Generator.getHumanNameDataType
train
public HumanNameDataType getHumanNameDataType(RolodexContract rolodex) { HumanNameDataType humanName = HumanNameDataType.Factory.newInstance(); if (rolodex != null) { humanName.setFirstName(rolodex.getFirstName()); humanName.setLastName(rolodex.getLastName()); String middleName = rolodex.getMiddleName(); if (middleName != null && !middleName.equals("")) { humanName.setMiddleName(middleName); } } return humanName; }
java
{ "resource": "" }
q17197
GlobalLibraryV2_0Generator.getContactPersonDataType
train
public ContactPersonDataType getContactPersonDataType(ProposalPersonContract person) { ContactPersonDataType contactPerson = ContactPersonDataType.Factory .newInstance(); if (person != null) { contactPerson.setName((getHumanNameDataType(person))); String phone = person.getOfficePhone(); if (phone != null && !phone.equals("")) { contactPerson.setPhone(phone); } String email = person.getEmailAddress(); if (email != null && !email.equals("")) { contactPerson.setEmail(email); } String title = person.getPrimaryTitle(); if (title != null && !title.equals("")) { contactPerson.setTitle(title); } String fax = person.getFaxNumber(); if (StringUtils.isNotEmpty(fax)) { contactPerson.setFax(fax); } contactPerson.setAddress(getAddressDataType(person)); } return contactPerson; }
java
{ "resource": "" }
q17198
BaseImagePicker.nextImageSet
train
public Map<String, URL> nextImageSet() { return buildImageSet(dirs.get(random.nextInt(dirs.size()))); }
java
{ "resource": "" }
q17199
FrameworkController.getController
train
public static Object getController(BaseComponent comp, boolean recurse) { return recurse ? comp.findAttribute(Constants.ATTR_COMPOSER) : comp.getAttribute(Constants.ATTR_COMPOSER); }
java
{ "resource": "" }