code stringlengths 73 34.1k | label stringclasses 1
value |
|---|---|
public RouteBuilder put(){
if(!methods.contains(HttpMethod.PUT)){
methods.add(HttpMethod.PUT);
}
return this;
} | java |
public RouteBuilder delete(){
if(!methods.contains(HttpMethod.DELETE)){
methods.add(HttpMethod.DELETE);
}
return this;
} | java |
protected boolean matches(String requestUri, ControllerPath controllerPath, HttpMethod httpMethod) throws ClassLoadException {
boolean match = false;
String[] requestUriSegments = Util.split(requestUri, '/');
if(isWildcard() && requestUriSegments.length >= segments.size() && wildSegmentsMatch(... | java |
protected static Map<String, Object> getSessionAttributes(){
//TODO: cache session attributes map since this method can be called multiple times during a request.
HttpSession session = RequestContext.getHttpRequest().getSession(true);
Enumeration names = session.getAttributeNames();
Map... | java |
protected FilterBuilder add(HttpSupportFilter... filters) {
for (HttpSupportFilter filter : filters) {
if(allFilters.contains(filter)){
throw new IllegalArgumentException("Cannot register the same filter instance more than once.");
}
}
allFilters.addAll(Co... | java |
public static boolean isXhr(){
String xhr = header("X-Requested-With");
if(xhr == null) {
xhr = header("x-requested-with");
}
return xhr != null && xhr.toLowerCase().equals("xmlhttprequest");
} | java |
public static List<String> params(String name){
String[] values = RequestContext.getHttpRequest().getParameterValues(name);
List<String>valuesList = null;
if (name.equals("id")) {
if(values.length == 1){
valuesList = Collections.singletonList(values[0]);
}... | java |
public static Map<String, String> params1st(){
//TODO: candidate for performance optimization
Map<String, String> params = new HashMap<>();
Enumeration names = RequestContext.getHttpRequest().getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextEleme... | java |
public static List<Cookie> cookies(){
javax.servlet.http.Cookie[] servletCookies = RequestContext.getHttpRequest().getCookies();
if(servletCookies == null)
return new ArrayList<>();
List<Cookie> cookies = new ArrayList<>();
for (javax.servlet.http.Cookie servletCookie: servl... | java |
public static Cookie cookie(String name){
javax.servlet.http.Cookie[] servletCookies = RequestContext.getHttpRequest().getCookies();
if (servletCookies != null) {
for (javax.servlet.http.Cookie servletCookie : servletCookies) {
if (servletCookie.getName().equals(name)) {
... | java |
public void session(String name, Object value){
RequestContext.getHttpRequest().getSession().getAttribute(name);
} | java |
private List<ConnectionSpecWrapper> getConnectionWrappers() {
List<ConnectionSpecWrapper> allConnections = DbConfiguration.getConnectionSpecWrappers();
List<ConnectionSpecWrapper> result = new LinkedList<>();
for (ConnectionSpecWrapper connectionWrapper : allConnections) {
if (!conn... | java |
protected void assign(String name, Object value) {
KeyWords.check(name);
RequestContext.getValues().put(name, value);
} | java |
protected HttpBuilder redirect(String path) {
RedirectResponse resp = new RedirectResponse(path);
RequestContext.setControllerResponse(resp);
return new HttpBuilder(resp);
} | java |
protected Iterator<FormItem> uploadedFiles(String encoding, long maxFileSize) {
List<FormItem> fileItems = new ArrayList<>();
for(FormItem item : multipartFormItems(encoding, maxFileSize)) {
if (item.isFile()) {
fileItems.add(item);
}
}
return file... | java |
private static String parseHashName(String param) {
Matcher matcher = hashPattern.matcher(param);
String name = null;
while (matcher.find()){
name = matcher.group(0);
}
return name == null? null : name.substring(1, name.length() - 1);
} | java |
protected boolean blank(String ... names){
//TODO: write test, move elsewhere - some helper
for(String name:names){
if(Util.blank(param(name))){
return true;
}
}
return false;
} | java |
protected String merge(String template, Map values){
StringWriter stringWriter = new StringWriter();
Configuration.getTemplateManager().merge(values, template, stringWriter);
return stringWriter.toString();
} | java |
public Map<String, String> getResponseHeaders(){
Collection<String> names = RequestContext.getHttpResponse().getHeaderNames();
Map<String, String> headers = new HashMap<>();
for (String name : names) {
headers.put(name, RequestContext.getHttpResponse().getHeader(name));
}
... | java |
public void addAttributesExcept(Map params, String ... exceptions){
List exceptionList = Arrays.asList(exceptions);
for(Object key: params.keySet()){
if(!exceptionList.contains(key)){
attribute(key.toString(), params.get(key).toString());
}
}
} | java |
public String id(){
HttpServletRequest r = RequestContext.getHttpRequest();
if(r == null){
return null;
}
HttpSession session = r.getSession(false);
return session == null ? null : session.getId();
} | java |
public Object get(String name){
return RequestContext.getHttpRequest().getSession(true).getAttribute(name);
} | java |
private void injectFreemarkerTags() {
if(!tagsInjected){
AbstractFreeMarkerConfig freeMarkerConfig = Configuration.getFreeMarkerConfig();
Injector injector = Configuration.getInjector();
tagsInjected = true;
if(injector == null || freeMarkerConfig == null){
... | java |
private void injectController(AppController controller) {
Injector injector = Configuration.getInjector();
if (injector != null) {
injector.injectMembers(controller);
}
} | java |
private void configureExplicitResponse(Route route, String controllerLayout, RenderTemplateResponse resp) throws InstantiationException, IllegalAccessException {
if(!Configuration.getDefaultLayout().equals(controllerLayout) && resp.hasDefaultLayout()){
resp.setLayout(controllerLayout);
... | java |
private void createDefaultResponse(Route route, String controllerLayout) throws InstantiationException, IllegalAccessException {
String controllerPath = Router.getControllerPath(route.getController().getClass());
String template = controllerPath + "/" + route.getActionName();
RenderT... | java |
private boolean checkActionMethod(AppController controller, String actionMethod) {
HttpMethod method = HttpMethod.getMethod(RequestContext.getHttpRequest());
if (!controller.actionSupportsHttpMethod(actionMethod, method)) {
DirectResponse res = new DirectResponse("");
//see http:... | java |
private void filterAfter(Route route) {
try {
List<HttpSupportFilter> filters = Configuration.getFilters();
for (int i = filters.size() - 1; i >= 0; i--) {
HttpSupportFilter filter = filters.get(i);
if(Configuration.getFilterMetadata(filter).matches(route)... | java |
public void jdbc(String driver, String url, String user, String password) {
connectionWrapper.setConnectionSpec(new ConnectionJdbcSpec(driver, url, user, password));
} | java |
public void jdbc(String driver, String url, Properties props) {
connectionWrapper.setConnectionSpec(new ConnectionJdbcSpec(driver, url, props));
} | java |
protected static void injectFilters() {
if(injector != null ){
if(Configuration.isTesting()){
for (HttpSupportFilter filter : filters) {
injector.injectMembers(filter);
}
} else if (!filtersInjected) {
for (HttpSupportFi... | java |
static FilterMetadata getFilterMetadata(HttpSupportFilter filter){
FilterMetadata config = filterMetadataMap.get(filter);
if(config == null){
config = new FilterMetadata();
filterMetadataMap.put(filter, config);
}
return config;
} | java |
public static <T extends Command> T fromXml(String commandXml) {
return (T) X_STREAM.fromXML(commandXml);
} | java |
public static byte[] generateImage(String text) {
int w = 180, h = 40;
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
... | java |
public String getStreamAsString(){
try {
return Util.read(fileItemStream.openStream());
} catch (Exception e) {
throw new ControllerException(e);
}
} | java |
public void registerTag(String name, FreeMarkerTag tag){
configuration.setSharedVariable(name, tag);
userTags.add(tag);
} | java |
private static List<URL> hackForWeblogic(FilterConfig config) {
List<URL> urls = new ArrayList<>();
Set libJars = config.getServletContext().getResourcePaths("/WEB-INF/lib");
for (Object jar : libJars) {
try {
urls.add(config.getServletContext().getResource((String) j... | java |
public void close() {
synchronized (sessions) {
closed = true;
sessionCleaner.close();
sessions.stream().forEach(PooledSession::reallyClose);
}
} | java |
public void stop() {
started = false;
senderSessionPool.close();
receiverSessionPool.close();
listenerConsumers.forEach(Util::closeQuietly);
listenerSessions.forEach(Util::closeQuietly);
closeQuietly(producerConnection);
closeQuietly(consumerConnection);
... | java |
public void configureNetty(String host, int port){
Map<String, Object> params = map(TransportConstants.HOST_PROP_NAME, host, TransportConstants.PORT_PROP_NAME, port);
config.getAcceptorConfigurations().add(new TransportConfiguration(NettyAcceptorFactory.class.getName(), params));
} | java |
public Message receiveMessage(String queueName, long timeout) {
checkStarted();
try(Session session = receiverSessionPool.getSession()){
Queue queue = (Queue) jmsServer.lookup(QUEUE_NAMESPACE + queueName);
try(MessageConsumer consumer = session.createConsumer(queue)) {
... | java |
public List<Command> getTopCommands(int count, String queueName) {
checkStarted();
List<Command> res = new ArrayList<>();
try(Session session = consumerConnection.createSession()) {
Queue queue = (Queue) jmsServer.lookup(QUEUE_NAMESPACE + queueName);
Enumeration message... | java |
protected Message lookupMessage(String queueName) {
checkStarted();
try(Session session = consumerConnection.createSession()) {
Queue queue = (Queue) jmsServer.lookup(QUEUE_NAMESPACE + queueName);
Enumeration messages = session.createBrowser(queue).getEnumeration();
... | java |
public Map<String, Long> getMessageCounts(){
Map<String, Long> counts = new HashMap<>();
for (QueueConfig queueConfig : queueConfigsList) {
counts.put(queueConfig.getName(), getMessageCount(queueConfig.getName()));
}
return counts;
} | java |
public long getMessageCount(String queue){
try {
return getQueueControl(queue).getMessageCount();
} catch (Exception e) {
throw new AsyncException(e);
}
} | java |
public void resume(String queueName) {
try {
getQueueControl(queueName).resume();
} catch (Exception e) {
throw new AsyncException(e);
}
} | java |
public void pause(String queueName) {
try {
getQueueControl(queueName).pause();
} catch (Exception e) {
throw new AsyncException(e);
}
} | java |
public int removeMessages(String queueName, String filter) {
try {
return getQueueControl(queueName).removeMessages(filter);
} catch (Exception e) {
throw new AsyncException(e);
}
} | java |
public int removeAllMessages(String queueName) {
try {
return getQueueControl(queueName).removeMessages(null);
} catch (Exception e) {
throw new AsyncException(e);
}
} | java |
public int moveMessages(String source, String target){
try {
return getQueueControl(source).moveMessages("", target);
} catch (Exception e) {
throw new AsyncException(e);
}
} | java |
private static String encode(String value, BitSet unescapedChars) {
// Code from org.apache.commons.codec.net.URLCodec.encodeUrl(BitSet, byte[])
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
for (final byte c : value.getBytes(CHARSET)) {
int b = c;
if ... | java |
public SchemaEntry extractResourceLocation(SchemaEntry entry) {
Optional<String> actualResourceUri = Optional.empty();
if (! entry.getVocabularyDefinedBy().equals(entry.getVocabularyNamespace()))
actualResourceUri = getContentLocation(entry.getVocabularyDefinedBy(), GENERALFORMAT, Lists.newA... | java |
private Optional<String> getContentVersions(String currentUrl, Collection<SerializationFormat> formats, ArrayList<String> redirects){
Optional<SerializationFormat> test = formats.stream().filter(x -> currentUrl.trim().endsWith(x.getExtension())).findFirst();
if(currentUrl != null && ! test.isPresent()){... | java |
public static void main(String[] args) {
LOVEndpoint lov = new LOVEndpoint();
String file = args.length > 0 ? args[1].trim() : "rdfunit-model/src/main/resources/org/aksw/rdfunit/configuration/schemaLOV.csv";
lov.writeAllLOVEntriesToFile(file);
} | java |
public static TestExecution validate(final TestCaseExecutionType testCaseExecutionType, final TestSource testSource, final TestSuite testSuite, final String agentID, DatasetOverviewResults overviewResults) {
checkNotNull(testCaseExecutionType, "Test Execution Type must not be null");
checkNotNull(testS... | java |
public static void init(String clientHost) {
VaadinSession.getCurrent().setAttribute("client", clientHost);
String baseDir = _getBaseDir();
VaadinSession.getCurrent().setAttribute(String.class, baseDir);
TestGeneratorExecutor testGeneratorExecutor = new TestGeneratorExecutor();
... | java |
public static String findLongestOverlap(String first, String second){
if(org.apache.commons.lang3.StringUtils.isEmpty(first) || org.apache.commons.lang3.StringUtils.isEmpty(second))
return "";
int length = Math.min(first.length(), second.length());
for(int i = 0; i < length; i++){
... | java |
public RDFUnit init() {
// Update pattern service
for (Pattern pattern : getPatterns()) {
PatternService.addPattern(pattern.getId(),pattern.getIRI(), pattern);
}
return this;
} | java |
private void handleRequestAndRespond(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
RDFUnitConfiguration configuration = null;
try {
configuration = getConfiguration(httpServletRequest);
} catch (ParameterException e) {
... | java |
private static void writeResults(final RDFUnitConfiguration configuration, final TestExecution testExecution, HttpServletResponse httpServletResponse) throws RdfWriterException, IOException {
SerializationFormat serializationFormat = configuration.geFirstOutputFormat();
if (serializationFormat == null) ... | java |
private boolean containsFormatName(String format) {
return name.equalsIgnoreCase(format) || synonyms.contains(format.toLowerCase());
} | java |
public static String getURIFromAbbrev(final String abbreviation) {
String[] parts = abbreviation.split(":");
if (parts.length == 2) {
return getNSFromPrefix(parts[0]) + parts[1];
}
throw new IllegalArgumentException("Undefined prefix in " + abbreviation);
} | java |
public static String getLocalName(final String uri, final String prefix) {
String ns = getNSFromPrefix(prefix);
if (ns != null) {
return uri.replace(ns, "");
}
throw new IllegalArgumentException("Undefined prefix (" + prefix + ") in URI: " + uri);
} | java |
protected static String getStatusClass(RLOGLevel level) {
String rowClass = "";
switch (level) {
case WARN:
rowClass = "warning";
break;
case ERROR:
rowClass = "danger";
break;
case INFO:
... | java |
private static String nodeTargetPattern(ShapeTargetValueShape target) {
return " " + formatNode(target.getNode()) + " " + writePropertyChain(target.pathChain) + " ?this . ";
} | java |
private Model initModel() {
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel());
try {
schemaReader.read(m);
} catch (RdfReaderException e) {
log.error("Cannot load ontology: {} ", getSchema(), e);
}
re... | java |
public static SerializationFormat getInputFormat(String name) {
for (SerializationFormat ft : Instance.serializationFormats) {
if (ft.isAcceptedAsInput(name)) {
return ft;
}
}
return null;
} | java |
public static SerializationFormat getOutputFormat(String name) {
for (SerializationFormat ft : Instance.serializationFormats) {
if (ft.isAcceptedAsOutput(name)) {
return ft;
}
}
return null;
} | java |
public static Collection<SerializationFormat> getAllFormats() {
ArrayList<SerializationFormat> serializationFormats = new ArrayList<>();
// single graph formats
serializationFormats.add(createTurtle());
serializationFormats.add(createN3());
serializationFormats.add(createNTriple... | java |
static HttpResponse executeHeadRequest(URI uri, SerializationFormat format) throws IOException {
HttpHead headMethod = new HttpHead(uri);
MyRedirectHandler redirectHandler = new MyRedirectHandler(uri);
String acceptHeader = format.getMimeType() != null && ! format.getMimeType().trim().isEmpty(... | java |
public static RdfReader createDereferenceReader(String uri) {
Collection<RdfReader> readers = new ArrayList<>();
if (!IOUtils.isFile(uri)) {
readers.add(new RdfDereferenceReader(uri));
//readers.add(new RDFaReader(uri));
} else {
readers.add(new RdfStreamReade... | java |
public String getNamespaceFromURI(String uri) {
String breakChar = "/";
if (uri.contains("#")) {
breakChar = "#";
} else {
if (uri.substring(6).contains(":")) {
breakChar = ":";
}
}
int pos = Math.min(uri.lastIndexOf(breakChar)... | java |
private Runnable decorateTask(Runnable task, boolean isRepeatingTask) {
Runnable result = TaskUtils.decorateTaskWithErrorHandler(task, this.errorHandler, isRepeatingTask);
if (this.enterpriseConcurrentScheduler) {
result = ManagedTaskBuilder.buildManagedTask(result, task.toString());
... | java |
public void registerMbeans() {
ServerAdminMBean serverAdministrationBean = new ServerAdmin();
try {
mbeanServer.registerMBean(serverAdministrationBean,
JMXUtils.getObjectName(jmxConfig.getContextName(), "ServerAdmin"));
} catch (InstanceAlreadyExistsException e) ... | java |
public static CommandProcessor getInstance() {
if (null == instance) {
synchronized (CommandProcessor.class) {
if (null == instance) {
instance = new CommandProcessor();
}
}
}
return instance;
} | java |
private static Configuration getDefault(){
Configuration config = new Configuration();
config.addHandler(new ConsoleAuditHandler());
config.setMetaData(new DummyMetaData());
config.setLayout(new SimpleLayout());
config.addProperty("log.file.location", "user.dir");
return ... | java |
public void addHandler(Handler handler) {
if (null == handlers) {
handlers = new ArrayList<>();
}
handlers.add(handler);
} | java |
public void addProperty(String key, String value) {
if (null == properties) {
properties = new HashMap<>();
}
properties.put(key, value);
} | java |
public boolean audit(Class<?> clazz, Method method, Object[] args) {
return audit(new AnnotationAuditEvent(clazz, method, args));
} | java |
public static IAuditManager getInstance() {
IAuditManager result = auditManager;
if(result == null) {
synchronized (AuditManager.class) {
result = auditManager;
if(result == null) {
Context.init();
auditManager = result ... | java |
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
if (triggerContext.lastScheduledExecutionTime() == null) {
return new Date(System.currentTimeMillis() + this.initialDelay);
} else if (this.fixedRate) {
return new Date(triggerContext.lastScheduledExecut... | java |
public String convertDateToString(final Date date) {
if (date == null) {
return null;
}
return dateFormat.get().format(date);
} | java |
public static Schedulers newThreadPoolScheduler(int poolSize) {
createSingleton();
Schedulers.increaseNoOfSchedullers();
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
CustomizableThreadFactory factory = new CustomizableThreadFactory();
scheduler.initializeExe... | java |
public static Schedulers stopAll() {
createSingleton();
if (instance.runningSchedullers.isEmpty()) {
throw new IllegalStateException("No schedulers available.");
}
for (Entry<String, ScheduledFuture<?>> entry : instance.runningSchedullers.entrySet()) {
ScheduledF... | java |
public List<I> getNewInstanceList(String[] clsssList) {
List<I> instances = new ArrayList<>();
for (String className : clsssList) {
I instance = new ReflectUtil<I>().getNewInstance(className);
instances.add(instance);
}
return instances;
} | java |
public void update(Date lastScheduledExecutionTime, Date lastActualExecutionTime, Date lastCompletionTime) {
this.lastScheduledExecutionTime = lastScheduledExecutionTime;
this.lastActualExecutionTime = lastActualExecutionTime;
this.lastCompletionTime = lastCompletionTime;
} | java |
public static DelegatingErrorHandlingRunnable decorateTaskWithErrorHandler(Runnable task,
ErrorHandler errorHandler, boolean isRepeatingTask) {
if (task instanceof DelegatingErrorHandlingRunnable) {
return (DelegatingErrorHandlingRunnable) task;
}
ErrorHandler eh = errorH... | java |
public static Date addDate(final Date date, final Integer different) {
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, different);
return cal.getTime();
} | java |
private static CopyStreamListener createListener() {
return new CopyStreamListener() {
private long megsTotal = 0;
// @Override
@Override
public void bytesTransferred(CopyStreamEvent event) {
bytesTransferred(event.getTotalBytesTransferred(), even... | java |
public static void info(Object... message) {
StringBuilder builder = new StringBuilder(APP_INFO);
for (Object object : message) {
builder.append(object.toString());
}
infoStream.println(builder.toString());
} | java |
public static void warn(Object... message) {
StringBuilder builder = new StringBuilder(APP_WARN);
for (Object object : message) {
builder.append(object.toString());
}
warnStream.println(builder.toString());
} | java |
public static void warn(final Object message, final Throwable t) {
warnStream.println(APP_WARN + message.toString());
warnStream.println(stackTraceToString(t));
} | java |
public static void error(Object... message) {
StringBuilder builder = new StringBuilder(APP_ERROR);
for (Object object : message) {
builder.append(object.toString());
}
errorStream.println(builder.toString());
} | java |
public static void error(final Object message, final Throwable t) {
errorStream.println(APP_ERROR + message.toString());
errorStream.println(stackTraceToString(t));
} | java |
static ObjectName getObjectName(String type, String name) {
try {
return new ObjectName(JMXUtils.class.getPackage().getName() + ":type=" + type + ",name=" + name);
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java |
void printBanner() {
PrintStream printStream = System.out;
for (String lineLocal : BANNER) {
printStream.println(lineLocal);
}
printStream.print(line);
String version = Audit4jBanner.class.getPackage().getImplementationVersion();
if (version == null) {
... | java |
protected File[] getAvailableFiles(final String logFileLocation, final Date maxDate) {
File dir = new File(logFileLocation);
return dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String fileName) {
boolean extentionMatch = fileNam... | java |
private Date fileCreatedDate(String fileName) {
String[] splittedWithoutExtention = fileName.split(".");
String fileNameWithoutExtention = splittedWithoutExtention[0];
String[] splittedWithoutPrefix = fileNameWithoutExtention.split("-");
String fileNameDateInStr = splittedWithoutPrefix[1... | java |
static ConfigurationStream resolveConfigFileAsStream(String configFilePath) throws ConfigurationException {
InputStream fileStream;
String fileExtention;
if (configFilePath != null) {
if (new File(configFilePath).isDirectory()) {
String path = scanConfigFile(... | java |
static String scanConfigFile(String dirPath) throws ConfigurationException {
String filePath = dirPath + File.separator + CONFIG_FILE_NAME + ".";
String fullFilePath;
// Scan for Yaml file
if (AuditUtil.isFileExists(filePath + YML_EXTENTION)) {
fullFilePath = filePath + YML... | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.