index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/servlet/RackResponsePropagator.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.rack.servlet;
import com.google.common.base.Throwables;
import com.squareup.rack.RackResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
/**
* Writes a {@link RackResponse} onto an {@link HttpServletResponse}.
*/
public class RackResponsePropagator {
private static final String RACK_INTERNAL_HEADER_PREFIX = "rack.";
public void propagate(RackResponse rackResponse, HttpServletResponse response) {
propagateStatus(rackResponse, response);
propagateHeaders(rackResponse, response);
propagateBody(rackResponse, response);
}
private void propagateStatus(RackResponse rackResponse, HttpServletResponse response) {
response.setStatus(rackResponse.getStatus());
}
private void propagateHeaders(RackResponse rackResponse, HttpServletResponse response) {
for (Map.Entry<String, String> header : rackResponse.getHeaders().entrySet()) {
if (shouldPropagateHeaderToClient(header)) {
for (String val : header.getValue().split("\n")) {
response.addHeader(header.getKey(), val);
}
}
}
try {
response.flushBuffer();
} catch (IOException e) {
Throwables.propagate(e);
}
}
private boolean shouldPropagateHeaderToClient(Map.Entry<String, String> header) {
return !header.getKey().startsWith(RACK_INTERNAL_HEADER_PREFIX);
}
private void propagateBody(RackResponse rackResponse, HttpServletResponse response) {
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
} catch (IOException e) {
Throwables.propagate(e);
}
Iterator<byte[]> body = rackResponse.getBody();
while (body.hasNext()) {
try {
outputStream.write(body.next());
} catch (IOException e) {
Throwables.propagate(e);
}
}
try {
outputStream.flush();
} catch (IOException e) {
Throwables.propagate(e);
}
}
}
| 5,600 |
0 | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/servlet/RackEnvironmentBuilder.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.rack.servlet;
import com.google.common.base.CharMatcher;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.squareup.rack.RackEnvironment;
import com.squareup.rack.RackErrors;
import com.squareup.rack.RackInput;
import com.squareup.rack.RackLogger;
import com.squareup.rack.io.TempfileBufferedInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Strings.nullToEmpty;
import static com.google.common.base.Throwables.propagate;
import static com.squareup.rack.RackEnvironment.CONTENT_LENGTH;
import static com.squareup.rack.RackEnvironment.CONTENT_TYPE;
import static com.squareup.rack.RackEnvironment.HTTP_HEADER_PREFIX;
import static com.squareup.rack.RackEnvironment.MINECART_HTTP_SERVLET_REQUEST;
import static com.squareup.rack.RackEnvironment.PATH_INFO;
import static com.squareup.rack.RackEnvironment.QUERY_STRING;
import static com.squareup.rack.RackEnvironment.RACK_ERRORS;
import static com.squareup.rack.RackEnvironment.RACK_HIJACK;
import static com.squareup.rack.RackEnvironment.RACK_INPUT;
import static com.squareup.rack.RackEnvironment.RACK_LOGGER;
import static com.squareup.rack.RackEnvironment.RACK_MULTIPROCESS;
import static com.squareup.rack.RackEnvironment.RACK_MULTITHREAD;
import static com.squareup.rack.RackEnvironment.RACK_RUN_ONCE;
import static com.squareup.rack.RackEnvironment.RACK_URL_SCHEME;
import static com.squareup.rack.RackEnvironment.RACK_VERSION;
import static com.squareup.rack.RackEnvironment.REQUEST_METHOD;
import static com.squareup.rack.RackEnvironment.SCRIPT_NAME;
import static com.squareup.rack.RackEnvironment.SERVER_NAME;
import static com.squareup.rack.RackEnvironment.SERVER_PORT;
import static java.util.Collections.list;
/**
* <p>Transforms an {@link HttpServletRequest} into a {@link RackEnvironment}.</p>
*
* <p>Conforms to version 1.2 of the Rack specification</p>.
*
* @see <a href="http://rack.rubyforge.org/doc/SPEC.html">The Rack Specification</a>
* @see <a href="https://tools.ietf.org/html/rfc3875#section-4.1.18">RFC 3875, section 4.1.18</a>
* @see <a href="http://blog.phusion.nl/2013/01/23/the-new-rack-socket-hijacking-api/">The Rack
* socket hijacking API</a>
*/
public class RackEnvironmentBuilder {
// We conform to version 1.2 of the Rack specification.
// Note that this number is completely different than the gem version of rack (lowercase):
// for example, the rack-1.5.2 gem ships with handlers that conform to version 1.2 of the Rack
// specification.
private static final List<Integer> VERSION_1_2 = ImmutableList.of(1, 2);
private static final Logger RACK_ERRORS_LOGGER = LoggerFactory.getLogger(RackErrors.class);
private static final Logger RACK_LOGGER_LOGGER = LoggerFactory.getLogger(RackLogger.class);
private static final Joiner COMMA = Joiner.on(',');
private static final CharMatcher DASH = CharMatcher.is('-');
public RackEnvironment build(HttpServletRequest request) {
ImmutableMap.Builder<String, Object> content = ImmutableMap.builder();
content.put(REQUEST_METHOD, request.getMethod());
content.put(SCRIPT_NAME, request.getServletPath());
content.put(PATH_INFO, nullToEmpty(request.getPathInfo()));
content.put(QUERY_STRING, nullToEmpty(request.getQueryString()));
content.put(SERVER_NAME, request.getServerName());
content.put(SERVER_PORT, String.valueOf(request.getServerPort()));
content.put(RACK_VERSION, VERSION_1_2);
content.put(RACK_URL_SCHEME, request.getScheme().toLowerCase());
content.put(RACK_INPUT, rackInput(request));
content.put(RACK_ERRORS, new RackErrors(RACK_ERRORS_LOGGER));
content.put(RACK_LOGGER, new RackLogger(RACK_LOGGER_LOGGER));
content.put(RACK_MULTITHREAD, true);
content.put(RACK_MULTIPROCESS, true);
content.put(RACK_RUN_ONCE, false);
content.put(RACK_HIJACK, false);
// Extra things we add that aren't in the Rack specification:
content.put(MINECART_HTTP_SERVLET_REQUEST, request);
// HTTP headers; Multimap acrobatics ensure we normalize capitalization and
// punctuation differences early
Enumeration<String> headerNames = request.getHeaderNames();
ImmutableListMultimap.Builder<String, Object> headers = ImmutableListMultimap.builder();
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
headers.putAll(rackHttpHeaderKey(name), list(request.getHeaders(name)));
}
for (Map.Entry<String, Collection<Object>> header : headers.build().asMap().entrySet()) {
content.put(header.getKey(), COMMA.join(header.getValue()));
}
// Request attributes
// This will include attributes like javax.servlet.request.X509Certificate
Enumeration<String> attributeNames = request.getAttributeNames();
while (attributeNames.hasMoreElements()) {
String name = attributeNames.nextElement();
content.put(name, request.getAttribute(name));
}
return new RackEnvironment(content.build());
}
private RackInput rackInput(HttpServletRequest request) {
try {
return new RackInput(new TempfileBufferedInputStream(request.getInputStream()));
} catch (IOException e) {
throw propagate(e);
}
}
private String rackHttpHeaderKey(String headerName) {
String transformed = DASH.replaceFrom(headerName.toUpperCase(), "_");
if (transformed.equals(CONTENT_LENGTH) || transformed.equals(CONTENT_TYPE)) {
return transformed;
} else {
return HTTP_HEADER_PREFIX + transformed;
}
}
}
| 5,601 |
0 | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/servlet/package-info.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The {@link com.squareup.rack.servlet.RackServlet} implementation,
* with supporting Servlet adapters.
*/
package com.squareup.rack.servlet; | 5,602 |
0 | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/io/TempfileBufferedInputStream.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.rack.io;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
/**
* <p>Buffers an {@link InputStream}, making it effectively rewindable.</p>
*
* <p>Operates in-memory, just like a {@link java.io.BufferedInputStream}, up to a size threshold,
* then begins buffering to disk once that size threshold is crossed.</p>
*
* <p>As compared with Guava's {@link com.google.common.io.FileBackedOutputStream}, does not require
* processing the entire stream before offering its contents to client code.</p>
*
* <p>Uses the default temporary-file directory, which you can control by setting the
* {@code java.io.tmpdir} system property.</p>
*
* @see File#createTempFile(String, String)
*/
public class TempfileBufferedInputStream extends InputStream {
private static final int DEFAULT_THRESHOLD = 1024 * 1024;
private final InputStream source;
private long readHead;
private long writeHead;
private long markPos;
private Buffer buffer;
/**
* Buffers a source InputStream, dropping to disk once a default size threshold has been crossed.
*
* @param source the InputStream to buffer.
*/
public TempfileBufferedInputStream(InputStream source) {
this(source, DEFAULT_THRESHOLD);
}
/**
* Buffers a source InputStream, dropping to disk once the given size threshold has been crossed.
*
* @param source the InputStream to buffer.
* @param threshold the size threshold beyond which to buffer to disk.
*/
public TempfileBufferedInputStream(InputStream source, int threshold) {
Preconditions.checkNotNull(source);
this.source = source;
this.buffer = new MemoryBuffer(threshold);
}
@Override public int read() throws IOException {
byte[] bytes = new byte[1];
int read = read(bytes);
return (read > 0) ? bytes[0] & 0xff : -1;
}
@Override public int read(byte[] bytes) throws IOException {
return read(bytes, 0, bytes.length);
}
@Override public int read(byte[] bytes, int offset, int length) throws IOException {
int bytesRead;
long cachedReadable = writeHead - readHead;
if (cachedReadable > 0) {
int bytesToTransfer = Math.min(length, (int) cachedReadable);
buffer.replay(bytes, offset, bytesToTransfer);
bytesRead = bytesToTransfer;
readHead += bytesRead;
} else {
bytesRead = source.read(bytes, offset, length);
if (bytesRead > 0) {
if (buffer.wouldOverflow(writeHead + bytesRead)) {
buffer = buffer.embiggened();
}
buffer.append(bytes, offset, bytesRead);
writeHead += bytesRead;
readHead += bytesRead;
}
}
return bytesRead;
}
@Override public synchronized void reset() throws IOException {
readHead = markPos;
buffer.sync();
}
@Override public synchronized void mark(int i) {
markPos = readHead;
}
@Override public boolean markSupported() {
return true;
}
@Override public void close() throws IOException {
try {
buffer.close();
} catch (IOException e) {
// safe to ignore, we're just closing a buffer
}
source.close();
}
interface Buffer {
void replay(byte[] bytes, int offset, int length) throws IOException;
void append(byte[] bytes, int offset, int length) throws IOException;
boolean wouldOverflow(long length);
Buffer embiggened() throws IOException;
void sync() throws IOException;
void close() throws IOException;
}
class MemoryBuffer implements Buffer {
private final ByteArrayBuffer cacheOutputStream;
private final int threshold;
public MemoryBuffer(int threshold) {
this.threshold = threshold;
this.cacheOutputStream = new ByteArrayBuffer();
}
public void replay(byte[] bytes, int offset, int bytesToTransfer) {
byte[] cacheBytes = cacheOutputStream.getBuffer();
// Cast is safe because threshold is an int. (Arrays can only have integer indexes.)
System.arraycopy(cacheBytes, (int) readHead, bytes, offset, bytesToTransfer);
}
@Override public void append(byte[] bytes, int offset, int length) {
cacheOutputStream.write(bytes, offset, length);
}
@Override public boolean wouldOverflow(long length) {
return length > threshold;
}
@Override public Buffer embiggened() throws IOException {
return new FileBackedBuffer(cacheOutputStream);
}
@Override public void sync() {
}
@Override public void close() {
}
}
private class FileBackedBuffer implements Buffer {
private final BufferedOutputStream outputStream;
private final FileChannel inputChannel;
private MappedByteBuffer mappedByteBuffer;
public FileBackedBuffer(ByteArrayBuffer baos) throws IOException {
File tempFile = File.createTempFile("stream-buffer", ".buf");
try {
FileOutputStream fileOutputStream = createFileOutputStream(tempFile);
outputStream = new BufferedOutputStream(fileOutputStream);
outputStream.write(baos.getBuffer(), 0, baos.getLength());
inputChannel = createFileInputStream(tempFile).getChannel();
} finally {
//noinspection ResultOfMethodCallIgnored
tempFile.delete();
}
}
@Override public void replay(byte[] bytes, int offset, int length) throws IOException {
if (mappedByteBuffer == null) {
mappedByteBuffer = inputChannel.map(FileChannel.MapMode.READ_ONLY, 0, writeHead);
}
// This cast is only unsafe if writeHead is > MAX_INT, i.e., the file is > 2GB. Unlikely?
mappedByteBuffer.position((int) readHead);
mappedByteBuffer.get(bytes, offset, length);
}
@Override public void append(byte[] bytes, int offset, int length) throws IOException {
outputStream.write(bytes, offset, length);
}
@Override public boolean wouldOverflow(long length) {
return false;
}
@Override public Buffer embiggened() {
throw new UnsupportedOperationException();
}
@Override public void sync() throws IOException {
outputStream.flush();
mappedByteBuffer = null;
}
@Override public void close() throws IOException {
mappedByteBuffer = null;
try {
outputStream.close();
} finally {
inputChannel.close();
}
}
}
@VisibleForTesting FileInputStream createFileInputStream(File tempFile)
throws FileNotFoundException {
return new FileInputStream(tempFile);
}
@VisibleForTesting FileOutputStream createFileOutputStream(File tempFile)
throws FileNotFoundException {
return new FileOutputStream(tempFile);
}
}
| 5,603 |
0 | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/io/package-info.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Support for rewinding the {@link javax.servlet.ServletInputStream}, as required by the Rack
* specification.
*/
package com.squareup.rack.io; | 5,604 |
0 | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/io/ByteArrayBuffer.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.rack.io;
import java.io.ByteArrayOutputStream;
/**
* An in-memory {@link java.io.OutputStream} that provides access to its internal buffer.
*/
public class ByteArrayBuffer extends ByteArrayOutputStream {
/**
* Creates a new buffer with the default initial size.
*/
public ByteArrayBuffer() {
super();
}
/**
* Creates an new buffer with the given initial size.
*
* @param initialSize the initial size of the internal buffer.
*/
public ByteArrayBuffer(int initialSize) {
super(initialSize);
}
/**
* Like {@link #toByteArray()}, but returns a reference to the internal buffer itself rather than
* allocating more memory and returning a copy.
*
* @return the current contents of the internal buffer.
*/
public byte[] getBuffer() {
return buf;
}
/**
* @return the currently-filled length of the internal buffer.
*/
public int getLength() {
return count;
}
/**
* Logically adjusts the currently-filled length of internal buffer.
*
* @param length the newly desired length.
*/
public void setLength(int length) {
count = length;
}
}
| 5,605 |
0 | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/jruby/JRubyRackInput.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.rack.jruby;
import com.squareup.rack.RackInput;
import java.io.IOException;
import org.jcodings.Encoding;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
/**
* <p>Adapts a {@link com.squareup.rack.RackInput} into Ruby-space.</p>
*
* <p>Is primarily responsible for translating Java byte arrays into Ruby Strings with
* {@code ASCII-8BIT} encoding.</p>
*/
public class JRubyRackInput extends RubyObject {
private RackInput rackInput;
private Encoding ascii8bitEncoding;
private static final ObjectAllocator ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new JRubyRackInput(runtime, klass);
}
};
private static RubyClass getRackInputClass(Ruby runtime) {
RubyModule module = runtime.getOrCreateModule("RackServlet");
RubyClass klass = module.getClass("RackInput");
if (klass == null) {
klass = module.defineClassUnder("RackInput", runtime.getObject(), ALLOCATOR);
klass.defineAnnotatedMethods(JRubyRackInput.class);
}
return klass;
}
JRubyRackInput(Ruby runtime, RubyClass klass) {
super(runtime, klass);
}
/**
* Creates a Ruby IO object that delegates to the given {@link RackInput}.
*
* @param runtime the Ruby runtime that will host this instance.
* @param rackInput the backing data source.
*/
public JRubyRackInput(Ruby runtime, RackInput rackInput) {
super(runtime, getRackInputClass(runtime));
this.rackInput = rackInput;
this.ascii8bitEncoding = runtime.getEncodingService().getAscii8bitEncoding();
}
@JRubyMethod public IRubyObject gets() {
try {
return toRubyString(rackInput.gets());
} catch (IOException e) {
throw getRuntime().newIOErrorFromException(e);
}
}
@JRubyMethod public IRubyObject each(ThreadContext context, Block block) {
IRubyObject nil = getRuntime().getNil();
IRubyObject line;
while ((line = gets()) != nil) {
block.yield(context, line);
}
return nil;
}
@JRubyMethod(optional = 1) public IRubyObject read(ThreadContext context, IRubyObject[] args) {
Integer length = null;
if (args.length > 0) {
long arg = args[0].convertToInteger("to_i").getLongValue();
length = (int) Math.min(arg, Integer.MAX_VALUE);
}
try {
return toRubyString(rackInput.read(length));
} catch (IOException e) {
throw getRuntime().newIOErrorFromException(e);
}
}
@JRubyMethod public IRubyObject rewind() {
try {
rackInput.rewind();
} catch (IOException e) {
throw getRuntime().newIOErrorFromException(e);
}
return getRuntime().getNil();
}
private IRubyObject toRubyString(byte[] bytes) {
if (bytes == null) {
return getRuntime().getNil();
} else {
return RubyString.newString(getRuntime(), new ByteList(bytes, ascii8bitEncoding));
}
}
}
| 5,606 |
0 | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/jruby/JRubyRackBodyIterator.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.rack.jruby;
import com.google.common.collect.AbstractIterator;
import org.jruby.RubyEnumerator;
import org.jruby.exceptions.RaiseException;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
/**
* <p>Adapts a (RubyObject) Enumerable into Java-space.</p>
*
* <p>Attempts to close the Enumerable after iteration where possible.</p>
*/
public class JRubyRackBodyIterator extends AbstractIterator<byte[]> {
private final IRubyObject body;
private final ThreadContext threadContext;
private final RubyEnumerator enumerator;
/**
* Creates a byte array Iterator backed by the given Ruby Enumerable.
*
* @param body the backing Enumerable.
*/
public JRubyRackBodyIterator(IRubyObject body) {
this.body = body;
this.threadContext = body.getRuntime().getThreadService().getCurrentContext();
this.enumerator = (RubyEnumerator) body.callMethod(threadContext, "to_enum");
}
@Override protected byte[] computeNext() {
try {
return enumerator.callMethod(threadContext, "next").convertToString().getBytes();
} catch (RaiseException e) {
close();
return endOfData();
}
}
private void close() {
if (body.respondsTo("close")) {
body.callMethod(threadContext, "close");
}
}
}
| 5,607 |
0 | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/jruby/JRubyRackApplication.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.rack.jruby;
import com.squareup.rack.RackApplication;
import com.squareup.rack.RackEnvironment;
import com.squareup.rack.RackInput;
import com.squareup.rack.RackResponse;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyHash;
import org.jruby.internal.runtime.ThreadService;
import org.jruby.runtime.builtin.IRubyObject;
import static org.jruby.RubyHash.newHash;
/**
* Adapts a (RubyObject) Rack application into Java-space.
*/
public class JRubyRackApplication implements RackApplication {
private final IRubyObject application;
private final Ruby runtime;
private final ThreadService threadService;
/**
* <p>Creates a {@link RackApplication} that delegates to the given Ruby Rack application.</p>
*
* <p>To obtain the necessary {@link IRubyObject}, you can create a JRuby
* {@link org.jruby.embed.ScriptingContainer} and {@link org.jruby.embed.ScriptingContainer#parse}
* and {@link org.jruby.embed.EmbedEvalUnit#run()} your Ruby code. See our examples for concrete
* code.</p>
*
* @param application the Ruby Rack application.
*/
public JRubyRackApplication(IRubyObject application) {
this.application = application;
this.runtime = application.getRuntime();
this.threadService = runtime.getThreadService();
}
/**
* Calls the delegate Rack application, translating into and back out of the JRuby interpreter.
*
* @param environment the Rack environment
* @return the Rack response
*/
@Override public RackResponse call(RackEnvironment environment) {
RubyHash environmentHash = convertToRubyHash(environment.entrySet());
RubyArray response = callRackApplication(environmentHash);
return convertToJavaRackResponse(response);
}
private RubyHash convertToRubyHash(Set<Map.Entry<String, Object>> entries) {
RubyHash hash = newHash(runtime);
for (Map.Entry<String, Object> entry : entries) {
String key = entry.getKey();
Object value = entry.getValue();
if (key.equals("rack.input")) {
value = new JRubyRackInput(runtime, (RackInput) value);
}
if (key.equals("rack.version")) {
value = convertToRubyArray((List<Integer>) value);
}
hash.put(key, value);
}
return hash;
}
private RubyArray convertToRubyArray(List<Integer> list) {
RubyArray array = RubyArray.newEmptyArray(runtime);
array.addAll(list);
return array;
}
private RubyArray callRackApplication(RubyHash rubyHash) {
return (RubyArray) application.callMethod(threadService.getCurrentContext(), "call", rubyHash);
}
private RackResponse convertToJavaRackResponse(RubyArray response) {
int status = Integer.parseInt(response.get(0).toString(), 10);
Map headers = (Map) response.get(1);
IRubyObject body = (IRubyObject) response.get(2);
return new RackResponse(status, headers, new JRubyRackBodyIterator(body));
}
}
| 5,608 |
0 | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack | Create_ds/rack-servlet/core/src/main/java/com/squareup/rack/jruby/package-info.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The {@link com.squareup.rack.jruby.JRubyRackApplication} implementation,
* with supporting JRuby adapters.
*/
package com.squareup.rack.jruby; | 5,609 |
0 | Create_ds/rack-servlet/integration/src/test/java/com/squareup/rack | Create_ds/rack-servlet/integration/src/test/java/com/squareup/rack/integration/HeaderFlushingTest.java | package com.squareup.rack.integration;
import com.squareup.rack.jruby.JRubyRackApplication;
import com.squareup.rack.servlet.RackServlet;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jruby.embed.ScriptingContainer;
import org.jruby.runtime.builtin.IRubyObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.jruby.embed.PathType.CLASSPATH;
import static org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY;
public class HeaderFlushingTest {
private HttpClient client;
private HttpHost localhost;
private ExampleServer server;
@Before public void setUp() throws Exception {
// Silence logging.
System.setProperty(DEFAULT_LOG_LEVEL_KEY, "WARN");
// Build the Rack servlet.
ScriptingContainer ruby = new ScriptingContainer();
IRubyObject application = ruby.parse(CLASSPATH, "application.rb").run();
RackServlet servlet = new RackServlet(new JRubyRackApplication(application));
server = new ExampleServer(servlet, "/*");
server.start();
client = new DefaultHttpClient();
localhost = new HttpHost("localhost", server.getPort());
}
@After public void tearDown() throws Exception {
server.stop();
}
@Test public void flushingHeaders() throws IOException {
HttpResponse response = get("/legen-wait-for-it");
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
assertThat(response.getFirstHeader("Transfer-Encoding").getValue()).isEqualTo("chunked");
InputStream stream = response.getEntity().getContent();
assertThat(stream.available()).isEqualTo(0);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
response.getEntity().writeTo(buffer);
assertThat(buffer.toString()).isEqualTo("dary!");
}
private HttpResponse get(String path) throws IOException {
return client.execute(localhost, new HttpGet(path));
}
}
| 5,610 |
0 | Create_ds/rack-servlet/integration/src/test/java/com/squareup/rack | Create_ds/rack-servlet/integration/src/test/java/com/squareup/rack/integration/MultiValuedHeadersTest.java | package com.squareup.rack.integration;
import com.squareup.rack.jruby.JRubyRackApplication;
import com.squareup.rack.servlet.RackServlet;
import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jruby.embed.ScriptingContainer;
import org.jruby.runtime.builtin.IRubyObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.jruby.embed.PathType.CLASSPATH;
import static org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY;
public class MultiValuedHeadersTest {
private HttpClient client;
private HttpHost localhost;
private ExampleServer server;
@Before public void setUp() throws Exception {
// Silence logging.
System.setProperty(DEFAULT_LOG_LEVEL_KEY, "WARN");
// Build the Rack servlet.
ScriptingContainer ruby = new ScriptingContainer();
IRubyObject application = ruby.parse(CLASSPATH, "application.rb").run();
RackServlet servlet = new RackServlet(new JRubyRackApplication(application));
server = new ExampleServer(servlet, "/*");
server.start();
client = new DefaultHttpClient();
localhost = new HttpHost("localhost", server.getPort());
}
@After public void tearDown() throws Exception {
server.stop();
}
@Test public void setMultipleCookies() throws IOException {
HttpResponse response = get("/set-multiple-cookies");
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
Header[] cookies = response.getHeaders("Set-Cookie");
assertThat(cookies).hasSize(2);
}
private HttpResponse get(String path) throws IOException {
return client.execute(localhost, new HttpGet(path));
}
}
| 5,611 |
0 | Create_ds/rack-servlet/integration/src/main/java/com/squareup/rack | Create_ds/rack-servlet/integration/src/main/java/com/squareup/rack/integration/ExampleServer.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.rack.integration;
import javax.servlet.Servlet;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class ExampleServer {
private final Server server;
public ExampleServer(Servlet servlet, String urlPattern) {
ServletHolder holder = new ServletHolder(servlet);
ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(holder, urlPattern);
server = new Server(0);
server.setHandler(handler);
}
public void start() throws Exception {
server.start();
}
public int getPort() {
Connector[] connectors = server.getConnectors();
NetworkConnector connector = (NetworkConnector) connectors[0];
return connector.getLocalPort();
}
public void stop() throws Exception {
server.stop();
}
}
| 5,612 |
0 | Create_ds/rack-servlet/examples/jetty/src/test/java/com/squareup/rack/examples | Create_ds/rack-servlet/examples/jetty/src/test/java/com/squareup/rack/examples/jetty/ExampleServerTest.java | package com.squareup.rack.examples.jetty;
import com.squareup.rack.jruby.JRubyRackApplication;
import com.squareup.rack.servlet.RackServlet;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.Servlet;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.jruby.embed.ScriptingContainer;
import org.jruby.runtime.builtin.IRubyObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY;
public class ExampleServerTest {
private HttpClient client;
private HttpHost localhost;
private ExampleServer server;
@Before public void setUp() throws Exception {
// Silence logging.
System.setProperty(DEFAULT_LOG_LEVEL_KEY, "WARN");
// Build the Rack servlet.
ScriptingContainer ruby = new ScriptingContainer();
IRubyObject application = ruby.parse("lambda { |env| [200, {}, ['Hello, World!']] }").run();
RackServlet servlet = new RackServlet(new JRubyRackApplication(application));
server = new ExampleServer(servlet, "/*");
server.start();
client = new DefaultHttpClient();
localhost = new HttpHost("localhost", server.getPort());
}
@After public void tearDown() throws Exception {
server.stop();
}
@Test public void get() throws IOException {
HttpResponse response = get("/anything");
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
assertThat(response.getEntity().getContent()).hasContentEqualTo(streamOf("Hello, World!"));
}
private HttpResponse get(String path) throws IOException {
return client.execute(localhost, new HttpGet(path));
}
private InputStream streamOf(String contents) {
return new ByteArrayInputStream(contents.getBytes());
}
public static class ExampleServer {
private final Server server;
public ExampleServer(Servlet servlet, String urlPattern) {
ServletHolder holder = new ServletHolder(servlet);
ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(holder, urlPattern);
server = new Server(0);
server.setHandler(handler);
}
public void start() throws Exception {
server.start();
}
public int getPort() {
Connector[] connectors = server.getConnectors();
NetworkConnector connector = (NetworkConnector) connectors[0];
return connector.getLocalPort();
}
public void stop() throws Exception {
server.stop();
}
}
}
| 5,613 |
0 | Create_ds/rack-servlet/examples/guice-servlet/src/test/java/com/squareup/rack/examples | Create_ds/rack-servlet/examples/guice-servlet/src/test/java/com/squareup/rack/examples/guice/ExampleServerTest.java | package com.squareup.rack.examples.guice;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.google.inject.servlet.GuiceFilter;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;
import com.squareup.rack.jruby.JRubyRackApplication;
import com.squareup.rack.servlet.RackServlet;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.jruby.embed.ScriptingContainer;
import org.jruby.runtime.builtin.IRubyObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY;
public class ExampleServerTest {
private HttpClient client;
private HttpHost localhost;
private ExampleServer server;
@Before public void setUp() throws Exception {
// Silence logging.
System.setProperty(DEFAULT_LOG_LEVEL_KEY, "WARN");
server = new ExampleServer(new RackModule());
server.start();
client = new DefaultHttpClient();
localhost = new HttpHost("localhost", server.getPort());
}
@After public void tearDown() throws Exception {
server.stop();
}
@Test public void get() throws IOException {
HttpResponse response = get("/anything");
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
assertThat(response.getEntity().getContent()).hasContentEqualTo(streamOf("Hello, World!"));
}
private HttpResponse get(String path) throws IOException {
return client.execute(localhost, new HttpGet(path));
}
private InputStream streamOf(String contents) {
return new ByteArrayInputStream(contents.getBytes());
}
private static class ExampleServer {
private final Server server;
public ExampleServer(Module... modules) {
ServletContextHandler handler = new ServletContextHandler();
handler.setContextPath("/");
handler.addEventListener(new GuiceInjectorServletContextListener(modules));
handler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
handler.addServlet(DefaultServlet.class, "/");
server = new Server(0);
server.setHandler(handler);
}
public void start() throws Exception {
server.start();
}
public int getPort() {
Connector[] connectors = server.getConnectors();
NetworkConnector connector = (NetworkConnector) connectors[0];
return connector.getLocalPort();
}
public void stop() throws Exception {
server.stop();
}
}
private static class GuiceInjectorServletContextListener extends GuiceServletContextListener {
private final Injector injector;
public GuiceInjectorServletContextListener(Module... modules) {
injector = Guice.createInjector(modules);
}
@Override protected Injector getInjector() {
return injector;
}
}
private static class RackModule extends ServletModule {
@Override protected void configureServlets() {
serve("/*").with(RackServlet.class);
}
@Provides @Singleton RackServlet provideRackServlet(IRubyObject application) {
return new RackServlet(new JRubyRackApplication(application));
}
@Provides IRubyObject provideApplication() {
ScriptingContainer ruby = new ScriptingContainer();
return ruby.parse("lambda { |env| [200, {}, ['Hello, World!']] }").run();
}
}
} | 5,614 |
0 | Create_ds/rack-servlet/examples/dropwizard/src/test/java/com/squareup/rack/examples | Create_ds/rack-servlet/examples/dropwizard/src/test/java/com/squareup/rack/examples/dropwizard/ExampleServiceTest.java | package com.squareup.rack.examples.dropwizard;
import com.yammer.dropwizard.config.Configuration;
import com.yammer.dropwizard.testing.junit.DropwizardServiceRule;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import static com.google.common.io.Resources.getResource;
import static org.fest.assertions.api.Assertions.assertThat;
public class ExampleServiceTest {
@ClassRule public static final DropwizardServiceRule<Configuration> RULE =
new DropwizardServiceRule<Configuration>(ExampleService.class,
getResource("example.yaml").getFile());
private HttpClient client;
private HttpHost localhost;
@Before public void setUp() {
client = new DefaultHttpClient();
localhost = new HttpHost("localhost", RULE.getLocalPort());
}
@Test public void getRackHello() throws IOException {
HttpResponse response = get("/rack/hello");
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
assertThat(response.getEntity().getContent()).hasContentEqualTo(streamOf("Hello, World!"));
}
private HttpResponse get(String path) throws IOException {
return client.execute(localhost, new HttpGet(path));
}
private InputStream streamOf(String contents) {
return new ByteArrayInputStream(contents.getBytes());
}
}
| 5,615 |
0 | Create_ds/rack-servlet/examples/dropwizard/src/main/java/com/squareup/rack/examples | Create_ds/rack-servlet/examples/dropwizard/src/main/java/com/squareup/rack/examples/dropwizard/ExampleService.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.rack.examples.dropwizard;
import com.google.common.io.Resources;
import com.squareup.rack.examples.dropwizard.health.FakeHealthCheck;
import com.squareup.rack.examples.dropwizard.resources.EmptyResource;
import com.squareup.rack.jruby.JRubyRackApplication;
import com.squareup.rack.servlet.RackServlet;
import com.yammer.dropwizard.Service;
import com.yammer.dropwizard.config.Bootstrap;
import com.yammer.dropwizard.config.Configuration;
import com.yammer.dropwizard.config.Environment;
import java.io.IOException;
import org.jruby.embed.ScriptingContainer;
import org.jruby.runtime.builtin.IRubyObject;
import static com.google.common.base.Throwables.propagate;
import static com.google.common.io.Resources.getResource;
import static java.nio.charset.Charset.defaultCharset;
public class ExampleService extends Service<Configuration> {
@Override public void initialize(Bootstrap<Configuration> bootstrap) {
// Nothing to do here.
}
@Override public void run(Configuration config, Environment environment) {
// Suppress the "THIS SERVICE HAS NO HEALTHCHECKS" warning.
// A real service would have proper health checks.
environment.addHealthCheck(new FakeHealthCheck());
// Suppress the "ResourceConfig instance does not contain any root resource classes" error.
// A real service would probably provide a Jersey resource or two.
environment.addResource(EmptyResource.class);
// Here's the interesting part:
// Mount the Rack application defined in the config.ru file on the classpath at /rack.
environment.addServlet(createRackServlet(), "/rack/*");
}
private RackServlet createRackServlet() {
return new RackServlet(new JRubyRackApplication(createApplication()));
}
private IRubyObject createApplication() {
// There's a lot you could do here; for now, we just read a rackup file from the classpath,
// then build a Rack application based on it.
ScriptingContainer container = new ScriptingContainer();
container.put("builder_script", readResource("config.ru"));
return container.parse("require 'rack'; Rack::Builder.new_from_string(builder_script)").run();
}
private String readResource(String path) {
try {
return Resources.toString(getResource(path), defaultCharset());
} catch (IOException e) {
throw propagate(e);
}
}
}
| 5,616 |
0 | Create_ds/rack-servlet/examples/dropwizard/src/main/java/com/squareup/rack/examples/dropwizard | Create_ds/rack-servlet/examples/dropwizard/src/main/java/com/squareup/rack/examples/dropwizard/health/FakeHealthCheck.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.rack.examples.dropwizard.health;
import com.yammer.metrics.core.HealthCheck;
public class FakeHealthCheck extends HealthCheck {
public FakeHealthCheck() {
super("fake");
}
@Override protected Result check() throws Exception {
return Result.healthy();
}
}
| 5,617 |
0 | Create_ds/rack-servlet/examples/dropwizard/src/main/java/com/squareup/rack/examples/dropwizard | Create_ds/rack-servlet/examples/dropwizard/src/main/java/com/squareup/rack/examples/dropwizard/resources/EmptyResource.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.rack.examples.dropwizard.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path("/")
public class EmptyResource {
@GET public String get() {
return "";
}
}
| 5,618 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi-openid/src/test/java/org/apache/geronimo/components/jaspi/modules | Create_ds/geronimo-jaspi/geronimo-jaspi-openid/src/test/java/org/apache/geronimo/components/jaspi/modules/openid/OpenIDServerAuthModuleTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.modules.openid;
import java.util.Map;
import java.util.HashMap;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.message.config.AuthConfigFactory;
import javax.security.auth.message.config.AuthConfigProvider;
import javax.security.auth.message.config.ServerAuthConfig;
import javax.security.auth.message.config.ServerAuthContext;
import javax.security.auth.message.module.ServerAuthModule;
import org.apache.geronimo.components.jaspi.model.JaspiUtil;
import org.apache.geronimo.components.jaspi.model.AuthModuleType;
import org.testng.annotations.Test;
/**
* @version $Rev$ $Date$
*/
public class OpenIDServerAuthModuleTest {
@Test
public void testServerAuthModule() throws Exception {
CallbackHandler callbackHandler = null;
// AuthConfigFactoryImpl.staticCallbackHandler = callbackHandler;
AuthConfigFactory factory1 = AuthConfigFactory.getFactory();
AuthModuleType<ServerAuthModule> authModuleType = new AuthModuleType<ServerAuthModule>();
authModuleType.setClassName(OpenIDServerAuthModule.class.getName());
Map<String, String> options = new HashMap<String, String>();
options.put(OpenIDServerAuthModule.LOGIN_PAGE_KEY, "/login.jsp");
options.put(OpenIDServerAuthModule.ERROR_PAGE_KEY, "/error.jsp");
authModuleType.setOptions(options);
AuthConfigProvider authConfigProvider = JaspiUtil.wrapServerAuthModule("Http", "testApp", "id", authModuleType, true);
factory1.registerConfigProvider(authConfigProvider, "Http", "testApp", "description");
AuthConfigProvider authConfigProvider2 = factory1.getConfigProvider("Http", "testApp", null);
ServerAuthConfig serverAuthConfig = authConfigProvider2.getServerAuthConfig("Http", "testApp", callbackHandler);
ServerAuthContext serverAuthContext = serverAuthConfig.getAuthContext("id", null, null);
if (serverAuthContext == null) {
throw new NullPointerException("no serverAuthContext");
}
}
}
| 5,619 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi-openid/src/main/java/org/apache/geronimo/components/jaspi/modules | Create_ds/geronimo-jaspi/geronimo-jaspi-openid/src/main/java/org/apache/geronimo/components/jaspi/modules/openid/OpenIDServerAuthModule.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.modules.openid;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.MessagePolicy;
import javax.security.auth.message.callback.CallerPrincipalCallback;
import javax.security.auth.message.callback.GroupPrincipalCallback;
import javax.security.auth.message.module.ServerAuthModule;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.openid4java.consumer.ConsumerException;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.InMemoryConsumerAssociationStore;
import org.openid4java.consumer.InMemoryNonceVerifier;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.DiscoveryException;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.MessageException;
import org.openid4java.message.ParameterList;
/**
* @version $Rev$ $Date$
*/
public class OpenIDServerAuthModule implements ServerAuthModule {
private static final Class[] SUPPORTED_MESSAGE_TYPES = new Class[]{HttpServletRequest.class, HttpServletResponse.class};
public static final String MANDATORY_KEY = "javax.security.auth.message.MessagePolicy.isMandatory";
public static final String AUTH_METHOD_KEY = "javax.servlet.http.authType";
private static final String OPENID_IDENTIFIER = "openid_identifier";
private static final String DISCOVERY_SESSION_KEY = "openid-disc";
private static final String RETURN_ADDRESS = "/_openid_security_check";
private static final String ORIGINAL_URI_KEY = "org.apache.geronimo.components.jaspi.openid.URI";
private static final String RETURN_ADDRESS_KEY = "org.apache.geronimo.components.jaspi.openid.return.address";
public static final String LOGIN_PAGE_KEY = "org.apache.geronimo.security.jaspi.openid.LoginPage";
public static final String ERROR_PAGE_KEY = "org.apache.geronimo.security.jaspi.openid.ErrorPage";
private String errorPage;
private String errorPath;
private String loginPage;
private String loginPath;
private CallbackHandler callbackHandler;
private ConsumerManager consumerManager;
private static final String ID_KEY = "org.apache.geronimo.components.jaspi.openid.ID";
public Class[] getSupportedMessageTypes() {
return SUPPORTED_MESSAGE_TYPES;
}
public void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy, CallbackHandler handler, Map options) throws AuthException {
if (options == null) {
throw new AuthException("No options supplied");
}
this.callbackHandler = handler;
try {
consumerManager = new ConsumerManager();
} catch (ConsumerException e) {
throw (AuthException) new AuthException("Unable to create ConsumerManager").initCause(e);
}
consumerManager.setAssociations(new InMemoryConsumerAssociationStore());
consumerManager.setNonceVerifier(new InMemoryNonceVerifier(5000));
//??
consumerManager.getRealmVerifier().setEnforceRpId(false);
setLoginPage((String) options.get(LOGIN_PAGE_KEY));
setErrorPage((String) options.get(ERROR_PAGE_KEY));
}
private void setLoginPage(String path) throws AuthException {
if (path == null) {
throw new AuthException("No login page specified with key " + LOGIN_PAGE_KEY);
}
if (!path.startsWith("/")) {
path = "/" + path;
}
loginPage = path;
loginPath = path;
if (loginPath.indexOf('?') > 0) {
loginPath = loginPath.substring(0, loginPath.indexOf('?'));
}
}
private void setErrorPage(String path) throws AuthException {
if (path == null) {
throw new AuthException("No error page specified with key " + ERROR_PAGE_KEY);
}
if (path == null || path.trim().length() == 0) {
errorPath = null;
errorPage = null;
} else {
if (!path.startsWith("/")) {
path = "/" + path;
}
errorPage = path;
errorPath = path;
if (errorPath.indexOf('?') > 0) {
errorPath = errorPath.substring(0, errorPath.indexOf('?'));
}
}
}
public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException {
}
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {
HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
boolean isMandatory = isMandatory(messageInfo);
HttpSession session = request.getSession(isMandatory);
String uri = request.getRequestURI();
if (session == null || isLoginOrErrorPage(uri)) {
//auth not mandatory and not logged in.
return AuthStatus.SUCCESS;
}
//are we returning from the OP redirect?
if (uri.endsWith(RETURN_ADDRESS)) {
ParameterList parameterList = new ParameterList(request.getParameterMap());
DiscoveryInformation discovered = (DiscoveryInformation) session.getAttribute(DISCOVERY_SESSION_KEY);
String returnAddress = (String) session.getAttribute(RETURN_ADDRESS_KEY);
session.removeAttribute(RETURN_ADDRESS_KEY);
try {
VerificationResult verification = consumerManager.verify(returnAddress, parameterList, discovered);
Identifier identifier = verification.getVerifiedId();
if (identifier != null) {
session.setAttribute(ID_KEY, identifier);
//redirect back to original page
response.setContentLength(0);
String originalURI = (String) session.getAttribute(ORIGINAL_URI_KEY);
session.removeAttribute(ORIGINAL_URI_KEY);
if (originalURI == null || originalURI.length() == 0) {
originalURI = request.getContextPath();
if (originalURI.length() == 0) {
originalURI = "/";
}
}
response.sendRedirect(response.encodeRedirectURL(originalURI));
return AuthStatus.SEND_CONTINUE;
}
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Response verification failed: " + verification.getStatusMsg());
// } catch (MessageException e) {
//
// } catch (DiscoveryException e) {
//
// } catch (AssociationException e) {
//
// } catch (IOException e) {
} catch (Exception e) {
try {
//TODO redirect to error page or just send error
response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
} catch (IOException e1) {
}
}
return AuthStatus.SEND_FAILURE;
}
//are we already logged in, and not expired?
Identifier identifier = (Identifier) session.getAttribute(ID_KEY);
if (identifier != null) {
//TODO set up subject and callback handler.
final IdentifierPrincipal principal = new IdentifierPrincipal(identifier.getIdentifier());
clientSubject.getPrincipals().add(principal);
clientSubject.getPrincipals().add(new AuthenticatedPrincipal());
DiscoveryInformation discovered = (DiscoveryInformation) session.getAttribute(DISCOVERY_SESSION_KEY);
URL opEndpoint = discovered.getOPEndpoint();
clientSubject.getPrincipals().add(new OpenIDProviderPrincipal(opEndpoint.toString()));
CallerPrincipalCallback cpCallback = new CallerPrincipalCallback(clientSubject, principal);
GroupPrincipalCallback gpCallback = new GroupPrincipalCallback(clientSubject, new String[]{"authenticated"});
try {
callbackHandler.handle(new Callback[]{cpCallback, gpCallback});
} catch (IOException e) {
} catch (UnsupportedCallbackException e) {
}
return AuthStatus.SUCCESS;
}
//if request is not mandatory, we don't authenticate.
if (!isMandatory) {
return AuthStatus.SUCCESS;
}
//assume not...
String openidIdentifier = request.getParameter(OPENID_IDENTIFIER);
try {
//redirect to login page here...
if (openidIdentifier == null) {
// redirect to login page
session.setAttribute(ORIGINAL_URI_KEY, getFullRequestURI(request).toString());
response.setContentLength(0);
response.sendRedirect(response.encodeRedirectURL(addPaths(request.getContextPath(), loginPage)));
return AuthStatus.SEND_CONTINUE;
}
List<DiscoveryInformation> discoveries = consumerManager.discover(openidIdentifier);
//associate with one OP
DiscoveryInformation discovered = consumerManager.associate(discoveries);
//save association info in session
session.setAttribute(DISCOVERY_SESSION_KEY, discovered);
String returnAddress = request.getRequestURL().append(RETURN_ADDRESS).toString();
AuthRequest authRequest = consumerManager.authenticate(discovered, returnAddress);
session.setAttribute(RETURN_ADDRESS_KEY, authRequest.getReturnTo());
//save original uri in response, to be retrieved after redirect returns
if (session.getAttribute(ORIGINAL_URI_KEY) == null) {
session.setAttribute(ORIGINAL_URI_KEY, getFullRequestURI(request).toString());
}
//TODO openid 2.0 form redirect
response.sendRedirect(authRequest.getDestinationUrl(true));
return AuthStatus.SEND_CONTINUE;
} catch (DiscoveryException e) {
throw (AuthException) new AuthException("Could not authenticate").initCause(e);
} catch (ConsumerException e) {
throw (AuthException) new AuthException("Could not authenticate").initCause(e);
} catch (MessageException e) {
throw (AuthException) new AuthException("Could not authenticate").initCause(e);
} catch (IOException e) {
throw (AuthException) new AuthException("Could not authenticate").initCause(e);
}
// return null;
}
private boolean isLoginOrErrorPage(String uri) {
return (uri != null &&
(uri.equals(loginPage) || uri.equals(errorPage)));
}
private String addPaths(String p1, String p2) {
StringBuilder b = new StringBuilder(p1);
if (p1.endsWith("/")) {
if (p2.startsWith("/")) {
b.append(p2, 1, p2.length() - 1);
} else {
b.append(p2);
}
} else {
if (!p2.startsWith("/")) {
b.append("/");
}
b.append(p2);
}
return b.toString();
}
private StringBuilder getFullRequestURI(HttpServletRequest request) {
StringBuilder builder = new StringBuilder();
builder.append(request.getScheme()).append("://");
builder.append(request.getServerName()).append(":");
builder.append(request.getServerPort());
//TODO jetty combines this with the uri and query string. Can this have query params?
builder.append(request.getContextPath());
builder.append(request.getPathInfo());
if (request.getQueryString() != null && request.getQueryString().length() > 0) {
builder.append("?").append(request.getQueryString());
}
return builder;
}
private boolean isMandatory(MessageInfo messageInfo) {
String mandatory = (String) messageInfo.getMap().get(MANDATORY_KEY);
if (mandatory == null) {
return false;
}
return Boolean.valueOf(mandatory);
}
public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException {
return AuthStatus.SEND_SUCCESS;
}
}
| 5,620 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi-openid/src/main/java/org/apache/geronimo/components/jaspi/modules | Create_ds/geronimo-jaspi/geronimo-jaspi-openid/src/main/java/org/apache/geronimo/components/jaspi/modules/openid/AuthenticatedPrincipal.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.modules.openid;
import java.security.Principal;
import java.io.Serializable;
/**
* @version $Rev$ $Date$
*/
public class AuthenticatedPrincipal implements Principal, Serializable {
private static final String AUTHENTICATED = "authenticated";
public AuthenticatedPrincipal() {
}
public AuthenticatedPrincipal(String ignoredName) {
}
public String getName() {
return AUTHENTICATED;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return true;
}
public int hashCode() {
return (AUTHENTICATED.hashCode());
}
}
| 5,621 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi-openid/src/main/java/org/apache/geronimo/components/jaspi/modules | Create_ds/geronimo-jaspi/geronimo-jaspi-openid/src/main/java/org/apache/geronimo/components/jaspi/modules/openid/OpenIDProviderPrincipal.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.modules.openid;
import java.security.Principal;
import java.io.Serializable;
/**
* @version $Rev$ $Date$
*/
public class OpenIDProviderPrincipal implements Principal, Serializable {
private final String name;
public OpenIDProviderPrincipal(String identifier) {
name = identifier;
}
public String getName() {
return name;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OpenIDProviderPrincipal that = (OpenIDProviderPrincipal) o;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
return true;
}
public int hashCode() {
return (name != null ? name.hashCode() : 0);
}
} | 5,622 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi-openid/src/main/java/org/apache/geronimo/components/jaspi/modules | Create_ds/geronimo-jaspi/geronimo-jaspi-openid/src/main/java/org/apache/geronimo/components/jaspi/modules/openid/IdentifierPrincipal.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.modules.openid;
import java.security.Principal;
import java.io.Serializable;
/**
* @version $Rev$ $Date$
*/
public class IdentifierPrincipal implements Principal, Serializable {
private final String name;
public IdentifierPrincipal(String identifier) {
name = identifier;
}
public String getName() {
return name;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IdentifierPrincipal principal = (IdentifierPrincipal) o;
if (name != null ? !name.equals(principal.name) : principal.name != null) return false;
return true;
}
public int hashCode() {
return (name != null ? name.hashCode() : 0);
}
}
| 5,623 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/test/java/org/apache/geronimo/components | Create_ds/geronimo-jaspi/geronimo-jaspi/src/test/java/org/apache/geronimo/components/jaspi/AuthConfigFactoryImplTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.components.jaspi;
import java.net.URL;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.message.config.AuthConfigFactory;
import javax.security.auth.message.config.AuthConfigFactory.RegistrationContext;
import javax.security.auth.message.config.AuthConfigProvider;
import javax.security.auth.message.config.RegistrationListener;
import javax.security.auth.message.module.ClientAuthModule;
import javax.security.auth.message.module.ServerAuthModule;
import junit.framework.TestCase;
import org.apache.geronimo.components.jaspi.model.AuthModuleType;
import org.apache.geronimo.components.jaspi.model.JaspiUtil;
import org.apache.geronimo.components.jaspi.providers.BadConstructorProvider;
import org.apache.geronimo.components.jaspi.providers.BadImplementProvider;
import org.apache.geronimo.components.jaspi.providers.DummyClientAuthModule;
import org.apache.geronimo.components.jaspi.providers.DummyProvider;
import org.apache.geronimo.components.jaspi.providers.DummyServerAuthModule;
public class AuthConfigFactoryImplTest extends TestCase {
protected void setUp() throws Exception {
URL url = getClass().getClassLoader().getResource("test-jaspi.xml");
System.setProperty(AuthConfigFactoryImpl.JASPI_CONFIGURATION_FILE, url.getPath());
CallbackHandler callbackHandler = null;
AuthConfigFactoryImpl.staticCallbackHandler = callbackHandler;
AuthConfigFactory.setFactory(null);
}
public void testFactory() throws Exception {
AuthConfigFactory factory1 = AuthConfigFactory.getFactory();
assertNotNull(factory1);
AuthConfigFactory factory2 = AuthConfigFactory.getFactory();
assertNotNull(factory2);
assertSame(factory1, factory2);
}
public void testBadConstructorProvider() throws Exception {
AuthConfigFactory factory = AuthConfigFactory.getFactory();
try {
factory.registerConfigProvider(BadConstructorProvider.class.getName(), null, "layer1", "appContext1", "description");
fail("An exception should have been thrown");
} catch (SecurityException e) {
}
}
public void testBadImplementProvider() throws Exception {
AuthConfigFactory factory = AuthConfigFactory.getFactory();
try {
factory.registerConfigProvider(BadImplementProvider.class.getName(), null, "layer2", "appContext2", "description");
fail("An exception should have been thrown");
} catch (SecurityException e) {
//e.printStackTrace();
}
}
public void testRegisterUnregister() throws Exception {
AuthConfigFactory factory = AuthConfigFactory.getFactory();
String regId = factory.registerConfigProvider(DummyProvider.class.getName(), null, "layer3", "appContext3", "description");
assertNotNull(regId);
RegistrationContext regContext = factory.getRegistrationContext(regId);
assertNotNull(regContext);
assertEquals("layer3", regContext.getMessageLayer());
assertEquals("appContext3", regContext.getAppContext());
assertEquals("description", regContext.getDescription());
assertTrue(factory.removeRegistration(regId));
regContext = factory.getRegistrationContext(regId);
assertNull(regContext);
}
public void testProviderWithLayerAndContext() throws Exception {
AuthConfigFactory factory = AuthConfigFactory.getFactory();
String registrationID = factory.registerConfigProvider(DummyProvider.class.getName(), null, "layer4", "appContext4", "description");
assertNotNull(factory.getConfigProvider("layer4", "appContext4", null));
assertNull(factory.getConfigProvider("layer4", "bad", null));
assertNull(factory.getConfigProvider("bad", "appContext4", null));
factory.removeRegistration(registrationID);
assertNull(factory.getRegistrationContext(registrationID));
}
public void testProviderWithLayer() throws Exception {
AuthConfigFactory factory = AuthConfigFactory.getFactory();
String registrationID = factory.registerConfigProvider(DummyProvider.class.getName(), null, "layer5", null, "description");
assertNotNull(factory.getConfigProvider("layer5", "appContext5", null));
assertNotNull(factory.getConfigProvider("layer5", "bad", null));
assertNull(factory.getConfigProvider("bad", "appContext5", null));
factory.removeRegistration(registrationID);
assertNull(factory.getRegistrationContext(registrationID));
}
public void testProviderContextLayer() throws Exception {
AuthConfigFactory factory = AuthConfigFactory.getFactory();
String registrationID = factory.registerConfigProvider(DummyProvider.class.getName(), null, null, "appContext6", "description");
assertNotNull(factory.getConfigProvider("layer6", "appContext6", null));
assertNull(factory.getConfigProvider("layer6", "bad", null));
assertNotNull(factory.getConfigProvider("bad", "appContext6", null));
factory.removeRegistration(registrationID);
assertNull(factory.getRegistrationContext(registrationID));
}
public void testProviderDefault() throws Exception {
AuthConfigFactory factory = AuthConfigFactory.getFactory();
String registrationID = factory.registerConfigProvider(DummyProvider.class.getName(), null, null, null, "description");
assertNotNull(factory.getConfigProvider("layer7", "appContext7", null));
assertNotNull(factory.getConfigProvider("layer7", "bad", null));
assertNotNull(factory.getConfigProvider("bad", "appContext7", null));
assertNotNull(factory.getConfigProvider("bad", "bad", null));
factory.removeRegistration(registrationID);
assertNull(factory.getRegistrationContext(registrationID));
}
public void testListenerOnRegister() throws Exception {
AuthConfigFactory factory = AuthConfigFactory.getFactory();
String registrationID = factory.registerConfigProvider(DummyProvider.class.getName(), null, null, null, "description");
DummyListener listener = new DummyListener();
assertNotNull(factory.getConfigProvider("foo", "bar", listener));
factory.registerConfigProvider(DummyProvider.class.getName(), null, null, null, "description");
assertTrue(listener.notified);
factory.removeRegistration(registrationID);
assertNull(factory.getRegistrationContext(registrationID));
}
public void testListenerOnUnregister() throws Exception {
AuthConfigFactory factory = AuthConfigFactory.getFactory();
String regId = factory.registerConfigProvider(DummyProvider.class.getName(), null, null, null, "description");
DummyListener listener = new DummyListener();
assertNotNull(factory.getConfigProvider("foo", "bar", listener));
factory.removeRegistration(regId);
assertTrue(listener.notified);
}
public void testWrapClientAuthModule() throws Exception {
AuthConfigFactory factory = AuthConfigFactory.getFactory();
AuthModuleType<ClientAuthModule> authModuleType = new AuthModuleType<ClientAuthModule>();
authModuleType.setClassName(DummyClientAuthModule.class.getName());
AuthConfigProvider authConfigProvider = JaspiUtil.wrapClientAuthModule("layer", "appContext1", "id", authModuleType, true);
String regId = factory.registerConfigProvider(authConfigProvider, "layer", "appContext1", "description");
DummyListener listener = new DummyListener();
assertNotNull(factory.getConfigProvider("layer", "appContext1", listener));
factory.removeRegistration(regId);
assertTrue(listener.notified);
}
public void testWrapServerAuthModule() throws Exception {
AuthConfigFactory factory = AuthConfigFactory.getFactory();
AuthModuleType<ServerAuthModule> authModuleType = new AuthModuleType<ServerAuthModule>();
authModuleType.setClassName(DummyServerAuthModule.class.getName());
AuthConfigProvider authConfigProvider = JaspiUtil.wrapServerAuthModule("layer", "appContext1", "id", authModuleType, true);
String regId = factory.registerConfigProvider(authConfigProvider, "layer", "appContext1", "description");
DummyListener listener = new DummyListener();
assertNotNull(factory.getConfigProvider("layer", "appContext1", listener));
factory.removeRegistration(regId);
assertTrue(listener.notified);
}
public static class DummyListener implements RegistrationListener {
public boolean notified = true;
public void notify(String layer, String appContext) {
notified = true;
}
}
}
| 5,624 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/test/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/test/java/org/apache/geronimo/components/jaspi/impl/JaxbTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.impl;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.File;
import java.io.Writer;
import java.io.FileWriter;
import java.io.FileReader;
import java.net.URL;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.security.auth.message.config.AuthConfigProvider;
import javax.security.auth.message.config.ClientAuthConfig;
import javax.security.auth.message.config.ClientAuthContext;
import javax.security.auth.message.config.ServerAuthConfig;
import javax.security.auth.message.config.ServerAuthContext;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.module.ClientAuthModule;
import javax.security.auth.callback.CallbackHandler;
import org.apache.geronimo.components.jaspi.AuthConfigFactoryImpl;
import org.apache.geronimo.components.jaspi.model.AuthModuleType;
import org.apache.geronimo.components.jaspi.model.ClientAuthConfigType;
import org.apache.geronimo.components.jaspi.model.ClientAuthContextType;
import org.apache.geronimo.components.jaspi.model.ConfigProviderType;
import org.apache.geronimo.components.jaspi.model.JaspiType;
import org.apache.geronimo.components.jaspi.model.JaspiXmlUtil;
import org.testng.annotations.Test;
import org.xml.sax.SAXException;
/**
* @version $Rev: 939768 $ $Date: 2010-04-30 11:26:46 -0700 (Fri, 30 Apr 2010) $
*/
public class JaxbTest {
public static final XMLInputFactory XMLINPUT_FACTORY = XMLInputFactory.newInstance();
private final int count = 2;
private CallbackHandler callbackHandler;
@Test
public void testLoad() throws Exception {
String file = "jaspi";
JaspiType jaspi1 = loadJaspi(file);
if (jaspi1.getConfigProvider().size() != count) throw new Exception("expected " + count + " configprovider, not this: " + jaspi1.getConfigProvider());
File newFile = getWriteFile(file);
Writer writer = new FileWriter(newFile);
JaspiXmlUtil.writeJaspi(jaspi1, writer);
JaspiType jaspi2 = JaspiXmlUtil.loadJaspi(new FileReader(newFile));
if (jaspi2.getConfigProvider().size() != count) throw new Exception("expected " + count + " configprovider, not this: " + jaspi2.getConfigProvider());
}
@Test
public void testLoad2() throws Exception {
String file = "jaspi-2";
JaspiType jaspi1 = loadJaspi(file);
if (jaspi1.getConfigProvider().size() != count) throw new Exception("expected " + count + " configprovider, not this: " + jaspi1.getConfigProvider());
File newFile = getWriteFile(file);
Writer writer = new FileWriter(newFile);
JaspiXmlUtil.writeJaspi(jaspi1, writer);
JaspiType jaspi2 = JaspiXmlUtil.loadJaspi(new FileReader(newFile));
if (jaspi2.getConfigProvider().size() != count) throw new Exception("expected " + count + " configprovider, not this: " + jaspi2.getConfigProvider());
AuthConfigFactoryImpl authConfigFactory = new AuthConfigFactoryImpl(jaspi1, callbackHandler);
AuthConfigProvider configProvider = authConfigFactory.getConfigProvider("Http", "test-app1", null);
// adapter.unmarshal(jaspi1.getConfigProvider()).get(ConfigProviderType.getRegistrationKey("Http", "test-app1")).getProvider();
checkConfigProvider(configProvider);
}
private JaspiType loadJaspi(String file) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
Reader reader = getReader(file);
JaspiType rbac = JaspiXmlUtil.loadJaspi(reader);
return rbac;
}
private Reader getReader(String file) {
InputStream in = getClass().getClassLoader().getResourceAsStream("test-" + file + ".xml");
Reader reader = new InputStreamReader(in);
return reader;
}
private File getWriteFile(String file) {
URL url = getClass().getClassLoader().getResource("test-jaspi.xml");
File newFile = new File(new File(url.getPath()).getParentFile(), "test-" + file + "-write.xml");
return newFile;
}
@Test
public void testConfigProvider() throws Exception {
String file = "config-provider";
Reader reader = getReader(file);
ConfigProviderType jaspi1 = JaspiXmlUtil.loadConfigProvider(reader);
// jaspi1.initialize(callbackHandler);
File newFile = getWriteFile(file);
Writer writer = new FileWriter(newFile);
JaspiXmlUtil.writeConfigProvider(jaspi1, writer);
ConfigProviderType jaspi2 = JaspiXmlUtil.loadConfigProvider(new FileReader(newFile));
AuthConfigProvider configProvider = ConfigProviderImpl.newConfigProvider(null, jaspi1);
checkConfigProvider(configProvider);
}
@Test
public void testClientAuthConfig() throws Exception {
String file = "client-auth-config";
Reader reader = getReader(file);
ClientAuthConfigType jaspi1 = JaspiXmlUtil.loadClientAuthConfig(reader);
// jaspi1.initialize(callbackHandler);
File newFile = getWriteFile(file);
Writer writer = new FileWriter(newFile);
JaspiXmlUtil.writeClientAuthConfig(jaspi1, writer);
ClientAuthConfigType jaspi2 = JaspiXmlUtil.loadClientAuthConfig(new FileReader(newFile));
ClientAuthConfig clientAuthConfig = ConfigProviderImpl.newClientAuthConfig(jaspi1, "Http", "app", callbackHandler);
checkClientAuthConfig(clientAuthConfig);
}
@Test
public void testClientAuthContext() throws Exception {
String file = "client-auth-context";
Reader reader = getReader(file);
ClientAuthContextType jaspi1 = JaspiXmlUtil.loadClientAuthContext(reader);
File newFile = getWriteFile(file);
Writer writer = new FileWriter(newFile);
JaspiXmlUtil.writeClientAuthContext(jaspi1, writer);
ClientAuthContextType jaspi2 = JaspiXmlUtil.loadClientAuthContext(new FileReader(newFile));
ClientAuthContext clientAuthConfig = ConfigProviderImpl.newClientAuthContext(jaspi1, callbackHandler);
clientAuthConfig.secureRequest(null, null);
}
@Test
public void testClientAuthModule() throws Exception {
String file = "client-auth-module";
Reader reader = getReader(file);
AuthModuleType<ClientAuthModule> jaspi1 = JaspiXmlUtil.loadClientAuthModule(reader);
File newFile = getWriteFile(file);
Writer writer = new FileWriter(newFile);
JaspiXmlUtil.writeClientAuthModule(jaspi1, writer);
AuthModuleType jaspi2 = JaspiXmlUtil.loadClientAuthModule(new FileReader(newFile));
ClientAuthModule clientAuthConfig =ConfigProviderImpl.newAuthModule(jaspi1, callbackHandler);
clientAuthConfig.secureRequest(null, null);
}
private void checkConfigProvider(AuthConfigProvider configProvider) throws AuthException {
ClientAuthConfig clientAuthConfig = configProvider.getClientAuthConfig("Http", "test-app1", null);
checkClientAuthConfig(clientAuthConfig);
ServerAuthConfig serverAuthConfig = configProvider.getServerAuthConfig("Http", "test-app1", null);
String authContextID = serverAuthConfig.getAuthContextID(null);
ServerAuthContext serverAuthContext = serverAuthConfig.getAuthContext(authContextID, null, null);
serverAuthContext.secureResponse(null, null);
}
private void checkClientAuthConfig(ClientAuthConfig clientAuthConfig) throws AuthException {
String authContextID = clientAuthConfig.getAuthContextID(null);
ClientAuthContext clientAuthContext = clientAuthConfig.getAuthContext(authContextID, null, null);
clientAuthContext.secureRequest(null, null);
}
}
| 5,625 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/test/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/test/java/org/apache/geronimo/components/jaspi/providers/DummyClientAuthModule.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.providers;
import java.util.Map;
import javax.security.auth.message.module.ClientAuthModule;
import javax.security.auth.message.MessagePolicy;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.Subject;
/**
* @version $Rev:$ $Date:$
*/
public class DummyClientAuthModule implements ClientAuthModule {
public Class[] getSupportedMessageTypes() {
return new Class[0];
}
public void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy, CallbackHandler handler, Map options) throws AuthException {
}
public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException {
}
public AuthStatus secureRequest(MessageInfo messageInfo, Subject clientSubject) throws AuthException {
return AuthStatus.SUCCESS;
}
public AuthStatus validateResponse(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {
return AuthStatus.SUCCESS;
}
}
| 5,626 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/test/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/test/java/org/apache/geronimo/components/jaspi/providers/BadImplementProvider.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.components.jaspi.providers;
import java.util.Map;
public class BadImplementProvider {
public BadImplementProvider(Map props) {
}
}
| 5,627 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/test/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/test/java/org/apache/geronimo/components/jaspi/providers/DummyProvider.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.components.jaspi.providers;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.config.AuthConfigProvider;
import javax.security.auth.message.config.ClientAuthConfig;
import javax.security.auth.message.config.ServerAuthConfig;
import javax.security.auth.message.config.AuthConfigFactory;
public class DummyProvider implements AuthConfigProvider {
public DummyProvider(Map props, AuthConfigFactory authConfigFactory) {
}
public ClientAuthConfig getClientAuthConfig(String layer, String appContext, CallbackHandler handler) throws AuthException, SecurityException {
// TODO Auto-generated method stub
return null;
}
public ServerAuthConfig getServerAuthConfig(String layer, String appContext, CallbackHandler handler) throws AuthException, SecurityException {
// TODO Auto-generated method stub
return null;
}
public void refresh() throws SecurityException {
// TODO Auto-generated method stub
}
}
| 5,628 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/test/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/test/java/org/apache/geronimo/components/jaspi/providers/DummyServerAuthModule.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.providers;
import java.util.Map;
import javax.security.auth.message.module.ServerAuthModule;
import javax.security.auth.message.MessagePolicy;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.Subject;
/**
* @version $Rev:$ $Date:$
*/
public class DummyServerAuthModule implements ServerAuthModule {
public Class[] getSupportedMessageTypes() {
return new Class[0];
}
public void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy, CallbackHandler handler, Map options) throws AuthException {
}
public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException {
}
public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException {
return AuthStatus.SEND_SUCCESS;
}
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {
return AuthStatus.SUCCESS;
}
}
| 5,629 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/test/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/test/java/org/apache/geronimo/components/jaspi/providers/BadConstructorProvider.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.components.jaspi.providers;
public class BadConstructorProvider {
}
| 5,630 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/AuthConfigFactoryImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.components.jaspi;
import org.apache.geronimo.components.jaspi.impl.ConfigProviderImpl;
import org.apache.geronimo.components.jaspi.model.ConfigProviderType;
import org.apache.geronimo.components.jaspi.model.JaspiType;
import org.apache.geronimo.components.jaspi.model.JaspiXmlUtil;
import org.apache.geronimo.components.jaspi.model.ObjectFactory;
import org.xml.sax.SAXException;
import javax.security.auth.AuthPermission;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.message.config.AuthConfigFactory;
import javax.security.auth.message.config.AuthConfigProvider;
import javax.security.auth.message.config.RegistrationListener;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamException;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implementation of the AuthConfigFactory.
*
* @version $Rev: $ $Date: $
*/
public class AuthConfigFactoryImpl extends AuthConfigFactory {
public static final String JASPI_CONFIGURATION_FILE = "org.apache.geronimo.jaspic.configurationFile";
private static final File DEFAULT_CONFIG_FILE = new File("var/config/security/jaspic/jaspic.xml");
public static CallbackHandler staticCallbackHandler;
private static ClassLoader contextClassLoader;
private Map<String, ConfigProviderInfo> configProviders = new HashMap<String, ConfigProviderInfo>();
private final CallbackHandler callbackHandler;
private final File configFile;
static {
contextClassLoader = java.security.AccessController
.doPrivileged(new java.security.PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return Thread.currentThread().getContextClassLoader();
}
});
}
public AuthConfigFactoryImpl(CallbackHandler callbackHandler, File configFile) {
JaspiXmlUtil.initialize(callbackHandler);
this.callbackHandler = callbackHandler;
this.configFile = configFile;
loadConfig();
}
public AuthConfigFactoryImpl() {
this(staticCallbackHandler, getConfigFile());
}
private static File getConfigFile() {
String fileLocation = java.security.AccessController
.doPrivileged(new java.security.PrivilegedAction<String>() {
public String run() {
return System.getProperty(JASPI_CONFIGURATION_FILE);
}
});
File file;
if (fileLocation == null) {
file = DEFAULT_CONFIG_FILE;
} else {
file = new File(fileLocation);
}
return file;
}
public AuthConfigFactoryImpl(JaspiType jaspiType, CallbackHandler callbackHandler) {
this.callbackHandler = callbackHandler;
this.configFile = null;
initialize(jaspiType);
}
public synchronized String[] detachListener(RegistrationListener listener, String layer, String appContext) throws SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new AuthPermission("detachAuthListener"));
}
List<String> ids = new ArrayList<String>();
for (Map.Entry<String, ConfigProviderInfo> entry : getRegistrations().entrySet()) {
ConfigProviderInfo ctx = entry.getValue();
if ((layer == null || layer.equals(ctx.getMessageLayer())) &&
(appContext == null || appContext.equals(ctx.getAppContext()))) {
if (ctx.getListeners().remove(listener)) {
ids.add(entry.getKey());
}
}
}
return ids.toArray(new String[ids.size()]);
}
private Map<String, ConfigProviderInfo> getRegistrations() {
return configProviders;
}
public synchronized AuthConfigProvider getConfigProvider(String layer, String appContext, RegistrationListener listener) {
if (layer == null) {
throw new NullPointerException("messageLayer");
}
if (appContext == null) {
throw new NullPointerException("appContext");
}
ConfigProviderInfo ctx = getRegistrations().get(ConfigProviderType.getRegistrationKey(layer, appContext));
if (ctx == null) {
ctx = getRegistrations().get(ConfigProviderType.getRegistrationKey(null, appContext));
}
if (ctx == null) {
ctx = getRegistrations().get(ConfigProviderType.getRegistrationKey(layer, null));
}
if (ctx == null) {
ctx = getRegistrations().get(ConfigProviderType.getRegistrationKey(null, null));
}
if (ctx != null) {
if (listener != null) {
ctx.getListeners().add(listener);
}
return ctx.getAuthConfigProvider();
}
return null;
}
public synchronized RegistrationContext getRegistrationContext(String registrationID) {
return getRegistrations().get(registrationID);
}
public synchronized String[] getRegistrationIDs(AuthConfigProvider provider) {
List<String> ids = new ArrayList<String>();
for (Map.Entry<String, ConfigProviderInfo> entry : getRegistrations().entrySet()) {
ConfigProviderInfo ctx = entry.getValue();
if (provider == null ||
provider.getClass().getName().equals(ctx.getAuthConfigProvider().getClass().getName())) {
ids.add(entry.getKey());
}
}
return ids.toArray(new String[ids.size()]);
}
public synchronized void refresh() throws SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new AuthPermission("refreshAuth"));
}
loadConfig();
}
public String registerConfigProvider(AuthConfigProvider authConfigProvider, String layer, String appContext, String description) throws SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new AuthPermission("registerAuthConfigProvider"));
}
return registerConfigProvider(authConfigProvider, layer, appContext, description, false, null, null);
}
public synchronized String registerConfigProvider(final String className, final Map constructorParam, String layer, String appContext, String description) throws SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new AuthPermission("registerAuthConfigProvider"));
}
String key = registerConfigProvider(null, layer, appContext, description, true, constructorParam, className);
saveConfig();
return key;
}
private String registerConfigProvider(AuthConfigProvider provider, String layer, String appContext, String description, boolean persistent, Map<String, String> constructorParam, String className) {
String key = ConfigProviderType.getRegistrationKey(layer, appContext);
// Get or create context
ConfigProviderInfo info = getRegistrations().get(key);
List<RegistrationListener> listeners;
if (info == null) {
listeners = new ArrayList<RegistrationListener>();
} else {
if (persistent != info.isPersistent()) {
throw new IllegalArgumentException("Cannot change the persistence state");
}
listeners = info.getListeners();
}
// Create provider
ConfigProviderType ctx = new ConfigProviderType(layer, appContext, persistent, persistent? null: this);
ctx.setDescription(description);
if (persistent) {
if (provider != null) {
throw new IllegalStateException("Config provider supplied but should be created");
}
ctx.setClassName(className);
ctx.setProperties(constructorParam);
provider = ConfigProviderImpl.newConfigProvider(this, ctx);
} else {
if (provider == null) {
throw new IllegalStateException("No config provider to set");
}
}
info = new ConfigProviderInfo(provider, ctx, listeners, persistent);
getRegistrations().put(key, info);
// Notify listeners
for (RegistrationListener listener : listeners) {
listener.notify(info.getMessageLayer(), info.getAppContext());
}
// Return registration Id
return key;
}
public synchronized boolean removeRegistration(String registrationID) throws SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new AuthPermission("removeAuthRegistration"));
}
ConfigProviderInfo ctx = getRegistrations().remove(registrationID);
saveConfig();
if (ctx != null) {
List<RegistrationListener> listeners = ctx.getListeners();
for (RegistrationListener listener : listeners) {
listener.notify(ctx.getMessageLayer(), ctx.getAppContext());
}
return true;
}
return false;
}
private void loadConfig() {
if (configFile != null && configFile.length() > 0) {
JaspiType jaspiType;
try {
FileReader in = new FileReader(configFile);
try {
jaspiType = JaspiXmlUtil.loadJaspi(in);
} finally {
in.close();
}
} catch (ParserConfigurationException e) {
throw new SecurityException("Could not read config", e);
} catch (IOException e) {
throw new SecurityException("Could not read config", e);
} catch (SAXException e) {
throw new SecurityException("Could not read config", e);
} catch (JAXBException e) {
throw new SecurityException("Could not read config", e);
} catch (XMLStreamException e) {
throw new SecurityException("Could not read config", e);
}
initialize(jaspiType);
}
}
private void initialize(JaspiType jaspiType) {
Map<String, ConfigProviderInfo> configProviderInfos = new HashMap<String, ConfigProviderInfo>();
try {
for (ConfigProviderType configProviderType: jaspiType.getConfigProvider()) {
AuthConfigProvider authConfigProvider = ConfigProviderImpl.newConfigProvider(this, configProviderType);
ConfigProviderInfo info = new ConfigProviderInfo(authConfigProvider, configProviderType, true);
configProviderInfos.put(configProviderType.getKey(), info);
}
} catch (Exception e) {
throw new SecurityException("Could not map config providers", e);
}
this.configProviders = configProviderInfos;
}
private void saveConfig() {
if (configFile != null) {
JaspiType jaspiType = new ObjectFactory().createJaspiType();
try {
for (ConfigProviderInfo info: configProviders.values()) {
if (info.isPersistent()) {
jaspiType.getConfigProvider().add(info.getConfigProviderType());
}
}
FileWriter out = new FileWriter(configFile);
try {
JaspiXmlUtil.writeJaspi(jaspiType, out);
} finally {
out.close();
}
} catch (IOException e) {
throw new SecurityException("Could not write config", e);
} catch (XMLStreamException e) {
throw new SecurityException("Could not write config", e);
} catch (JAXBException e) {
throw new SecurityException("Could not write config", e);
} catch (Exception e) {
throw new SecurityException("Could not write config", e);
}
}
}
private static class ConfigProviderInfo implements AuthConfigFactory.RegistrationContext {
private final AuthConfigProvider authConfigProvider;
private final ConfigProviderType configProviderType;
private final boolean persistent;
private final List<RegistrationListener> listeners;
private ConfigProviderInfo(AuthConfigProvider authConfigProvider, ConfigProviderType configProviderType, boolean persistent) {
this.authConfigProvider = authConfigProvider;
this.configProviderType = configProviderType;
this.persistent = persistent;
listeners = new ArrayList<RegistrationListener>();
}
private ConfigProviderInfo(AuthConfigProvider authConfigProvider, ConfigProviderType configProviderType, List<RegistrationListener> listeners, boolean persistent) {
this.authConfigProvider = authConfigProvider;
this.configProviderType = configProviderType;
this.listeners = listeners;
this.persistent = persistent;
}
public AuthConfigProvider getAuthConfigProvider() {
return authConfigProvider;
}
public ConfigProviderType getConfigProviderType() {
return configProviderType;
}
public List<RegistrationListener> getListeners() {
return listeners;
}
@Override
public String getAppContext() {
return configProviderType.getAppContext();
}
@Override
public String getDescription() {
return configProviderType.getDescription();
}
@Override
public String getMessageLayer() {
return configProviderType.getMessageLayer();
}
@Override
public boolean isPersistent() {
return persistent;
}
}
}
| 5,631 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/ConfigException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi;
/**
* @version $Rev$ $Date$
*/
public class ConfigException extends Exception {
public ConfigException() {
super();
}
public ConfigException(String s) {
super(s);
}
public ConfigException(String s, Throwable throwable) {
super(s, throwable);
}
public ConfigException(Throwable throwable) {
super(throwable);
}
}
| 5,632 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/JaspicUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi;
import java.io.Reader;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.config.AuthConfigFactory;
import javax.security.auth.message.config.AuthConfigProvider;
import javax.security.auth.message.module.ClientAuthModule;
import javax.security.auth.message.module.ServerAuthModule;
import org.apache.geronimo.components.jaspi.model.AuthModuleType;
import org.apache.geronimo.components.jaspi.model.ClientAuthConfigType;
import org.apache.geronimo.components.jaspi.model.ClientAuthContextType;
import org.apache.geronimo.components.jaspi.model.ConfigProviderType;
import org.apache.geronimo.components.jaspi.model.JaspiUtil;
import org.apache.geronimo.components.jaspi.model.JaspiXmlUtil;
import org.apache.geronimo.components.jaspi.model.ServerAuthConfigType;
import org.apache.geronimo.components.jaspi.model.ServerAuthContextType;
/**
* @version $Rev$ $Date$
*/
public class JaspicUtil {
private JaspicUtil() {
}
public static String registerAuthConfigProvider(Reader config, String messageLayer, String appContext) throws ConfigException {
try {
ConfigProviderType configProviderType = JaspiXmlUtil.loadConfigProvider(config);
AuthConfigProvider authConfigProvider = JaspiUtil.wrapAuthConfigProvider(configProviderType);
return AuthConfigFactory.getFactory().registerConfigProvider(authConfigProvider, messageLayer, appContext, null);
} catch (Exception e) {
throw new ConfigException(e);
}
}
public static String registerClientAuthConfig(Reader config) throws ConfigException {
try {
ClientAuthConfigType clientAuthConfigType = JaspiXmlUtil.loadClientAuthConfig(config);
AuthConfigProvider authConfigProvider = JaspiUtil.wrapClientAuthConfig(clientAuthConfigType);
return AuthConfigFactory.getFactory().registerConfigProvider(authConfigProvider, clientAuthConfigType.getMessageLayer(), clientAuthConfigType.getAppContext(), null);
} catch (Exception e) {
throw new ConfigException(e);
}
}
public static String registerClientAuthContext(Reader config, boolean _protected) throws ConfigException {
try {
ClientAuthContextType clientAuthContextType = JaspiXmlUtil.loadClientAuthContext(config);
AuthConfigProvider authConfigProvider = JaspiUtil.wrapClientAuthContext(clientAuthContextType, _protected);
return AuthConfigFactory.getFactory().registerConfigProvider(authConfigProvider, clientAuthContextType.getMessageLayer(), clientAuthContextType.getAppContext(), null);
} catch (Exception e) {
throw new ConfigException(e);
}
}
public static String registerClientAuthModule(String messageLayer, String appContext, String authenticationContextID, Reader config, boolean _protected) throws ConfigException {
try {
AuthModuleType<ClientAuthModule> clientAuthModuleType = JaspiXmlUtil.loadClientAuthModule(config);
AuthConfigProvider authConfigProvider = JaspiUtil.wrapClientAuthModule(messageLayer, appContext, authenticationContextID, clientAuthModuleType, _protected);
return AuthConfigFactory.getFactory().registerConfigProvider(authConfigProvider, messageLayer, appContext, null);
} catch (Exception e) {
throw new ConfigException(e);
}
}
public static String registerServerAuthConfig(Reader config) throws ConfigException {
try {
ServerAuthConfigType serverAuthConfigType = JaspiXmlUtil.loadServerAuthConfig(config);
AuthConfigProvider authConfigProvider = JaspiUtil.wrapServerAuthConfig(serverAuthConfigType);
return AuthConfigFactory.getFactory().registerConfigProvider(authConfigProvider, serverAuthConfigType.getMessageLayer(), serverAuthConfigType.getAppContext(), null);
} catch (Exception e) {
throw new ConfigException(e);
}
}
public static String registerServerAuthContext(Reader config, boolean _protected) throws ConfigException {
try {
ServerAuthContextType serverAuthContextType = JaspiXmlUtil.loadServerAuthContext(config);
AuthConfigProvider authConfigProvider = JaspiUtil.wrapServerAuthContext(serverAuthContextType, _protected);
return AuthConfigFactory.getFactory().registerConfigProvider(authConfigProvider, serverAuthContextType.getMessageLayer(), serverAuthContextType.getAppContext(), null);
} catch (Exception e) {
throw new ConfigException(e);
}
}
public static String registerServerAuthModule(String messageLayer, String appContext, String authenticationContextID, Reader config, boolean _protected) throws ConfigException {
try {
AuthModuleType<ServerAuthModule> serverAuthModuleType = JaspiXmlUtil.loadServerAuthModule(config);
AuthConfigProvider authConfigProvider = JaspiUtil.wrapServerAuthModule(messageLayer, appContext, authenticationContextID, serverAuthModuleType, _protected);
return AuthConfigFactory.getFactory().registerConfigProvider(authConfigProvider, messageLayer, appContext, null);
} catch (Exception e) {
throw new ConfigException(e);
}
}
}
| 5,633 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/impl/ConfigProviderImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.impl;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.MessagePolicy;
import javax.security.auth.message.config.AuthConfigFactory;
import javax.security.auth.message.config.AuthConfigProvider;
import javax.security.auth.message.config.ClientAuthConfig;
import javax.security.auth.message.config.ClientAuthContext;
import javax.security.auth.message.config.ServerAuthConfig;
import javax.security.auth.message.config.ServerAuthContext;
import javax.security.auth.message.module.ClientAuthModule;
import javax.security.auth.message.module.ServerAuthModule;
import org.apache.geronimo.components.jaspi.model.AuthModuleType;
import org.apache.geronimo.components.jaspi.model.ClientAuthConfigType;
import org.apache.geronimo.components.jaspi.model.ClientAuthContextType;
import org.apache.geronimo.components.jaspi.model.ConfigProviderType;
import org.apache.geronimo.components.jaspi.model.KeyedObjectMapAdapter;
import org.apache.geronimo.components.jaspi.model.MessagePolicyType;
import org.apache.geronimo.components.jaspi.model.ProtectionPolicyType;
import org.apache.geronimo.components.jaspi.model.ServerAuthConfigType;
import org.apache.geronimo.components.jaspi.model.ServerAuthContextType;
import org.apache.geronimo.components.jaspi.model.TargetPolicyType;
import org.apache.geronimo.components.jaspi.model.TargetType;
import org.apache.geronimo.osgi.locator.ProviderLocator;
/**
* @version $Rev:$ $Date:$
*/
public class ConfigProviderImpl implements AuthConfigProvider {
private final Map<String, ClientAuthConfigType> clientConfigTypeMap;
private final Map<String, ServerAuthConfigType> serverAuthConfigMap;
public ConfigProviderImpl(List<ClientAuthConfigType> clientAuthConfigTypes, List<ServerAuthConfigType> serverAuthConfigTypes) {
try {
this.clientConfigTypeMap = new KeyedObjectMapAdapter<ClientAuthConfigType>().unmarshal(clientAuthConfigTypes);
} catch (Exception e) {
throw new RuntimeException(e);
}
try {
this.serverAuthConfigMap = new KeyedObjectMapAdapter<ServerAuthConfigType>().unmarshal(serverAuthConfigTypes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* spec required constructor
* @param properties useless properties map
* @param factory useless factory
*/
public ConfigProviderImpl(Map<String, String> properties, AuthConfigFactory factory) {
throw new RuntimeException("don't call this");
}
public ClientAuthConfig getClientAuthConfig(String layer, String appContext, CallbackHandler handler) throws AuthException, SecurityException {
if (layer == null) {
throw new NullPointerException("messageLayer");
}
if (appContext == null) {
throw new NullPointerException("appContext");
}
ClientAuthConfigType ctx = clientConfigTypeMap.get(ConfigProviderType.getRegistrationKey(layer, appContext));
if (ctx == null) {
ctx = clientConfigTypeMap.get(ConfigProviderType.getRegistrationKey(null, appContext));
}
if (ctx == null) {
ctx = clientConfigTypeMap.get(ConfigProviderType.getRegistrationKey(layer, null));
}
if (ctx == null) {
ctx = clientConfigTypeMap.get(ConfigProviderType.getRegistrationKey(null, null));
}
if (ctx != null) {
return newClientAuthConfig(ctx, layer, appContext, handler);
}
throw new AuthException("No suitable ClientAuthConfig");
}
public ServerAuthConfig getServerAuthConfig(String layer, String appContext, CallbackHandler handler) throws AuthException, SecurityException {
if (layer == null) {
throw new NullPointerException("messageLayer");
}
if (appContext == null) {
throw new NullPointerException("appContext");
}
ServerAuthConfigType ctx = serverAuthConfigMap.get(ConfigProviderType.getRegistrationKey(layer, appContext));
if (ctx == null) {
ctx = serverAuthConfigMap.get(ConfigProviderType.getRegistrationKey(null, appContext));
}
if (ctx == null) {
ctx = serverAuthConfigMap.get(ConfigProviderType.getRegistrationKey(layer, null));
}
if (ctx == null) {
ctx = serverAuthConfigMap.get(ConfigProviderType.getRegistrationKey(null, null));
}
if (ctx != null) {
return newServerAuthConfig(ctx, layer, appContext, handler);
}
throw new AuthException("No suitable ServerAuthConfig");
}
public void refresh() throws SecurityException {
}
public static AuthConfigProvider newConfigProvider(final AuthConfigFactory authConfigFactory, final ConfigProviderType configProviderType) {
AuthConfigProvider provider;
if (configProviderType.getClassName() == null) {
provider = new ConfigProviderImpl(configProviderType.getClientAuthConfig(), configProviderType.getServerAuthConfig());
} else {
try {
provider = java.security.AccessController
.doPrivileged(new PrivilegedExceptionAction<AuthConfigProvider>() {
public AuthConfigProvider run() throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
Class<? extends AuthConfigProvider> cl = ProviderLocator.loadClass(configProviderType.getClassName(), getClass(), Thread.currentThread().getContextClassLoader()).asSubclass(AuthConfigProvider.class);
Constructor<? extends AuthConfigProvider> cnst = cl.getConstructor(Map.class, AuthConfigFactory.class);
return cnst.newInstance(configProviderType.getProperties(), authConfigFactory);
}
});
} catch (PrivilegedActionException e) {
Exception inner = e.getException();
if (inner instanceof InstantiationException) {
throw new SecurityException("AuthConfigFactory error:"
+ inner.getCause().getMessage(), inner.getCause());
} else {
throw new SecurityException("AuthConfigFactory error: " + inner, inner);
}
} catch (Exception e) {
throw new SecurityException("AuthConfigFactory error: " + e, e);
}
}
return provider;
}
static ClientAuthConfig newClientAuthConfig(ClientAuthConfigType clientAuthConfigType, String messageLayer, String appContext, CallbackHandler callbackHandler) throws AuthException {
Map<String, ClientAuthContext> authContextMap = new HashMap<String, ClientAuthContext>();
for (ClientAuthContextType clientAuthContextType: clientAuthConfigType.getClientAuthContext()) {
if (match(clientAuthContextType, messageLayer, appContext)) {
ClientAuthContext clientAuthContext = newClientAuthContext(clientAuthContextType, callbackHandler);
String authContextID = clientAuthContextType.getAuthenticationContextID();
if (authContextID == null) {
authContextID = clientAuthConfigType.getAuthenticationContextID();
}
if (!authContextMap.containsKey(authContextID)) {
authContextMap.put(authContextID, clientAuthContext);
}
}
}
return new ClientAuthConfigImpl(clientAuthConfigType, authContextMap);
}
static ClientAuthContext newClientAuthContext(ClientAuthContextType clientAuthContextType, CallbackHandler callbackHandler) throws AuthException {
List<ClientAuthModule> clientAuthModules = new ArrayList<ClientAuthModule>();
for (AuthModuleType<ClientAuthModule> clientAuthModuleType: clientAuthContextType.getClientAuthModule()) {
ClientAuthModule instance = newAuthModule(clientAuthModuleType, callbackHandler);
clientAuthModules.add(instance);
}
return new ClientAuthContextImpl(clientAuthModules);
}
private static boolean match(ClientAuthContextType clientAuthContextType, String messageLayer, String appContext) {
if (messageLayer == null) throw new NullPointerException("messageLayer");
if (appContext == null) throw new NullPointerException("appContext");
if (messageLayer.equals(clientAuthContextType.getMessageLayer())) {
return appContext.equals(clientAuthContextType.getAppContext()) || clientAuthContextType.getAppContext() == null;
}
if (clientAuthContextType.getMessageLayer() == null) {
return appContext.equals(clientAuthContextType.getAppContext()) || clientAuthContextType.getAppContext() == null;
}
return false;
}
static ServerAuthConfig newServerAuthConfig(ServerAuthConfigType serverAuthConfigType, String messageLayer, String appContext, CallbackHandler callbackHandler) throws AuthException {
Map<String, ServerAuthContext> authContextMap = new HashMap<String, ServerAuthContext>();
for (ServerAuthContextType serverAuthContextType: serverAuthConfigType.getServerAuthContext()) {
if (match(serverAuthContextType, messageLayer, appContext)) {
ServerAuthContext serverAuthContext = newServerAuthContext(serverAuthContextType, callbackHandler);
String authContextID = serverAuthContextType.getAuthenticationContextID();
if (authContextID == null) {
authContextID = serverAuthConfigType.getAuthenticationContextID();
}
if (!authContextMap.containsKey(authContextID)) {
authContextMap.put(authContextID, serverAuthContext);
}
}
}
return new ServerAuthConfigImpl(serverAuthConfigType, authContextMap);
}
static ServerAuthContext newServerAuthContext(ServerAuthContextType serverAuthContextType, CallbackHandler callbackHandler) throws AuthException {
List<ServerAuthModule> serverAuthModules = new ArrayList<ServerAuthModule>();
for (AuthModuleType<ServerAuthModule> serverAuthModuleType: serverAuthContextType.getServerAuthModule()) {
ServerAuthModule instance = newAuthModule(serverAuthModuleType, callbackHandler);
serverAuthModules.add(instance);
}
return new ServerAuthContextImpl(serverAuthModules);
}
private static boolean match(ServerAuthContextType serverAuthContextType, String messageLayer, String appContext) {
if (messageLayer == null) throw new NullPointerException("messageLayer");
if (appContext == null) throw new NullPointerException("appContext");
if (messageLayer.equals(serverAuthContextType.getMessageLayer())) {
return appContext.equals(serverAuthContextType.getAppContext()) || serverAuthContextType.getAppContext() == null;
}
if (serverAuthContextType.getMessageLayer() == null) {
return appContext.equals(serverAuthContextType.getAppContext()) || serverAuthContextType.getAppContext() == null;
}
return false;
}
static <T> T newAuthModule(final AuthModuleType authModuleType, final CallbackHandler callbackHandler) throws AuthException {
T authModule;
try {
authModule = java.security.AccessController
.doPrivileged(new PrivilegedExceptionAction<T>() {
public T run() throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, AuthException {
Class<? extends T> cl = (Class<? extends T>) ProviderLocator.loadClass(authModuleType.getClassName(), getClass(), Thread.currentThread().getContextClassLoader());
Constructor<? extends T> cnst = cl.getConstructor();
T authModule = cnst.newInstance();
Method m = cl.getMethod("initialize", MessagePolicy.class, MessagePolicy.class, CallbackHandler.class, Map.class);
MessagePolicy reqPolicy = newMessagePolicy(authModuleType.getRequestPolicy());
MessagePolicy respPolicy = newMessagePolicy(authModuleType.getResponsePolicy());
m.invoke(authModule, reqPolicy, respPolicy, callbackHandler, authModuleType.getOptions());
return authModule;
}
});
} catch (PrivilegedActionException e) {
Exception inner = e.getException();
if (inner instanceof InstantiationException) {
throw (AuthException) new AuthException("AuthConfigFactory error:"
+ inner.getCause().getMessage()).initCause(inner.getCause());
} else {
throw (AuthException) new AuthException("AuthConfigFactory error: " + inner).initCause(inner);
}
} catch (Exception e) {
throw (AuthException) new AuthException("AuthConfigFactory error: " + e).initCause(e);
}
return authModule;
}
private static MessagePolicy newMessagePolicy(MessagePolicyType messagePolicyType) throws AuthException {
if (messagePolicyType == null) {
return null;
}
if (messagePolicyType.getTargetPolicy().size() == 0) {
return null;
}
MessagePolicy.TargetPolicy[] targetPolicies = new MessagePolicy.TargetPolicy[messagePolicyType.getTargetPolicy().size()];
int i = 0;
for (TargetPolicyType targetPolicyType: messagePolicyType.getTargetPolicy()) {
targetPolicies[i++] = newTargetPolicy(targetPolicyType);
}
return new MessagePolicy(targetPolicies, messagePolicyType.isMandatory());
}
private static MessagePolicy.TargetPolicy newTargetPolicy(TargetPolicyType targetPolicyType) throws AuthException {
MessagePolicy.Target[] targets = new MessagePolicy.Target[targetPolicyType.getTarget().size()];
int i = 0;
for (TargetType targetType: targetPolicyType.getTarget()) {
targets[i++] = newTarget(targetType);
}
return new MessagePolicy.TargetPolicy(targets, newProtectionPolicy(targetPolicyType.getProtectionPolicy()));
}
private static MessagePolicy.Target newTarget(final TargetType targetType) throws AuthException {
try {
return java.security.AccessController
.doPrivileged(new PrivilegedExceptionAction<MessagePolicy.Target>() {
public MessagePolicy.Target run() throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
Class<? extends MessagePolicy.Target> cl = ProviderLocator.loadClass(targetType.getClassName(), getClass(), Thread.currentThread().getContextClassLoader()).asSubclass(MessagePolicy.Target.class);
Constructor<? extends MessagePolicy.Target> cnst = cl.getConstructor();
MessagePolicy.Target target = cnst.newInstance();
return target;
}
});
} catch (PrivilegedActionException e) {
Exception inner = e.getException();
if (inner instanceof InstantiationException) {
throw (AuthException) new AuthException("AuthConfigFactory error:"
+ inner.getCause().getMessage()).initCause(inner.getCause());
} else {
throw (AuthException) new AuthException("AuthConfigFactory error: " + inner).initCause(inner);
}
} catch (Exception e) {
throw (AuthException) new AuthException("AuthConfigFactory error: " + e).initCause(e);
}
}
private static MessagePolicy.ProtectionPolicy newProtectionPolicy(final ProtectionPolicyType protectionPolicyType) throws AuthException {
try {
return java.security.AccessController
.doPrivileged(new PrivilegedExceptionAction<MessagePolicy.ProtectionPolicy>() {
public MessagePolicy.ProtectionPolicy run() throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
Class<? extends MessagePolicy.ProtectionPolicy> cl = ProviderLocator.loadClass(protectionPolicyType.getClassName(), getClass(), Thread.currentThread().getContextClassLoader()).asSubclass(MessagePolicy.ProtectionPolicy.class);
Constructor<? extends MessagePolicy.ProtectionPolicy> cnst = cl.getConstructor();
MessagePolicy.ProtectionPolicy target = cnst.newInstance();
return target;
}
});
} catch (PrivilegedActionException e) {
Exception inner = e.getException();
if (inner instanceof InstantiationException) {
throw (AuthException) new AuthException("AuthConfigFactory error:"
+ inner.getCause().getMessage()).initCause(inner.getCause());
} else {
throw (AuthException) new AuthException("AuthConfigFactory error: " + inner).initCause(inner);
}
} catch (Exception e) {
throw (AuthException) new AuthException("AuthConfigFactory error: " + e).initCause(e);
}
}
}
| 5,634 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/impl/ServerAuthConfigImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.impl;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.config.ServerAuthConfig;
import javax.security.auth.message.config.ServerAuthContext;
import org.apache.geronimo.components.jaspi.model.ServerAuthConfigType;
/**
* @version $Rev:$ $Date:$
*/
public class ServerAuthConfigImpl implements ServerAuthConfig {
private final ServerAuthConfigType serverAuthConfigType;
private final Map<String, ServerAuthContext> serverAuthContextMap;
public ServerAuthConfigImpl(ServerAuthConfigType serverAuthConfigType, Map<String, ServerAuthContext> serverAuthContextMap) {
this.serverAuthConfigType = serverAuthConfigType;
this.serverAuthContextMap = serverAuthContextMap;
}
public ServerAuthContext getAuthContext(String authContextID, Subject serverSubject, Map properties) throws AuthException {
return serverAuthContextMap.get(authContextID);
}
public String getAppContext() {
return serverAuthConfigType.getAppContext();
}
public String getAuthContextID(MessageInfo messageInfo) throws IllegalArgumentException {
return serverAuthConfigType.getAuthContextID(messageInfo);
}
public String getMessageLayer() {
return serverAuthConfigType.getMessageLayer();
}
public boolean isProtected() {
return serverAuthConfigType.isProtected();
}
public void refresh() throws SecurityException {
}
}
| 5,635 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/impl/ClientAuthConfigImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.impl;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.config.ClientAuthConfig;
import javax.security.auth.message.config.ClientAuthContext;
import org.apache.geronimo.components.jaspi.model.ClientAuthConfigType;
/**
* @version $Rev:$ $Date:$
*/
public class ClientAuthConfigImpl implements ClientAuthConfig {
private final ClientAuthConfigType clientAuthConfigType;
private final Map<String, ClientAuthContext> clientAuthContextMap;
public ClientAuthConfigImpl(ClientAuthConfigType clientAuthConfigType, Map<String, ClientAuthContext> clientAuthContextMap) {
this.clientAuthConfigType = clientAuthConfigType;
this.clientAuthContextMap = clientAuthContextMap;
}
public ClientAuthContext getAuthContext(String authContextID, Subject clientSubject, Map properties) throws AuthException {
return clientAuthContextMap.get(authContextID);
}
public String getAppContext() {
return clientAuthConfigType.getAppContext();
}
public String getAuthContextID(MessageInfo messageInfo) throws IllegalArgumentException {
return clientAuthConfigType.getAuthContextID(messageInfo);
}
public String getMessageLayer() {
return clientAuthConfigType.getMessageLayer();
}
public boolean isProtected() {
return clientAuthConfigType.isProtected();
}
public void refresh() throws SecurityException {
}
}
| 5,636 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/impl/ClientAuthContextImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.impl;
import java.util.List;
import javax.security.auth.Subject;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.config.ClientAuthContext;
import javax.security.auth.message.module.ClientAuthModule;
/**
* @version $Rev:$ $Date:$
*/
public class ClientAuthContextImpl implements ClientAuthContext {
private final List<ClientAuthModule> clientAuthModules;
public ClientAuthContextImpl(List<ClientAuthModule> clientAuthModules) {
this.clientAuthModules = clientAuthModules;
}
public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException {
for (ClientAuthModule clientAuthModule : clientAuthModules) {
clientAuthModule.cleanSubject(messageInfo, subject);
}
}
public AuthStatus secureRequest(MessageInfo messageInfo, Subject clientSubject) throws AuthException {
for (ClientAuthModule clientAuthModule : clientAuthModules) {
AuthStatus result = clientAuthModule.secureRequest(messageInfo, clientSubject);
//jaspi spec p 74
if (result == AuthStatus.SUCCESS) {
continue;
}
if (result == AuthStatus.SEND_CONTINUE || result == AuthStatus.FAILURE) {
return result;
}
throw new AuthException("Invalid AuthStatus " + result + " from client auth module: " + clientAuthModule);
}
return AuthStatus.SUCCESS;
}
public AuthStatus validateResponse(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {
for (ClientAuthModule clientAuthModule : clientAuthModules) {
AuthStatus result = clientAuthModule.validateResponse(messageInfo, clientSubject, serviceSubject);
//jaspi spec p 74
if (result == AuthStatus.SUCCESS) {
continue;
}
if (result == AuthStatus.SEND_CONTINUE || result == AuthStatus.FAILURE) {
return result;
}
throw new AuthException("Invalid AuthStatus " + result + " from client auth module: " + clientAuthModule);
}
return AuthStatus.SUCCESS;
}
}
| 5,637 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/impl/ServerAuthContextImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.impl;
import java.util.List;
import javax.security.auth.Subject;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.config.ServerAuthContext;
import javax.security.auth.message.module.ServerAuthModule;
/**
* @version $Rev:$ $Date:$
*/
public class ServerAuthContextImpl implements ServerAuthContext {
private final List<ServerAuthModule> serverAuthModules;
public ServerAuthContextImpl(List<ServerAuthModule> serverAuthModules) {
this.serverAuthModules = serverAuthModules;
}
public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException {
for (ServerAuthModule serverAuthModule : serverAuthModules) {
serverAuthModule.cleanSubject(messageInfo, subject);
}
}
public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException {
for (ServerAuthModule serverAuthModule : serverAuthModules) {
AuthStatus result = serverAuthModule.secureResponse(messageInfo, serviceSubject);
//jaspi spec p 86
if (result == AuthStatus.SEND_SUCCESS) {
continue;
}
if (result == AuthStatus.SEND_CONTINUE || result == AuthStatus.SEND_FAILURE) {
return result;
}
throw new AuthException("Invalid AuthStatus " + result + " from server auth module secureResponse: " + serverAuthModule);
}
return AuthStatus.SEND_SUCCESS;
}
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {
for (ServerAuthModule serverAuthModule : serverAuthModules) {
AuthStatus result = serverAuthModule.validateRequest(messageInfo, clientSubject, serviceSubject);
//jaspi spec p 88
if (result == AuthStatus.SUCCESS) {
continue;
}
if (result == AuthStatus.SEND_SUCCESS || result == AuthStatus.SEND_CONTINUE || result == AuthStatus.FAILURE) {
return result;
}
throw new AuthException("Invalid AuthStatus " + result + " from server auth module validateRequest: " + serverAuthModule);
}
return AuthStatus.SUCCESS;
}
}
| 5,638 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/ClientAuthContextType.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.5-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2008.07.15 at 04:13:34 PM PDT
//
package org.apache.geronimo.components.jaspi.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.config.ClientAuthContext;
import javax.security.auth.message.module.ClientAuthModule;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.geronimo.components.jaspi.impl.ClientAuthContextImpl;
/**
* <p>Java class for clientAuthContextType complex type.
* <p/>
* <p>The following schema fragment specifies the expected content contained within this class.
* <p/>
* <pre>
* <complexType name="clientAuthContextType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="messageLayer" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="appContext" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="authenticationContextID" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="clientAuthModule" type="{http://geronimo.apache.org/xml/ns/geronimo-jaspi}authModuleType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
* @version $Rev: 939768 $ $Date: 2010-04-30 11:26:46 -0700 (Fri, 30 Apr 2010) $
*/
@XmlRootElement(name = "clientAuthContext", namespace = "http://geronimo.apache.org/xml/ns/geronimo-jaspi")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "clientAuthContextType", propOrder = {
"messageLayer",
"appContext",
"authenticationContextID",
"clientAuthModule"
})
public class ClientAuthContextType
implements Serializable {
private final static long serialVersionUID = 12343L;
protected String messageLayer;
protected String appContext;
@XmlElement(required = true)
protected String authenticationContextID;
protected List<AuthModuleType<ClientAuthModule>> clientAuthModule;
public ClientAuthContextType() {
}
public ClientAuthContextType(String messageLayer, String appContext, String authenticationContextID, AuthModuleType<ClientAuthModule> clientAuthModule) {
this.messageLayer = messageLayer;
this.appContext = appContext;
this.authenticationContextID = authenticationContextID;
this.clientAuthModule = Collections.singletonList(clientAuthModule);
}
/**
* Gets the value of the messageLayer property.
*
* @return possible object is
* {@link String }
*/
public String getMessageLayer() {
return messageLayer;
}
/**
* Sets the value of the messageLayer property.
*
* @param value allowed object is
* {@link String }
*/
public void setMessageLayer(String value) {
this.messageLayer = value;
}
/**
* Gets the value of the appContext property.
*
* @return possible object is
* {@link String }
*/
public String getAppContext() {
return appContext;
}
/**
* Sets the value of the appContext property.
*
* @param value allowed object is
* {@link String }
*/
public void setAppContext(String value) {
this.appContext = value;
}
/**
* Gets the value of the authenticationContextID property.
*
* @return possible object is
* {@link String }
*/
public String getAuthenticationContextID() {
return authenticationContextID;
}
public String getAuthenticationContextID(MessageInfo messageInfo) {
return authenticationContextID;
}
/**
* Sets the value of the authenticationContextID property.
*
* @param value allowed object is
* {@link String }
*/
public void setAuthenticationContextID(String value) {
this.authenticationContextID = value;
}
/**
* Gets the value of the clientAuthModule property.
* <p/>
* <p/>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the clientAuthModule property.
* <p/>
* <p/>
* For example, to add a new item, do as follows:
* <pre>
* getClientAuthModule().add(newItem);
* </pre>
* <p/>
* <p/>
* <p/>
* Objects of the following type(s) are allowed in the list
* {@link AuthModuleType }
*
* @return list of client auth module wrappers
*/
public List<AuthModuleType<ClientAuthModule>> getClientAuthModule() {
if (clientAuthModule == null) {
clientAuthModule = new ArrayList<AuthModuleType<ClientAuthModule>>();
}
return this.clientAuthModule;
}
}
| 5,639 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/JaspiType.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.5-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2008.07.15 at 04:13:34 PM PDT
//
package org.apache.geronimo.components.jaspi.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for jaspiType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="jaspiType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="configProvider" type="{http://geronimo.apache.org/xml/ns/geronimo-jaspi}configProviderType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
* @version $Rev: 939768 $ $Date: 2010-04-30 11:26:46 -0700 (Fri, 30 Apr 2010) $
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "jaspiType", propOrder = {
"configProvider"
})
public class JaspiType
implements Serializable
{
private final static long serialVersionUID = 12343L;
protected List<ConfigProviderType> configProvider;
// @XmlJavaTypeAdapter(KeyedObjectMapAdapter.class)
// protected Map<String, ConfigProviderType> configProvider;
/**
* Gets the value of the configProvider property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the configProvider property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getConfigProvider().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ConfigProviderType }
*
*
* @return list of Config Provider
*/
public List<ConfigProviderType> getConfigProvider() {
if (configProvider == null) {
configProvider = new ArrayList<ConfigProviderType>();
}
return this.configProvider;
}
}
| 5,640 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/JaspiUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.model;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.config.AuthConfigProvider;
import javax.security.auth.message.module.ClientAuthModule;
import javax.security.auth.message.module.ServerAuthModule;
import org.apache.geronimo.components.jaspi.impl.ConfigProviderImpl;
/**
* Convenience methods to wrap various jaspi objects into AuthConfigProvider instances, ready to be registered.
* @version $Rev: 939768 $ $Date: 2010-04-30 11:26:46 -0700 (Fri, 30 Apr 2010) $
*/
public class JaspiUtil {
private JaspiUtil() {
}
public static AuthConfigProvider wrapAuthConfigProvider(ConfigProviderType configProviderType) {
return new ConfigProviderImpl(configProviderType.getClientAuthConfig(), configProviderType.getServerAuthConfig());
}
public static AuthConfigProvider wrapClientAuthConfig(ClientAuthConfigType clientAuthConfigType) throws AuthException {
List<ClientAuthConfigType> clientAuthConfig = Collections.singletonList(clientAuthConfigType);
return new ConfigProviderImpl(clientAuthConfig, Collections.<ServerAuthConfigType>emptyList());
}
public static AuthConfigProvider wrapClientAuthContext(ClientAuthContextType clientAuthContextType, boolean _protected) throws AuthException {
ClientAuthConfigType clientAuthConfigType = new ClientAuthConfigType(clientAuthContextType, _protected);
return wrapClientAuthConfig(clientAuthConfigType);
}
public static AuthConfigProvider wrapClientAuthModule(String messageLayer, String appContext, String authenticationContextID, AuthModuleType<ClientAuthModule> clientAuthModuleType, boolean _protected) throws AuthException {
ClientAuthContextType clientAuthContextType = new ClientAuthContextType(messageLayer, appContext, authenticationContextID, clientAuthModuleType);
return wrapClientAuthContext(clientAuthContextType, _protected);
}
public static AuthConfigProvider wrapServerAuthConfig(ServerAuthConfigType serverAuthConfigType) throws AuthException {
List<ServerAuthConfigType> serverAuthConfig = Collections.singletonList(serverAuthConfigType);
return new ConfigProviderImpl(Collections.<ClientAuthConfigType>emptyList(), serverAuthConfig);
}
public static AuthConfigProvider wrapServerAuthContext(ServerAuthContextType serverAuthContextType, boolean _protected) throws AuthException {
ServerAuthConfigType serverAuthConfigType = new ServerAuthConfigType(serverAuthContextType, _protected);
return wrapServerAuthConfig(serverAuthConfigType);
}
public static AuthConfigProvider wrapServerAuthModule(String messageLayer, String appContext, String authenticationContextID, AuthModuleType<ServerAuthModule> serverAuthModuleType, boolean _protected) throws AuthException {
ServerAuthContextType serverAuthContextType = new ServerAuthContextType(messageLayer, appContext, authenticationContextID, serverAuthModuleType);
return wrapServerAuthContext(serverAuthContextType, _protected);
}
}
| 5,641 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/StringMapAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.model;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.xml.bind.annotation.adapters.XmlAdapter;
/**
* jaxb helper class for maps
*
* @version $Rev: 939768 $ $Date: 2010-04-30 11:26:46 -0700 (Fri, 30 Apr 2010) $
*/
public class StringMapAdapter extends XmlAdapter<String, Map<String, String>> {
public Map<String, String> unmarshal(String s) throws Exception {
if (s == null) {
return null;
}
Properties properties = new Properties();
ByteArrayInputStream in = new ByteArrayInputStream(s.getBytes());
properties.load(in);
Map<String, String> map = new HashMap<String, String>(properties.size());
for (Map.Entry entry: properties.entrySet()) {
map.put((String)entry.getKey(), (String)entry.getValue());
}
return map;
}
public String marshal(Map<String, String> map) throws Exception {
if (map == null) {
return "";
}
Properties properties = new Properties();
properties.putAll(map);
ByteArrayOutputStream out = new ByteArrayOutputStream();
properties.store(out, null);
return new String(out.toByteArray());
}
}
| 5,642 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/AuthModuleType.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.5-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2008.07.15 at 04:13:34 PM PDT
//
package org.apache.geronimo.components.jaspi.model;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.MessagePolicy;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.geronimo.osgi.locator.ProviderLocator;
/**
* <p>Java class for authModuleType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="authModuleType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="className" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="requestPolicy" type="{http://geronimo.apache.org/xml/ns/geronimo-jaspi}messagePolicyType"/>
* <element name="responsePolicy" type="{http://geronimo.apache.org/xml/ns/geronimo-jaspi}messagePolicyType"/>
* <element name="options" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
* @version $Rev: $ $Date: $
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "authModuleType", propOrder = {
"className",
"classLoaderName",
"requestPolicy",
"responsePolicy",
"options"
})
public class AuthModuleType<T>
implements Serializable
{
private final static long serialVersionUID = 12343L;
@XmlElement(required = true)
protected String className;
protected String classLoaderName;
protected MessagePolicyType requestPolicy;
protected MessagePolicyType responsePolicy;
@XmlJavaTypeAdapter(StringMapAdapter.class)
protected Map<String, String> options;
/**
* Gets the value of the className property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClassName() {
return className;
}
/**
* Sets the value of the className property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClassName(String value) {
this.className = value;
}
/**
* Gets the value of the requestPolicy property.
*
* @return
* possible object is
* {@link MessagePolicyType }
*
*/
public MessagePolicyType getRequestPolicy() {
return requestPolicy;
}
/**
* Sets the value of the requestPolicy property.
*
* @param value
* allowed object is
* {@link MessagePolicyType }
*
*/
public void setRequestPolicy(MessagePolicyType value) {
this.requestPolicy = value;
}
/**
* Gets the value of the responsePolicy property.
*
* @return
* possible object is
* {@link MessagePolicyType }
*
*/
public MessagePolicyType getResponsePolicy() {
return responsePolicy;
}
/**
* Sets the value of the responsePolicy property.
*
* @param value
* allowed object is
* {@link MessagePolicyType }
*
*/
public void setResponsePolicy(MessagePolicyType value) {
this.responsePolicy = value;
}
/**
* Gets the value of the options property.
*
* @return
* possible object is
* {@link Map<String, String> }
*
*/
public Map<String, String> getOptions() {
return options;
}
/**
* Sets the value of the options property.
*
* @param value
* allowed object is
* {@link Map<String, String> }
*
*/
public void setOptions(Map<String, String> value) {
this.options = value;
}
public String getClassLoaderName() {
return classLoaderName;
}
public void setClassLoaderName(String classLoaderName) {
this.classLoaderName = classLoaderName;
}
}
| 5,643 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/KeyedObject.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.model;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.message.AuthException;
/**
* @version $Rev: 939768 $ $Date: 2010-04-30 11:26:46 -0700 (Fri, 30 Apr 2010) $
*/
public interface KeyedObject {
String getKey();
}
| 5,644 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/ObjectFactory.java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.5-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2008.07.29 at 04:09:58 PM PDT
//
package org.apache.geronimo.components.jaspi.model;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the org.apache.geronimo.xml.ns.geronimo_jaspi package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _ServerAuthContext_QNAME = new QName("http://geronimo.apache.org/xml/ns/geronimo-jaspi", "serverAuthContext");
private final static QName _ClientAuthConfig_QNAME = new QName("http://geronimo.apache.org/xml/ns/geronimo-jaspi", "clientAuthConfig");
private final static QName _ClientAuthContext_QNAME = new QName("http://geronimo.apache.org/xml/ns/geronimo-jaspi", "clientAuthContext");
private final static QName _ServerAuthConfig_QNAME = new QName("http://geronimo.apache.org/xml/ns/geronimo-jaspi", "serverAuthConfig");
private final static QName _Jaspi_QNAME = new QName("http://geronimo.apache.org/xml/ns/geronimo-jaspi", "jaspi");
private final static QName _ServerAuthModule_QNAME = new QName("http://geronimo.apache.org/xml/ns/geronimo-jaspi", "serverAuthModule");
private final static QName _ConfigProvider_QNAME = new QName("http://geronimo.apache.org/xml/ns/geronimo-jaspi", "configProvider");
private final static QName _ClientAuthModule_QNAME = new QName("http://geronimo.apache.org/xml/ns/geronimo-jaspi", "clientAuthModule");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.apache.geronimo.xml.ns.geronimo_jaspi
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link AuthModuleType }
*
*/
public AuthModuleType createAuthModuleType() {
return new AuthModuleType();
}
/**
* Create an instance of {@link ProtectionPolicyType }
*
*/
public ProtectionPolicyType createProtectionPolicyType() {
return new ProtectionPolicyType();
}
/**
* Create an instance of {@link JaspiType }
*
*/
public JaspiType createJaspiType() {
return new JaspiType();
}
/**
* Create an instance of {@link ClientAuthConfigType }
*
*/
public ClientAuthConfigType createClientAuthConfigType() {
return new ClientAuthConfigType();
}
/**
* Create an instance of {@link ServerAuthContextType }
*
*/
public ServerAuthContextType createServerAuthContextType() {
return new ServerAuthContextType();
}
/**
* Create an instance of {@link ClientAuthContextType }
*
*/
public ClientAuthContextType createClientAuthContextType() {
return new ClientAuthContextType();
}
/**
* Create an instance of {@link MessagePolicyType }
*
*/
public MessagePolicyType createMessagePolicyType() {
return new MessagePolicyType();
}
/**
* Create an instance of {@link TargetPolicyType }
*
*/
public TargetPolicyType createTargetPolicyType() {
return new TargetPolicyType();
}
/**
* Create an instance of {@link ConfigProviderType }
*
*/
public ConfigProviderType createConfigProviderType() {
return new ConfigProviderType();
}
/**
* Create an instance of {@link TargetType }
*
*/
public TargetType createTargetType() {
return new TargetType();
}
/**
* Create an instance of {@link ServerAuthConfigType }
*
*/
public ServerAuthConfigType createServerAuthConfigType() {
return new ServerAuthConfigType();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link ServerAuthContextType }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://geronimo.apache.org/xml/ns/geronimo-jaspi", name = "serverAuthContext")
public JAXBElement<ServerAuthContextType> createServerAuthContext(ServerAuthContextType value) {
return new JAXBElement<ServerAuthContextType>(_ServerAuthContext_QNAME, ServerAuthContextType.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link ClientAuthConfigType }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://geronimo.apache.org/xml/ns/geronimo-jaspi", name = "clientAuthConfig")
public JAXBElement<ClientAuthConfigType> createClientAuthConfig(ClientAuthConfigType value) {
return new JAXBElement<ClientAuthConfigType>(_ClientAuthConfig_QNAME, ClientAuthConfigType.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link ClientAuthContextType }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://geronimo.apache.org/xml/ns/geronimo-jaspi", name = "clientAuthContext")
public JAXBElement<ClientAuthContextType> createClientAuthContext(ClientAuthContextType value) {
return new JAXBElement<ClientAuthContextType>(_ClientAuthContext_QNAME, ClientAuthContextType.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link ServerAuthConfigType }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://geronimo.apache.org/xml/ns/geronimo-jaspi", name = "serverAuthConfig")
public JAXBElement<ServerAuthConfigType> createServerAuthConfig(ServerAuthConfigType value) {
return new JAXBElement<ServerAuthConfigType>(_ServerAuthConfig_QNAME, ServerAuthConfigType.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link JaspiType }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://geronimo.apache.org/xml/ns/geronimo-jaspi", name = "jaspi")
public JAXBElement<JaspiType> createJaspi(JaspiType value) {
return new JAXBElement<JaspiType>(_Jaspi_QNAME, JaspiType.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link AuthModuleType }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://geronimo.apache.org/xml/ns/geronimo-jaspi", name = "serverAuthModule")
public JAXBElement<AuthModuleType> createServerAuthModule(AuthModuleType value) {
return new JAXBElement<AuthModuleType>(_ServerAuthModule_QNAME, AuthModuleType.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link ConfigProviderType }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://geronimo.apache.org/xml/ns/geronimo-jaspi", name = "configProvider")
public JAXBElement<ConfigProviderType> createConfigProvider(ConfigProviderType value) {
return new JAXBElement<ConfigProviderType>(_ConfigProvider_QNAME, ConfigProviderType.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link AuthModuleType }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://geronimo.apache.org/xml/ns/geronimo-jaspi", name = "clientAuthModule")
public JAXBElement<AuthModuleType> createClientAuthModule(AuthModuleType value) {
return new JAXBElement<AuthModuleType>(_ClientAuthModule_QNAME, AuthModuleType.class, null, value);
}
}
| 5,645 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/JaspiXmlUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.model;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.message.module.ClientAuthModule;
import javax.security.auth.message.module.ServerAuthModule;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.xml.sax.SAXException;
/**
* @version $Rev: 939768 $ $Date: 2010-04-30 11:26:46 -0700 (Fri, 30 Apr 2010) $
*/
public class JaspiXmlUtil {
public static final XMLInputFactory XMLINPUT_FACTORY = XMLInputFactory.newInstance();
public static final JAXBContext JASPI_CONTEXT;
// private static KeyedObjectMapAdapter configProviderMapAdapter = new KeyedObjectMapAdapter(ConfigProviderType.class);
static {
try {
JASPI_CONTEXT = JAXBContext.newInstance(JaspiType.class, ConfigProviderType.class, ClientAuthConfigType.class, ClientAuthContextType.class, ServerAuthConfigType.class, ServerAuthContextType.class, AuthModuleType.class);
// JASPI_CONTEXT = com.envoisolutions.sxc.jaxb.JAXBContextImpl.newInstance(new Class[] {JaspiType.class, ConfigProviderType.class, ClientAuthConfigType.class, ClientAuthContextType.class, ServerAuthConfigType.class, ServerAuthContextType.class, AuthModuleType.class}, Collections.singletonMap("com.envoisolutions.sxc.generate", "false"));
} catch (JAXBException e) {
throw new RuntimeException("Could not create jaxb contexts for plugin types", e);
}
}
public static void initialize(CallbackHandler callbackHandler) {
KeyedObjectMapAdapter.staticCallbackHandler = callbackHandler;
}
public static <T> void write(JAXBElement<T> element, Writer out) throws JAXBException {
Marshaller marshaller = JASPI_CONTEXT.createMarshaller();
marshaller.setProperty("jaxb.formatted.output", true);
marshaller.marshal(element, out);
}
public static <T>T load(Reader in, Class<T> clazz) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
XMLStreamReader xmlStream = XMLINPUT_FACTORY.createXMLStreamReader(in);
try {
return load(xmlStream, clazz);
} finally {
xmlStream.close();
}
}
public static Object untypedLoad(Reader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
XMLStreamReader xmlStream = XMLINPUT_FACTORY.createXMLStreamReader(in);
try {
return untypedLoad(xmlStream);
} finally {
xmlStream.close();
}
}
public static <T>T load(XMLStreamReader in, Class<T> clazz) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
Unmarshaller unmarshaller = JASPI_CONTEXT.createUnmarshaller();
JAXBElement<T> element = unmarshaller.unmarshal(in, clazz);
return element.getValue();
}
public static Object untypedLoad(XMLStreamReader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
Unmarshaller unmarshaller = JASPI_CONTEXT.createUnmarshaller();
return unmarshaller.unmarshal(in);
}
public static void writeJaspi(JaspiType metadata, Writer out) throws XMLStreamException, JAXBException {
write(new ObjectFactory().createJaspi(metadata), out);
}
public static JaspiType loadJaspi(Reader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, JaspiType.class);
}
public static JaspiType loadJaspi(XMLStreamReader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, JaspiType.class);
}
public static void writeConfigProvider(ConfigProviderType metadata, Writer out) throws XMLStreamException, JAXBException {
write(new ObjectFactory().createConfigProvider(metadata), out);
}
public static ConfigProviderType loadConfigProvider(Reader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, ConfigProviderType.class);
}
public static ConfigProviderType loadConfigProvider(XMLStreamReader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, ConfigProviderType.class);
}
public static void writeClientAuthConfig(ClientAuthConfigType metadata, Writer out) throws XMLStreamException, JAXBException {
write(new ObjectFactory().createClientAuthConfig(metadata), out);
}
public static ClientAuthConfigType loadClientAuthConfig(Reader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, ClientAuthConfigType.class);
}
public static ClientAuthConfigType loadClientAuthConfig(XMLStreamReader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, ClientAuthConfigType.class);
}
public static void writeClientAuthContext(ClientAuthContextType metadata, Writer out) throws XMLStreamException, JAXBException {
write(new ObjectFactory().createClientAuthContext(metadata), out);
}
public static ClientAuthContextType loadClientAuthContext(Reader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, ClientAuthContextType.class);
}
public static ClientAuthContextType loadClientAuthContext(XMLStreamReader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, ClientAuthContextType.class);
}
public static void writeClientAuthModule(AuthModuleType metadata, Writer out) throws XMLStreamException, JAXBException {
write(new ObjectFactory().createClientAuthModule(metadata), out);
}
public static AuthModuleType<ClientAuthModule> loadClientAuthModule(Reader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, AuthModuleType.class);
}
public static AuthModuleType<ClientAuthModule> loadClientAuthModule(XMLStreamReader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, AuthModuleType.class);
}
public static void writeServerAuthConfig(ServerAuthConfigType metadata, Writer out) throws XMLStreamException, JAXBException {
write(new ObjectFactory().createServerAuthConfig(metadata), out);
}
public static ServerAuthConfigType loadServerAuthConfig(Reader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, ServerAuthConfigType.class);
}
public static ServerAuthConfigType loadServerAuthConfig(XMLStreamReader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, ServerAuthConfigType.class);
}
public static void writeServerAuthContext(ServerAuthContextType metadata, Writer out) throws XMLStreamException, JAXBException {
write(new ObjectFactory().createServerAuthContext(metadata), out);
}
public static ServerAuthContextType loadServerAuthContext(Reader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, ServerAuthContextType.class);
}
public static ServerAuthContextType loadServerAuthContext(XMLStreamReader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, ServerAuthContextType.class);
}
public static void writeServerAuthModule(AuthModuleType metadata, Writer out) throws XMLStreamException, JAXBException {
write(new ObjectFactory().createServerAuthModule(metadata), out);
}
public static AuthModuleType<ServerAuthModule> loadServerAuthModule(Reader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, AuthModuleType.class);
}
public static AuthModuleType<ServerAuthModule> loadServerAuthModule(XMLStreamReader in) throws ParserConfigurationException, IOException, SAXException, JAXBException, XMLStreamException {
return load(in, AuthModuleType.class);
}
}
| 5,646 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/ServerAuthContextType.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.5-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2008.07.15 at 04:13:34 PM PDT
//
package org.apache.geronimo.components.jaspi.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.config.ServerAuthContext;
import javax.security.auth.message.module.ServerAuthModule;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import org.apache.geronimo.components.jaspi.impl.ServerAuthContextImpl;
/**
* <p>Java class for serverAuthContextType complex type.
* <p/>
* <p>The following schema fragment specifies the expected content contained within this class.
* <p/>
* <pre>
* <complexType name="serverAuthContextType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="messageLayer" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="appContext" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="authenticationContextID" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="serverAuthModule" type="{http://geronimo.apache.org/xml/ns/geronimo-jaspi}authModuleType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
* @version $Rev: 939768 $ $Date: 2010-04-30 11:26:46 -0700 (Fri, 30 Apr 2010) $
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "serverAuthContextType", propOrder = {
"messageLayer",
"appContext",
"authenticationContextID",
"serverAuthModule"
})
public class ServerAuthContextType
implements Serializable {
private final static long serialVersionUID = 12343L;
protected String messageLayer;
protected String appContext;
protected String authenticationContextID;
protected List<AuthModuleType<ServerAuthModule>> serverAuthModule;
public ServerAuthContextType() {
}
public ServerAuthContextType(String messageLayer, String appContext, String authenticationContextID, AuthModuleType<ServerAuthModule> serverAuthModule) {
this.messageLayer = messageLayer;
this.appContext = appContext;
this.authenticationContextID = authenticationContextID;
this.serverAuthModule = Collections.singletonList(serverAuthModule);
}
/**
* Gets the value of the messageLayer property.
*
* @return possible object is
* {@link String }
*/
public String getMessageLayer() {
return messageLayer;
}
/**
* Sets the value of the messageLayer property.
*
* @param value allowed object is
* {@link String }
*/
public void setMessageLayer(String value) {
this.messageLayer = value;
}
/**
* Gets the value of the appContext property.
*
* @return possible object is
* {@link String }
*/
public String getAppContext() {
return appContext;
}
/**
* Sets the value of the appContext property.
*
* @param value allowed object is
* {@link String }
*/
public void setAppContext(String value) {
this.appContext = value;
}
/**
* Gets the value of the authenticationContextID property.
*
* @return possible object is
* {@link String }
*/
public String getAuthenticationContextID() {
return authenticationContextID;
}
public String getAuthenticationContextID(MessageInfo messageInfo) {
return authenticationContextID;
}
/**
* Sets the value of the authenticationContextID property.
*
* @param value allowed object is
* {@link String }
*/
public void setAuthenticationContextID(String value) {
this.authenticationContextID = value;
}
/**
* Gets the value of the serverAuthModule property.
* <p/>
* <p/>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the serverAuthModule property.
* <p/>
* <p/>
* For example, to add a new item, do as follows:
* <pre>
* getServerAuthModule().add(newItem);
* </pre>
* <p/>
* <p/>
* <p/>
* Objects of the following type(s) are allowed in the list
* {@link AuthModuleType }
* @return list of Server auth modules in this context
*/
public List<AuthModuleType<ServerAuthModule>> getServerAuthModule() {
if (serverAuthModule == null) {
serverAuthModule = new ArrayList<AuthModuleType<ServerAuthModule>>();
}
return this.serverAuthModule;
}
}
| 5,647 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/TargetPolicyType.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.5-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2008.07.15 at 04:13:34 PM PDT
//
package org.apache.geronimo.components.jaspi.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.MessagePolicy;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for targetPolicyType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="targetPolicyType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="protectionPolicy" type="{http://geronimo.apache.org/xml/ns/geronimo-jaspi}protectionPolicyType"/>
* <element name="target" type="{http://geronimo.apache.org/xml/ns/geronimo-jaspi}targetType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
* @version $Rev: 939768 $ $Date: 2010-04-30 11:26:46 -0700 (Fri, 30 Apr 2010) $
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "targetPolicyType", propOrder = {
"protectionPolicy",
"target"
})
public class TargetPolicyType
implements Serializable
{
private final static long serialVersionUID = 12343L;
@XmlElement(required = true)
protected ProtectionPolicyType protectionPolicy;
protected List<TargetType> target;
/**
* Gets the value of the protectionPolicy property.
*
* @return
* possible object is
* {@link ProtectionPolicyType }
*
*/
public ProtectionPolicyType getProtectionPolicy() {
return protectionPolicy;
}
/**
* Sets the value of the protectionPolicy property.
*
* @param value
* allowed object is
* {@link ProtectionPolicyType }
*
*/
public void setProtectionPolicy(ProtectionPolicyType value) {
this.protectionPolicy = value;
}
/**
* Gets the value of the target property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the target property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTarget().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TargetType }
*
*
* @return list of targets
*/
public List<TargetType> getTarget() {
if (target == null) {
target = new ArrayList<TargetType>();
}
return this.target;
}
}
| 5,648 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/TargetType.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.5-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2008.07.15 at 04:13:34 PM PDT
//
package org.apache.geronimo.components.jaspi.model;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.MessagePolicy;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.geronimo.osgi.locator.ProviderLocator;
/**
* <p>Java class for targetType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="targetType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="className" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
* @version $Rev: 939768 $ $Date: 2010-04-30 11:26:46 -0700 (Fri, 30 Apr 2010) $
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "targetType", propOrder = {
"className"
})
public class TargetType
implements Serializable
{
private final static long serialVersionUID = 12343L;
@XmlElement(required = true)
protected String className;
/**
* Gets the value of the className property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClassName() {
return className;
}
/**
* Sets the value of the className property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClassName(String value) {
this.className = value;
}
}
| 5,649 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/ProtectionPolicyType.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.5-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2008.07.15 at 04:13:34 PM PDT
//
package org.apache.geronimo.components.jaspi.model;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.MessagePolicy;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.geronimo.osgi.locator.ProviderLocator;
/**
* <p>Java class for protectionPolicyType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="protectionPolicyType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="className" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
* @version $Rev: 939768 $ $Date: 2010-04-30 11:26:46 -0700 (Fri, 30 Apr 2010) $
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "protectionPolicyType", propOrder = {
"className"
})
public class ProtectionPolicyType
implements Serializable
{
private final static long serialVersionUID = 12343L;
@XmlElement(required = true)
protected String className;
/**
* Gets the value of the className property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClassName() {
return className;
}
/**
* Sets the value of the className property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClassName(String value) {
this.className = value;
}
}
| 5,650 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/ConfigProviderType.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.5-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2008.07.15 at 04:13:34 PM PDT
//
package org.apache.geronimo.components.jaspi.model;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.message.config.AuthConfigFactory;
import javax.security.auth.message.config.AuthConfigProvider;
import javax.security.auth.message.config.RegistrationListener;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.geronimo.components.jaspi.impl.ConfigProviderImpl;
import org.apache.geronimo.osgi.locator.ProviderLocator;
/**
* <p>Java class for configProviderType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="configProviderType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="messageLayer" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="appContext" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <choice>
* <sequence>
* <element name="className" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="properties" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* <sequence>
* <element name="clientAuthConfig" type="{http://geronimo.apache.org/xml/ns/geronimo-jaspi}clientAuthConfigType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="serverAuthConfig" type="{http://geronimo.apache.org/xml/ns/geronimo-jaspi}serverAuthConfigType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </choice>
* <element name="persistent" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="classLoaderName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlRootElement(name = "configProvider", namespace = "http://geronimo.apache.org/xml/ns/geronimo-jaspi")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "configProviderType", propOrder = {
"messageLayer",
"appContext",
"description",
"className",
"properties",
"clientAuthConfig",
"serverAuthConfig",
"persistent",
"classLoaderName"
})
public class ConfigProviderType
implements Serializable
{
private final static long serialVersionUID = 12343L;
protected String messageLayer;
protected String appContext;
protected String description;
protected String className;
@XmlElement(required = true)
@XmlJavaTypeAdapter(StringMapAdapter.class)
protected Map<String, String> properties;
private List<ClientAuthConfigType> clientAuthConfig;
private List<ServerAuthConfigType> serverAuthConfig;
protected Boolean persistent = Boolean.FALSE;
protected String classLoaderName;
public ConfigProviderType() {
}
public ConfigProviderType(String messageLayer, String appContext, boolean persistent, AuthConfigFactory authConfigFactory) {
this.messageLayer = messageLayer;
this.appContext = appContext;
this.persistent = persistent;
}
/**
* Gets the value of the messageLayer property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMessageLayer() {
return messageLayer;
}
/**
* Sets the value of the messageLayer property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessageLayer(String value) {
this.messageLayer = value;
}
/**
* Gets the value of the appContext property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAppContext() {
return appContext;
}
/**
* Sets the value of the appContext property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAppContext(String value) {
this.appContext = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the className property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClassName() {
return className;
}
/**
* Sets the value of the className property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClassName(String value) {
this.className = value;
}
/**
* Gets the value of the properties property.
*
* @return
* possible object is
* {@link String }
*
*/
public Map<String, String> getProperties() {
return properties;
}
/**
* Sets the value of the properties property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProperties(Map<String, String> value) {
this.properties = value;
}
/**
* Gets the value of the clientAuthConfig property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the clientAuthConfig property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getClientAuthConfig().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ClientAuthConfigType }
*
* @return map of id to client auth config
*/
public List<ClientAuthConfigType> getClientAuthConfig() {
if (clientAuthConfig == null) {
clientAuthConfig = new ArrayList<ClientAuthConfigType>();
}
return clientAuthConfig;
}
/**
* Gets the value of the serverAuthConfig property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the serverAuthConfig property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getServerAuthConfig().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ServerAuthConfigType }
*
* @return map of id to server auth config
*/
public List<ServerAuthConfigType> getServerAuthConfig() {
if (serverAuthConfig == null) {
serverAuthConfig = new ArrayList<ServerAuthConfigType>();
}
return serverAuthConfig;
}
/**
* Gets the value of the persistent property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isPersistent() {
return persistent;
}
/**
* Sets the value of the persistent property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setPersistent(boolean value) {
this.persistent = value;
}
public String getClassLoaderName() {
return classLoaderName;
}
public void setClassLoaderName(String classLoaderName) {
this.classLoaderName = classLoaderName;
}
public static String getRegistrationKey(String layer, String appContext) {
return layer + "/" + appContext;
}
public String getKey() {
return getRegistrationKey(getMessageLayer(), getAppContext());
}
}
| 5,651 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/MessagePolicyType.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.5-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2008.07.15 at 04:13:34 PM PDT
//
package org.apache.geronimo.components.jaspi.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.MessagePolicy;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for messagePolicyType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="messagePolicyType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="targetPolicy" type="{http://geronimo.apache.org/xml/ns/geronimo-jaspi}targetPolicyType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="mandatory" type="{http://www.w3.org/2001/XMLSchema}boolean" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
* @version $Rev: 939768 $ $Date: 2010-04-30 11:26:46 -0700 (Fri, 30 Apr 2010) $
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "messagePolicyType", propOrder = {
"targetPolicy"
})
public class MessagePolicyType
implements Serializable
{
private final static long serialVersionUID = 12343L;
protected List<TargetPolicyType> targetPolicy;
@XmlAttribute
protected Boolean mandatory;
/**
* Gets the value of the targetPolicy property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the targetPolicy property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTargetPolicy().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TargetPolicyType }
*
*
* @return list of target policies
*/
public List<TargetPolicyType> getTargetPolicy() {
if (targetPolicy == null) {
targetPolicy = new ArrayList<TargetPolicyType>();
}
return this.targetPolicy;
}
/**
* Gets the value of the mandatory property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isMandatory() {
return mandatory;
}
/**
* Sets the value of the mandatory property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setMandatory(boolean value) {
this.mandatory = value;
}
}
| 5,652 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/KeyedObjectMapAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.components.jaspi.model;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
import javax.xml.bind.annotation.adapters.XmlAdapter;
/**
* @version $Rev: 939768 $ $Date: 2010-04-30 11:26:46 -0700 (Fri, 30 Apr 2010) $
*/
public class KeyedObjectMapAdapter<T extends KeyedObject> extends XmlAdapter<List<T>, Map<String, T>> {
public static CallbackHandler staticCallbackHandler;
private final CallbackHandler callbackHandler;
// private final Class<T> type;
public KeyedObjectMapAdapter(CallbackHandler callbackHandler) {
this.callbackHandler = callbackHandler;
// this.type = type;
}
public KeyedObjectMapAdapter() {
this(staticCallbackHandler);
}
public Map<String, T> unmarshal(List<T> configProviderTypes) throws Exception {
Map<String, T> map = new HashMap<String, T>();
if (configProviderTypes != null) {
for (T configProviderType : configProviderTypes) {
if (configProviderType != null) {
String key = configProviderType.getKey();
map.put(key, configProviderType);
}
}
}
return map;
}
public ArrayList<T> marshal(Map<String, T> stringConfigProviderTypeMap) throws Exception {
if (stringConfigProviderTypeMap == null) {
return null;
}
ArrayList<T> list = new ArrayList<T>();
for (T configProviderType : stringConfigProviderTypeMap.values()) {
list.add(configProviderType);
}
return list;
}
}
| 5,653 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/ClientAuthConfigType.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.5-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2008.07.15 at 04:13:34 PM PDT
//
package org.apache.geronimo.components.jaspi.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.config.ClientAuthConfig;
import javax.security.auth.message.config.ClientAuthContext;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.geronimo.components.jaspi.impl.ClientAuthConfigImpl;
/**
* <p>Java class for clientAuthConfigType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="clientAuthConfigType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="messageLayer" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="appContext" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="authenticationContextID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="protected" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* <element name="clientAuthContext" type="{http://geronimo.apache.org/xml/ns/geronimo-jaspi}clientAuthContextType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
* @version $Rev: 939768 $ $Date: 2010-04-30 11:26:46 -0700 (Fri, 30 Apr 2010) $
*/
@XmlRootElement(name = "clientAuthConfig", namespace = "http://geronimo.apache.org/xml/ns/geronimo-jaspi")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "clientAuthConfigType", propOrder = {
"messageLayer",
"appContext",
"authenticationContextID",
"_protected",
"clientAuthContext"
})
public class ClientAuthConfigType
implements Serializable, KeyedObject
{
private final static long serialVersionUID = 12343L;
protected String messageLayer;
protected String appContext;
protected String authenticationContextID;
@XmlElement(name = "protected")
protected boolean _protected;
//TODO go back to a map
// @XmlJavaTypeAdapter(KeyedObjectMapAdapter.class)
protected List<ClientAuthContextType> clientAuthContext;
public ClientAuthConfigType() {
}
public ClientAuthConfigType(ClientAuthContextType clientAuthContextType, boolean _protected) {
this.messageLayer = clientAuthContextType.getMessageLayer();
this.appContext = clientAuthContextType.getAppContext();
this.authenticationContextID = clientAuthContextType.getAuthenticationContextID();
this.clientAuthContext = Collections.singletonList(clientAuthContextType);
this._protected = _protected;
}
/**
* Gets the value of the messageLayer property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMessageLayer() {
return messageLayer;
}
/**
* Sets the value of the messageLayer property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessageLayer(String value) {
this.messageLayer = value;
}
/**
* Gets the value of the appContext property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAppContext() {
return appContext;
}
/**
* Sets the value of the appContext property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAppContext(String value) {
this.appContext = value;
}
/**
* Gets the value of the authenticationContextID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAuthenticationContextID() {
return authenticationContextID;
}
/**
* Sets the value of the authenticationContextID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAuthenticationContextID(String value) {
this.authenticationContextID = value;
}
/**
* Gets the value of the protected property.
*
* @return whether the client auth config is protected
*/
public boolean isProtected() {
return _protected;
}
public void refresh() throws AuthException, SecurityException {
}
/**
* Sets the value of the protected property.
*
* @param value whether client auth config is protected.
*/
public void setProtected(boolean value) {
this._protected = value;
}
/**
* Gets the value of the clientAuthContext property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the clientAuthContext property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getClientAuthContext().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ClientAuthContextType }
*
*
* @return map of id to client auth context
*/
public List<ClientAuthContextType> getClientAuthContext() {
if (clientAuthContext == null) {
clientAuthContext = new ArrayList<ClientAuthContextType>();
}
return clientAuthContext;
}
//TODO move to ClientAuthContextImpl
public String getAuthContextID(MessageInfo messageInfo) throws IllegalArgumentException {
if (authenticationContextID != null) {
return authenticationContextID;
}
for (ClientAuthContextType clientAuthContextType: clientAuthContext) {
String authContextID = clientAuthContextType.getAuthenticationContextID(messageInfo);
if (authContextID != null) {
return authContextID;
}
}
return null;
}
public String getKey() {
return ConfigProviderType.getRegistrationKey(messageLayer, appContext);
}
}
| 5,654 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/ServerAuthConfigType.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.5-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2008.07.15 at 04:13:34 PM PDT
//
package org.apache.geronimo.components.jaspi.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.config.ServerAuthConfig;
import javax.security.auth.message.config.ServerAuthContext;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.geronimo.components.jaspi.impl.ServerAuthConfigImpl;
/**
* <p>Java class for serverAuthConfigType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="serverAuthConfigType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="messageLayer" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="appContext" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="authenticationContextID" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="protected" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* <element name="serverAuthContext" type="{http://geronimo.apache.org/xml/ns/geronimo-jaspi}serverAuthContextType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
* @version $Rev: 939768 $ $Date: 2010-04-30 11:26:46 -0700 (Fri, 30 Apr 2010) $
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "serverAuthConfigType", propOrder = {
"messageLayer",
"appContext",
"authenticationContextID",
"_protected",
"serverAuthContext"
})
public class ServerAuthConfigType
implements Serializable, KeyedObject
{
private final static long serialVersionUID = 12343L;
protected String messageLayer;
protected String appContext;
protected String authenticationContextID;
@XmlElement(name = "protected")
protected boolean _protected;
// @XmlJavaTypeAdapter(KeyedObjectMapAdapter.class)
protected List<ServerAuthContextType> serverAuthContext;
public ServerAuthConfigType() {
}
public ServerAuthConfigType(ServerAuthContextType serverAuthContextType, boolean _protected) {
this.messageLayer = serverAuthContextType.getMessageLayer();
this.appContext = serverAuthContextType.getAppContext();
this.authenticationContextID = serverAuthContextType.getAuthenticationContextID();
this.serverAuthContext = Collections.singletonList(serverAuthContextType);
this._protected = _protected;
}
/**
* Gets the value of the messageLayer property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMessageLayer() {
return messageLayer;
}
/**
* Sets the value of the messageLayer property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessageLayer(String value) {
this.messageLayer = value;
}
/**
* Gets the value of the appContext property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAppContext() {
return appContext;
}
public String getAuthContextID(MessageInfo messageInfo) throws IllegalArgumentException {
if (authenticationContextID != null) {
return authenticationContextID;
}
for (ServerAuthContextType serverAuthContextType: serverAuthContext) {
String authContextID = serverAuthContextType.getAuthenticationContextID(messageInfo);
if (authContextID != null) {
return authContextID;
}
}
return null;
}
/**
* Sets the value of the appContext property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAppContext(String value) {
this.appContext = value;
}
/**
* Gets the value of the authenticationContextID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAuthenticationContextID() {
return authenticationContextID;
}
/**
* Sets the value of the authenticationContextID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAuthenticationContextID(String value) {
this.authenticationContextID = value;
}
/**
* Gets the value of the protected property.
*
* @return whether the server auth config is protected
*/
public boolean isProtected() {
return _protected;
}
public void refresh() throws AuthException, SecurityException {
}
/**
* Sets the value of the protected property.
*
* @param value whether the server auth context should be protected
*/
public void setProtected(boolean value) {
this._protected = value;
}
/**
* Gets the value of the serverAuthContext property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the serverAuthContext property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getServerAuthContext().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ServerAuthContextType }
*
*
* @return map of id to Server auth config
*/
public List<ServerAuthContextType> getServerAuthContext() {
if (serverAuthContext == null) {
serverAuthContext = new ArrayList<ServerAuthContextType>();
}
return serverAuthContext;
}
public String getKey() {
return ConfigProviderType.getRegistrationKey(messageLayer, appContext);
}
}
| 5,655 |
0 | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi | Create_ds/geronimo-jaspi/geronimo-jaspi/src/main/java/org/apache/geronimo/components/jaspi/model/package-info.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.5-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2008.07.15 at 04:13:34 PM PDT
//
/**
* @version $Rev: 680565 $ $Date: 2008-07-28 16:33:51 -0700 (Mon, 28 Jul 2008) $
*/
@javax.xml.bind.annotation.XmlSchema(namespace = "http://geronimo.apache.org/xml/ns/geronimo-jaspi", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.apache.geronimo.components.jaspi.model;
| 5,656 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/TenantContextHolderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.Semaphore;
public class TenantContextHolderTest {
private static String TEST_IDENTIFIER = "test";
public TenantContextHolderTest() {
super();
}
@After
public void clearTenantContext() {
TenantContextHolder.clear();
}
@Test
public void shouldSetTenantIdentifier() {
TenantContextHolder.setIdentifier(TEST_IDENTIFIER);
Assert.assertTrue(TenantContextHolder.identifier().isPresent());
@SuppressWarnings("OptionalGetWithoutIsPresent") final String identifier = TenantContextHolder.identifier().get();
Assert.assertEquals(TEST_IDENTIFIER, identifier);
}
@Test(expected = IllegalStateException.class)
public void shouldThrowIfNotSet()
{
TenantContextHolder.clear();
TenantContextHolder.checkedGetIdentifier();
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotSetTenantIdentifierAlreadyAssigned() {
TenantContextHolder.setIdentifier(TEST_IDENTIFIER);
TenantContextHolder.setIdentifier(TEST_IDENTIFIER);
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotSetTenantIdentifierNull() {
//noinspection ConstantConditions
TenantContextHolder.setIdentifier(null);
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotSetTenantIdentifierEmpty() {
TenantContextHolder.setIdentifier("");
}
//Correct execution of commands in the command bus depend on the value of tenant being unchanged, even if the
// original jetty thread is returned to the thread pool before the command is executed.
@Test()
public void settingParentThreadValueShouldNotChangeChildThreadValueAfterFork() throws InterruptedException {
TenantContextHolder.setIdentifier(TEST_IDENTIFIER);
final ChildRunnable child = new ChildRunnable();
child.parentSignal.acquire();
final Thread childThread = new Thread(child);
childThread.start();
TenantContextHolder.clear();
TenantContextHolder.setIdentifier(TEST_IDENTIFIER + "somethingelse");
final boolean tenantChanged = TenantContextHolder.identifier().map(x -> !x.equals(TEST_IDENTIFIER)).orElse(false);
Assert.assertTrue(tenantChanged);
do {
child.parentSignal.release();
child.parentSignal.acquire();
} while (!child.tenantChecked);
Assert.assertTrue(child.tenantUnchanged);
}
private static class ChildRunnable implements Runnable {
private boolean tenantUnchanged = false;
private boolean tenantChecked = false;
private Semaphore parentSignal = new Semaphore(1);
@Override
public void run() {
try {
parentSignal.acquire();
tenantUnchanged = TenantContextHolder.identifier().map(x -> x.equals(TEST_IDENTIFIER)).orElse(false);
tenantChecked = true;
parentSignal.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| 5,657 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/AutoTenantContextTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang;
import org.junit.Assert;
import org.junit.Test;
import java.util.Optional;
/**
* @author Myrle Krantz
*/
public class AutoTenantContextTest {
@Test
public void stateIsUndisturbedOutsideOfTryBlock()
{
TenantContextHolder.setIdentifier("x");
//noinspection EmptyTryBlock
try (final AutoTenantContext ignored = new AutoTenantContext("m"))
{
Assert.assertEquals(TenantContextHolder.identifier(), Optional.of("m"));
}
Assert.assertEquals(TenantContextHolder.identifier(), Optional.of("x"));
TenantContextHolder.clear();
}
} | 5,658 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/ApplicationNameTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author Myrle Krantz
*/
@RunWith(Parameterized.class)
public class ApplicationNameTest {
private final TestCase testCase;
public ApplicationNameTest(final TestCase testCase) {
this.testCase = testCase;
}
@Parameterized.Parameters
public static Collection testCases() {
final Collection<TestCase> ret = new ArrayList<>();
ret.add(new TestCase("1isis-v1").exception("app name should begin with a letter"));
ret.add(new TestCase("isis-va1").exception("the version marker v should be followed by a number"));
ret.add(new TestCase("isis-1").exception("the version needs to be preceeded by 'v'"));
ret.add(new TestCase("isis-V1").exception("capital V for version part is not allowed"));
ret.add(new TestCase("i-v1").exception("one character is not allowed"));
ret.add(new TestCase("i/v-v1").exception("/ is not allowed"));
ret.add(new TestCase("i.v-v1").exception(". is not allowed"));
ret.add(new TestCase("isisHorus-v1").exception("camel case is not allowed"));
ret.add(new TestCase("isis").exception("app name must have a version"));
ret.add(new TestCase("/isis-v1")
.appNameWithVersion("isis", "1")
.toStringOutput("isis-v1")
);
ret.add(new TestCase("isis-v1_2.34")
.appNameWithVersion("isis", "1_2.34")
.toStringOutput("isis-v1_2.34")
);
ret.add(new TestCase("isis_horus-v1")
.appNameWithVersion("isis_horus", "1")
.toStringOutput("isis_horus-v1")
);
return ret;
}
@Test()
public void testParse() {
try {
final ApplicationName testSubject =
ApplicationName.parse(testCase.springApplicationName);
Assert.assertFalse("An exception was expected for the application name "
+ testCase.springApplicationName + " because " + testCase.exceptionReason + ".",
testCase.exceptionExpected);
Assert.assertEquals(testCase.expectedOutput, testSubject);
Assert.assertEquals(testCase.expectedOutput.getServiceName(), testSubject.getServiceName());
Assert.assertEquals(testCase.expectedOutput.getVersionString(), testSubject.getVersionString());
Assert.assertEquals(testCase.toStringOutput, testSubject.toString());
Assert.assertEquals(testCase.expectedOutput.hashCode(), testSubject.hashCode());
} catch (final IllegalArgumentException e) {
Assert.assertTrue("An exception was not expected for the application name "
+ testCase.springApplicationName, testCase.exceptionExpected);
}
}
private static class TestCase {
final String springApplicationName;
ApplicationName expectedOutput;
boolean exceptionExpected;
private String exceptionReason;
private String toStringOutput;
TestCase(final String springApplicationName) {
this.springApplicationName = springApplicationName;
this.exceptionExpected = false;
}
TestCase appNameWithVersion(final String name, final String version) {
expectedOutput = ApplicationName.appNameWithVersion(name, version);
return this;
}
TestCase exception(final String reason) {
this.exceptionReason = reason;
this.exceptionExpected = true;
return this;
}
TestCase toStringOutput(final String toStringOutput) {
this.toStringOutput = toStringOutput;
return this;
}
}
}
| 5,659 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/DateRangeTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang;
import org.junit.Assert;
import org.junit.Test;
import java.time.LocalDate;
/**
* @author Myrle Krantz
*/
public class DateRangeTest {
@Test
public void dateRangeFromIsoString() {
final String startString = "2017-07-13Z";
final String endString = "2017-07-16Z";
final LocalDate start = DateConverter.dateFromIsoString(startString);
final LocalDate end = DateConverter.dateFromIsoString(endString);
final String dateRangeString = startString + ".." + endString;
final DateRange dateRange = DateRange.fromIsoString(dateRangeString);
Assert.assertEquals(dateRangeString, dateRange.toString());
Assert.assertEquals(start.atStartOfDay(), dateRange.getStartDateTime());
Assert.assertEquals(end.plusDays(1).atStartOfDay(), dateRange.getEndDateTime());
Assert.assertEquals(4, dateRange.stream().count());
final DateRange dateRangeToday = DateRange.fromIsoString(null);
Assert.assertEquals(1, dateRangeToday.stream().count());
try {
final DateRange dateRangeHalf = DateRange.fromIsoString(startString);
Assert.fail("Invalid date range format should throw exception.");
}
catch (final ServiceException ignore) {
}
try {
final DateRange dateRangeHalf = DateRange.fromIsoString("notanisostringZ..anothernonisostringZ");
Assert.fail("Invalid date range format should throw exception.");
}
catch (final ServiceException ignore) {
}
}
}
| 5,660 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/DateConverterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang;
import org.junit.Assert;
import org.junit.Test;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
/**
* @author Myrle Krantz
*/
public class DateConverterTest {
private final static Instant momentInTime = Instant.ofEpochSecond(1481281507);
@Test
public void dateToIsoString() throws Exception {
final Date date = Date.from(momentInTime);
final String isoString = DateConverter.toIsoString(date);
Assert.assertEquals("2016-12-09T11:05:07Z", isoString);
}
@Test
public void dateFromIsoString() throws Exception {
final LocalDate date = DateConverter.dateFromIsoString("2017-07-13Z");
final String isoString = DateConverter.toIsoString(date);
Assert.assertEquals("2017-07-13Z", isoString);
}
@Test
public void localDateTimeToIsoString() throws Exception {
final LocalDateTime localDateTime = LocalDateTime.ofInstant(momentInTime, ZoneId.of("UTC"));
final String isoString = DateConverter.toIsoString(localDateTime);
Assert.assertEquals("2016-12-09T11:05:07Z", isoString);
final LocalDateTime roundTrip = DateConverter.fromIsoString(isoString);
Assert.assertEquals(localDateTime, roundTrip);
}
@Test
public void localDateTimeToEpochMillis() throws Exception {
final LocalDateTime localDateTime = LocalDateTime.ofInstant(momentInTime, ZoneId.of("UTC"));
final Long epochMillis = DateConverter.toEpochMillis(localDateTime);
Assert.assertEquals(Long.valueOf(1481281507000L), epochMillis);
final LocalDateTime roundTrip = DateConverter.fromEpochMillis(epochMillis);
Assert.assertEquals(localDateTime, roundTrip);
}
@Test
public void localDateToIsoString() throws Exception {
final LocalDateTime localDateTime = LocalDateTime.ofInstant(momentInTime, ZoneId.of("UTC"));
final LocalDate localDate = DateConverter.toLocalDate(localDateTime);
final String isoString = DateConverter.toIsoString(localDate);
Assert.assertEquals("2016-12-09Z", isoString);
}
@Test
public void localDateToEpochDay() throws Exception {
final LocalDateTime localDateTime = LocalDateTime.ofInstant(momentInTime, ZoneId.of("UTC"));
final LocalDate localDate = DateConverter.toLocalDate(localDateTime);
final Long epochDay = DateConverter.toEpochDay(localDate);
Assert.assertEquals(Long.valueOf(17144), epochDay);
}
} | 5,661 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/listening/TenantedEventListenerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.listening;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
/**
* @author Myrle Krantz
*/
public class TenantedEventListenerTest {
static class SomeState {
boolean mutableBit = false;
}
@Test
public void shouldWaitForEventOccurenceTrue() throws InterruptedException {
final TenantedEventListener testSubject = new TenantedEventListener();
final EventKey eventKey = new EventKey("shouldWaitForEventOccurenceTrue", "blah", "blah");
final EventExpectation eventExpectation = testSubject.expect(eventKey);
final SomeState someState = stateThatMutatesIn60MillisThenNotifiesOnEventKey(testSubject, eventKey);
Assert.assertTrue(eventExpectation.waitForOccurrence(600, TimeUnit.MILLISECONDS));
Assert.assertTrue(someState.mutableBit);
}
@Test
public void shouldWaitForEventOccurenceFalse() throws InterruptedException {
final TenantedEventListener testSubject = new TenantedEventListener();
final EventKey eventKey = new EventKey("shouldWaitForEventOccurenceFalse", "blah", "blah");
final EventExpectation eventExpectation = testSubject.expect(eventKey);
final SomeState someState = stateThatMutatesIn60MillisThenNotifiesOnEventKey(testSubject, eventKey);
Assert.assertFalse(eventExpectation.waitForOccurrence(6, TimeUnit.MILLISECONDS));
Assert.assertFalse(someState.mutableBit); //Some potential for flakiness here, because this is timing dependent.
}
@Test
public void shouldNotWaitForEventOccurence() throws InterruptedException {
final TenantedEventListener testSubject = new TenantedEventListener();
final EventKey eventKey = new EventKey("shouldNotWaitForEventOccurence", "blah", "blah");
final EventExpectation eventExpectation = testSubject.expect(eventKey);
final SomeState someState = stateThatMutatesIn60MillisThenNotifiesOnEventKey(testSubject, eventKey);
testSubject.withdrawExpectation(eventExpectation);
Assert.assertFalse(eventExpectation.waitForOccurrence(600, TimeUnit.MILLISECONDS));
Assert.assertFalse(someState.mutableBit); //Some potential for flakiness here, because this is timing dependent.
}
private SomeState stateThatMutatesIn60MillisThenNotifiesOnEventKey(
final TenantedEventListener testSubject,
final EventKey eventKey) {
final SomeState someState = new SomeState();
new Thread(() -> {
try {
TimeUnit.MILLISECONDS.sleep(60);
someState.mutableBit = true;
testSubject.notify(eventKey);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
return someState;
}
} | 5,662 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/config/TenantHeaderFilterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.config;
import org.apache.fineract.cn.lang.TenantContextHolder;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TenantHeaderFilterTest {
private static final String TEST_TENANT = "test";
public TenantHeaderFilterTest() {
super();
}
@Test
public void shouldFilterTenant() throws Exception {
final HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class);
Mockito.when(mockedRequest.getHeader(TenantHeaderFilter.TENANT_HEADER)).thenReturn(TEST_TENANT);
final HttpServletResponse mockedResponse = Mockito.mock(HttpServletResponse.class);
final FilterChain mockedFilterChain = (request, response) -> {
Assert.assertTrue(TenantContextHolder.identifier().isPresent());
//noinspection OptionalGetWithoutIsPresent
Assert.assertEquals(TEST_TENANT, TenantContextHolder.identifier().get());
};
final TenantHeaderFilter tenantHeaderFilter = new TenantHeaderFilter();
tenantHeaderFilter.doFilter(mockedRequest, mockedResponse, mockedFilterChain);
Assert.assertFalse(TenantContextHolder.identifier().isPresent());
Mockito.verifyZeroInteractions(mockedResponse);
}
@Test
public void shouldNotFilterTenantMissingHeader() throws Exception {
final HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class);
Mockito.when(mockedRequest.getHeader(TenantHeaderFilter.TENANT_HEADER)).thenReturn(null);
final HttpServletResponse mockedResponse = Mockito.mock(HttpServletResponse.class);
final FilterChain mockedFilterChain =
(request, response) -> Assert.assertFalse(TenantContextHolder.identifier().isPresent());
final TenantHeaderFilter tenantHeaderFilter = new TenantHeaderFilter();
tenantHeaderFilter.doFilter(mockedRequest, mockedResponse, mockedFilterChain);
Assert.assertFalse(TenantContextHolder.identifier().isPresent());
Mockito.verify(mockedResponse, Mockito.times(1)).sendError(Mockito.eq(400), Mockito.anyString());
}
}
| 5,663 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/config/ServiceExceptionFilterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.config;
import org.apache.fineract.cn.lang.ServiceException;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.web.util.NestedServletException;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServiceExceptionFilterTest {
public ServiceExceptionFilterTest() {
super();
}
@Test
public void shouldProceedNoServiceException() throws Exception {
final HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse mockedResponse = Mockito.mock(HttpServletResponse.class);
final FilterChain mockedFilterChain = Mockito.mock(FilterChain.class);
final ServiceExceptionFilter serviceExceptionFilter = new ServiceExceptionFilter();
serviceExceptionFilter.doFilter(mockedRequest, mockedResponse, mockedFilterChain);
Mockito.verifyZeroInteractions(mockedResponse);
Mockito.verify(mockedFilterChain, Mockito.times(1)).doFilter(mockedRequest, mockedResponse);
}
@Test
public void shouldFilterServiceException() throws Exception {
final String errorMessage = "Should fail.";
final HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse mockedResponse = Mockito.mock(HttpServletResponse.class);
final FilterChain mockedFilterChain = (request, response) -> {
throw new NestedServletException(errorMessage, ServiceException.conflict(errorMessage));
};
final ServiceExceptionFilter serviceExceptionFilter = new ServiceExceptionFilter();
serviceExceptionFilter.doFilter(mockedRequest, mockedResponse, mockedFilterChain);
Mockito.verify(mockedResponse, Mockito.times(1)).sendError(Mockito.eq(409), Mockito.eq(errorMessage));
}
}
| 5,664 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/security/RsaKeyPairFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.security;
import static junit.framework.TestCase.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class RsaKeyPairFactoryTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
}
@After
public void restoreStreams() {
System.setOut(originalOut);
}
@Test
public void shouldCreateRsaKeys() throws Exception {
final RsaKeyPairFactory.KeyPairHolder keyPairHolder = RsaKeyPairFactory.createKeyPair();
Assert.assertNotNull(keyPairHolder);
Assert.assertNotNull(keyPairHolder.getTimestamp());
Assert.assertFalse(keyPairHolder.getTimestamp().contains("."));
Assert.assertNotNull(keyPairHolder.publicKey());
Assert.assertNotNull(keyPairHolder.privateKey());
}
@Test
public void shouldPrintSpringStyle() {
RsaKeyPairFactory.main(new String[]{"SPRING"});
String systemOutput = outContent.toString();
assertTrue(systemOutput.contains("system.publicKey.exponent="));
assertTrue(systemOutput.contains("system.publicKey.modulus="));
assertTrue(systemOutput.contains("system.publicKey.timestamp="));
assertTrue(systemOutput.contains("system.privateKey.modulus="));
assertTrue(systemOutput.contains("system.privateKey.exponent="));
}
@Test
public void shouldPrintUnixStyle() {
RsaKeyPairFactory.main(new String[]{"UNIX"});
String systemOutput = outContent.toString();
assertTrue(systemOutput.contains("PUBLIC_KEY_EXPONENT="));
assertTrue(systemOutput.contains("PUBLIC_KEY_MODULUS="));
assertTrue(systemOutput.contains("PUBLIC_KEY_TIMESTAMP="));
assertTrue(systemOutput.contains("PRIVATE_KEY_MODULUS="));
assertTrue(systemOutput.contains("PRIVATE_KEY_EXPONENT="));
}
}
| 5,665 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/security/RsaPrivateKeyBuilderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.security;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigInteger;
import java.security.PrivateKey;
/**
* @author Myrle Krantz
*/
public class RsaPrivateKeyBuilderTest {
@Test
public void shouldReadPublicKeyCorrectly() {
final RsaKeyPairFactory.KeyPairHolder keyPair = RsaKeyPairFactory.createKeyPair();
final BigInteger exp = keyPair.getPrivateKeyExp();
final BigInteger mod = keyPair.getPrivateKeyMod();
final PrivateKey privateKey =
new RsaPrivateKeyBuilder().setPrivateKeyExp(exp).setPrivateKeyMod(mod).build();
Assert.assertEquals(privateKey, keyPair.privateKey());
}
@Test(expected = IllegalStateException.class)
public void shouldFailToReadBrokenPublicKey() {
final BigInteger exp = BigInteger.valueOf(-1);
final BigInteger mod = BigInteger.valueOf(-1);
new RsaPrivateKeyBuilder().setPrivateKeyExp(exp).setPrivateKeyMod(mod).build();
}
}
| 5,666 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/security/RsaPublicKeyBuilderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.security;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigInteger;
import java.security.PublicKey;
/**
* @author Myrle Krantz
*/
public class RsaPublicKeyBuilderTest {
@Test
public void shouldReadPublicKeyCorrectly() {
final RsaKeyPairFactory.KeyPairHolder keyPair = RsaKeyPairFactory.createKeyPair();
final BigInteger exp = keyPair.getPublicKeyExp();
final BigInteger mod = keyPair.getPublicKeyMod();
final PublicKey publicKey =
new RsaPublicKeyBuilder().setPublicKeyExp(exp).setPublicKeyMod(mod).build();
Assert.assertEquals(publicKey, keyPair.publicKey());
}
@Test(expected = IllegalStateException.class)
public void shouldFailToReadBrokenPublicKey() {
final BigInteger exp = BigInteger.valueOf(-1);
final BigInteger mod = BigInteger.valueOf(-1);
new RsaPublicKeyBuilder().setPublicKeyExp(exp).setPublicKeyMod(mod).build();
}
}
| 5,667 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/validation/TestHelper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.validation;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
/**
* @author Myrle Krantz
*/
class TestHelper {
static <T> boolean isValid(final T annotatedInstance)
{
final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
final Validator validator = factory.getValidator();
final Set<ConstraintViolation<T>> errors = validator.validate(annotatedInstance);
return errors.size() == 0;
}
}
| 5,668 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/validation/ValidIdentifierTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.validation;
import org.apache.fineract.cn.lang.validation.constraints.ValidIdentifier;
import org.junit.Assert;
import org.junit.Test;
import static org.apache.fineract.cn.lang.validation.TestHelper.isValid;
/**
* @author Myrle Krantz
*/
public class ValidIdentifierTest {
@Test
public void validIdentifierWithTilda()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass("xy~mn");
Assert.assertFalse(isValid(annotatedInstance));
}
@Test
public void validIdentifierWithUnderscore()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass("xy_mn");
Assert.assertTrue(isValid(annotatedInstance));
}
@Test
public void validIdentifierWithDot()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass("xy.mn");
Assert.assertTrue(isValid(annotatedInstance));
}
@Test
public void validIdentifierWithDash()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass("xy-mn");
Assert.assertTrue(isValid(annotatedInstance));
}
@Test
public void validIdentifier()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass("xxxx");
Assert.assertTrue(isValid(annotatedInstance));
}
@Test
public void nullIdentifier()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass(null);
Assert.assertFalse(isValid(annotatedInstance));
}
@Test
public void emptyStringIdentifier()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass("");
Assert.assertFalse(isValid(annotatedInstance));
}
@Test
public void tooShortStringIdentifier()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass("x");
Assert.assertFalse(isValid(annotatedInstance));
}
@Test
public void tooLongStringIdentifier()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass("012345");
Assert.assertFalse(isValid(annotatedInstance));
}
@Test
public void notEncodableStringIdentifier()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass("x/y/z");
Assert.assertFalse(isValid(annotatedInstance));
}
private static class AnnotatedClass {
@ValidIdentifier(maxLength = 5)
String applicationName;
AnnotatedClass(final String applicationName) {
this.applicationName = applicationName;
}
}
}
| 5,669 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/validation/ValidIdentifiersTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.validation;
import org.apache.fineract.cn.lang.validation.constraints.ValidIdentifiers;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.apache.fineract.cn.lang.validation.TestHelper.isValid;
/**
* @author Myrle Krantz
*/
public class ValidIdentifiersTest {
@Test
public void valid()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass(Collections.singletonList("xxxx"));
Assert.assertTrue(isValid(annotatedInstance));
}
@Test
public void toolong()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass(Collections.singletonList("xxxxxx"));
Assert.assertFalse(isValid(annotatedInstance));
}
@Test
public void nullList()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass(null);
Assert.assertFalse(isValid(annotatedInstance));
}
@Test
public void nullInList()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass(Collections.singletonList(null));
Assert.assertFalse(isValid(annotatedInstance));
}
@Test
public void badApple()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass(Arrays.asList("xxxx", null));
Assert.assertFalse(isValid(annotatedInstance));
}
private static class AnnotatedClass {
@ValidIdentifiers(maxLength = 5)
List<String> identifiers;
AnnotatedClass(final List<String> identifiers) {
this.identifiers= identifiers;
}
}
}
| 5,670 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/validation/ValidLocalDateTimeStringTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.validation;
import org.apache.fineract.cn.lang.DateConverter;
import org.apache.fineract.cn.lang.validation.constraints.ValidLocalDateTimeString;
import org.junit.Assert;
import org.junit.Test;
import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import static org.apache.fineract.cn.lang.validation.TestHelper.isValid;
/**
* @author Myrle Krantz
*/
public class ValidLocalDateTimeStringTest {
@Test
public void now()
{
final AnnotatedClassNullable annotatedInstance = new AnnotatedClassNullable(DateConverter.toIsoString(LocalDateTime.now()));
Assert.assertTrue(isValid(annotatedInstance));
}
@Test
public void invalidString()
{
final AnnotatedClassNullable annotatedInstance = new AnnotatedClassNullable("This is not a date time.");
Assert.assertFalse(isValid(annotatedInstance));
}
@Test
public void nullLocalDateTimeStringAllowed()
{
final AnnotatedClassNullable annotatedInstance = new AnnotatedClassNullable(null);
Assert.assertTrue(isValid(annotatedInstance));
}
@Test
public void nullLocalDateTimeStringNotAllowed()
{
final AnnotatedClassNotNull annotatedInstance = new AnnotatedClassNotNull(null);
Assert.assertFalse(isValid(annotatedInstance));
}
private static class AnnotatedClassNullable {
@Nullable
@ValidLocalDateTimeString()
String localDateTimeString;
AnnotatedClassNullable(final String localDateTimeString) {
this.localDateTimeString = localDateTimeString;
}
}
private static class AnnotatedClassNotNull {
@NotNull
@ValidLocalDateTimeString()
String localDateTimeString;
AnnotatedClassNotNull(final String localDateTimeString) {
this.localDateTimeString = localDateTimeString;
}
}
}
| 5,671 |
0 | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/test/java/org/apache/fineract/cn/lang/validation/ValidApplicationNameTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.validation;
import org.apache.fineract.cn.lang.validation.constraints.ValidApplicationName;
import org.junit.Assert;
import org.junit.Test;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
/**
* @author Myrle Krantz
*/
public class ValidApplicationNameTest {
@Test
public void validApplicationName()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass("blub-v1");
Assert.assertTrue(isValid(annotatedInstance));
}
@Test
public void invalidAppplicationName()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass("blubv1");
Assert.assertFalse(isValid(annotatedInstance));
}
@Test
public void tooLongAppplicationName()
{
final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 65 -3; i++) {
stringBuilder.append("b");
}
stringBuilder.append("-v1");
final AnnotatedClass annotatedInstance = new AnnotatedClass(stringBuilder.toString());
Assert.assertFalse(isValid(annotatedInstance));
}
@Test
public void nullAppplicationName()
{
final AnnotatedClass annotatedInstance = new AnnotatedClass(null);
Assert.assertFalse(isValid(annotatedInstance));
}
private boolean isValid(final AnnotatedClass annotatedInstance)
{
final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
final Validator validator = factory.getValidator();
final Set<ConstraintViolation<AnnotatedClass>> errors = validator.validate(annotatedInstance);
return errors.size() == 0;
}
private static class AnnotatedClass {
@ValidApplicationName
String applicationName;
AnnotatedClass(final String applicationName) {
this.applicationName = applicationName;
}
}
}
| 5,672 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/ServiceException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang;
import java.text.MessageFormat;
@SuppressWarnings({"WeakerAccess", "unused"})
public final class ServiceException extends RuntimeException {
private final ServiceError serviceError;
public ServiceException(final ServiceError serviceError) {
super(serviceError.getMessage());
this.serviceError = serviceError;
}
public static ServiceException badRequest(final String message, final Object... args) {
return new ServiceException(ServiceError
.create(400)
.message(MessageFormat.format(message, args))
.build());
}
public static ServiceException notFound(final String message, final Object... args) {
return new ServiceException(ServiceError
.create(404)
.message(MessageFormat.format(message, args))
.build());
}
public static ServiceException conflict(final String message, final Object... args) {
return new ServiceException(ServiceError
.create(409)
.message(MessageFormat.format(message, args))
.build());
}
public static ServiceException internalError(final String message, final Object... args) {
return new ServiceException(ServiceError
.create(500)
.message(MessageFormat.format(message, args))
.build());
}
public ServiceError serviceError() {
return this.serviceError;
}
@Override
public String toString() {
return "ServiceException{" +
"serviceError=" + serviceError +
'}';
}
}
| 5,673 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/DateRange.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang;
import org.springframework.util.Assert;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.time.Clock;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.stream.Stream;
/**
* A range of dates specified by a start and an end. Inclusive of both.
*
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class DateRange {
private final @Nonnull LocalDate start;
private final @Nonnull LocalDate end;
public DateRange(final @Nonnull LocalDate start, final @Nonnull LocalDate end) {
this.start = start;
this.end = end;
}
public Stream<LocalDate> stream() {
return Stream.iterate(start, (current) -> current.plusDays(1))
.limit(ChronoUnit.DAYS.between(start, end) + 1);
}
public LocalDateTime getStartDateTime() {
return start.atStartOfDay();
}
public LocalDateTime getEndDateTime() {
return end.plusDays(1).atStartOfDay();
}
@Override
public String toString() {
return DateConverter.toIsoString(start) + ".." + DateConverter.toIsoString(end);
}
@Nonnull
public static DateRange fromIsoString(@Nullable final String isoDateRangeString) {
if (isoDateRangeString == null) {
final LocalDate today = LocalDate.now(Clock.systemUTC());
return new DateRange(today, today);
} else {
final String[] dates = isoDateRangeString.split("\\.\\.");
if (dates.length != 2)
throw ServiceException.badRequest("Date range should consist of exactly two dates.",
isoDateRangeString);
try {
return new DateRange(DateConverter.dateFromIsoString(dates[0]), DateConverter.dateFromIsoString(dates[1]));
}
catch(final DateTimeParseException e){
throw ServiceException.badRequest("Date {0} must use ISO format",
isoDateRangeString);
}
}
}
}
| 5,674 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/AutoTenantContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang;
import java.util.Optional;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"OptionalUsedAsFieldOrParameterType", "WeakerAccess", "unused"})
public class AutoTenantContext implements AutoCloseable {
private final Optional<String> previousIdentifier;
public AutoTenantContext(final String tenantName)
{
previousIdentifier = TenantContextHolder.identifier();
TenantContextHolder.clear();
TenantContextHolder.setIdentifier(tenantName);
}
public AutoTenantContext()
{
previousIdentifier = TenantContextHolder.identifier();
TenantContextHolder.clear();
}
@Override public void close() {
TenantContextHolder.clear();
previousIdentifier.ifPresent(TenantContextHolder::setIdentifier);
}
}
| 5,675 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/TenantContextHolder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang;
import org.springframework.util.Assert;
import javax.annotation.Nonnull;
import java.util.Optional;
public final class TenantContextHolder {
private static final InheritableThreadLocal<String> THREAD_LOCAL = new InheritableThreadLocal<>();
private TenantContextHolder() {
super();
}
@Nonnull
public static Optional<String> identifier() {
return Optional.ofNullable(TenantContextHolder.THREAD_LOCAL.get());
}
@SuppressWarnings("WeakerAccess")
public static String checkedGetIdentifier() {
return identifier().orElseThrow(() -> new IllegalStateException("Tenant context not set."));
}
public static void setIdentifier(@Nonnull final String identifier) {
Assert.hasLength(identifier, "A tenant identifier must have at least one character.");
Assert.isNull(TenantContextHolder.THREAD_LOCAL.get(), "Tenant identifier already set.");
TenantContextHolder.THREAD_LOCAL.set(identifier);
}
public static void clear() {
TenantContextHolder.THREAD_LOCAL.remove();
}
}
| 5,676 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/DateConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang;
import org.springframework.util.Assert;
import javax.annotation.Nonnull;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public interface DateConverter {
@Nonnull
static Long toEpochMillis(@Nonnull final LocalDateTime localDateTime) {
return localDateTime.toInstant(ZoneOffset.UTC).toEpochMilli();
}
@Nonnull
static Long toEpochDay(@Nonnull final LocalDate localDate) {
return localDate.toEpochDay();
}
@Nonnull
static LocalDateTime fromEpochMillis(@Nonnull final Long epochMillis) {
return LocalDateTime.from(Instant.ofEpochMilli(epochMillis).atZone(ZoneOffset.UTC));
}
@Nonnull
static String toIsoString(@Nonnull final Date date) {
return toIsoString(LocalDateTime.ofInstant(date.toInstant(), ZoneId.of("UTC")));
}
@Nonnull
static String toIsoString(@Nonnull final LocalDateTime localDateTime) {
return localDateTime.format(DateTimeFormatter.ISO_DATE_TIME) + "Z";
}
@Nonnull
static LocalDateTime fromIsoString(@Nonnull final String isoDateTimeString) {
return LocalDateTime.from(Instant.parse(isoDateTimeString).atZone(ZoneOffset.UTC));
}
@Nonnull
static LocalDate dateFromIsoString(@Nonnull final String isoDateString) {
final int zIndex = isoDateString.indexOf("Z");
final String shortenedString = isoDateString.substring(0, zIndex);
return LocalDate.from(DateTimeFormatter.ISO_LOCAL_DATE.parse(shortenedString));
}
@Nonnull
static String toIsoString(@Nonnull final LocalDate localDate) {
return localDate.format(DateTimeFormatter.ISO_DATE) + "Z";
}
@Nonnull
static LocalDate toLocalDate(@Nonnull final LocalDateTime localDateTime) {
return localDateTime.toLocalDate();
}
}
| 5,677 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/ApplicationName.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class ApplicationName {
final private String serviceName;
final private String versionString;
private ApplicationName(final String serviceName, final String versionString) {
this.serviceName = serviceName;
this.versionString = versionString;
}
public static ApplicationName fromSpringApplicationName(final String springApplicationName) {
return parse(springApplicationName);
}
public static ApplicationName appNameWithVersion(final String serviceName, final String versionString) {
return new ApplicationName(serviceName, versionString);
}
static ApplicationName parse(final String springApplicationNameString) {
if (springApplicationNameString.length() > 64) {
throw new IllegalArgumentException("Spring application name strings for Apache Fineract CN applications should be 64 characters or less.");
}
final Pattern applicationNamePattern = Pattern.compile(
"^(/??(?<name>\\p{Lower}[\\p{Lower}_]+)(?:-v(?<version>\\d[\\d\\._]*))?)$");
final Matcher applicationNameMatcher = applicationNamePattern.matcher(springApplicationNameString);
if (!applicationNameMatcher.matches()) {
throw new IllegalArgumentException(
"This is not a spring application name string for an Apache Fineract CN application: "
+ springApplicationNameString);
}
String versionString = applicationNameMatcher.group("version");
if (versionString == null) {
throw new IllegalArgumentException("Application name: '" + springApplicationNameString + "' requires a version. For example 'amit/v1'.");
}
final String serviceName = applicationNameMatcher.group("name");
return new ApplicationName(serviceName, versionString);
}
public String getServiceName() {
return serviceName;
}
public String getVersionString() {
return versionString;
}
@Override
public String toString() {
return serviceName + "-v" + versionString;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ApplicationName))
return false;
ApplicationName that = (ApplicationName) o;
return Objects.equals(serviceName, that.serviceName) && Objects
.equals(versionString, that.versionString);
}
@Override
public int hashCode() {
return Objects.hash(serviceName, versionString);
}
}
| 5,678 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/ServiceError.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang;
@SuppressWarnings("WeakerAccess")
public final class ServiceError {
private final int code;
private final String message;
private ServiceError(final int code, final String message) {
super();
this.code = code;
this.message = message;
}
public static Builder create(final int code) {
return new Builder(code);
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
public static final class Builder {
private final int code;
private String message;
public Builder(final int code) {
super();
this.code = code;
}
public Builder message(final String message) {
this.message = message;
return this;
}
public ServiceError build() {
return new ServiceError(this.code, this.message);
}
}
@Override
public String toString() {
return "ServiceError{" +
"code=" + code +
", message='" + message + '\'' +
'}';
}
}
| 5,679 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/DateOfBirth.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang;
import java.time.LocalDate;
@SuppressWarnings({"WeakerAccess", "unused"})
public final class DateOfBirth {
private Integer year;
private Integer month;
private Integer day;
public DateOfBirth() {
super();
}
public static DateOfBirth fromLocalDate(final LocalDate localDate) {
final DateOfBirth dateOfBirth = new DateOfBirth();
dateOfBirth.setYear(localDate.getYear());
dateOfBirth.setMonth(localDate.getMonthValue());
dateOfBirth.setDay(localDate.getDayOfMonth());
return dateOfBirth;
}
public Integer getYear() {
return this.year;
}
public void setYear(final Integer year) {
this.year = year;
}
public Integer getMonth() {
return this.month;
}
public void setMonth(final Integer month) {
this.month = month;
}
public Integer getDay() {
return this.day;
}
public void setDay(final Integer day) {
this.day = day;
}
public LocalDate toLocalDate() {
return LocalDate.of(
this.year,
this.month != null ? this.month : 1,
this.day != null ? this.day : 1
);
}
}
| 5,680 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/listening/EventKey.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.listening;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class EventKey {
private String tenantIdentifier;
private String eventName;
private Object event;
public EventKey(
final String tenantIdentifier,
final String eventName,
final Object event) {
this.tenantIdentifier = tenantIdentifier;
this.eventName = eventName;
this.event = event;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EventKey eventKey = (EventKey) o;
return Objects.equals(tenantIdentifier, eventKey.tenantIdentifier) &&
Objects.equals(eventName, eventKey.eventName) &&
Objects.equals(event, eventKey.event);
}
@Override
public int hashCode() {
return Objects.hash(tenantIdentifier, eventName, event);
}
@Override
public String toString() {
return "EventKey{" +
"tenantIdentifier='" + tenantIdentifier + '\'' +
", eventName='" + eventName + '\'' +
", event=" + event +
'}';
}
}
| 5,681 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/listening/EventExpectation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.listening;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author Myrle Krantz
*/
public class EventExpectation {
private final EventKey key;
private boolean eventFound = false;
private boolean eventWithdrawn = false;
private final ReentrantLock lock = new ReentrantLock();
private final Condition found = lock.newCondition();
EventExpectation(final EventKey key) {
this.key = key;
}
EventKey getKey() {
return key;
}
void setEventFound() {
lock.lock();
try {
this.eventFound = true;
found.signal();
}
finally {
lock.unlock();
}
}
void setEventWithdrawn() {
lock.lock();
try {
this.eventWithdrawn = true;
found.signal();
}
finally {
lock.unlock();
}
}
@SuppressWarnings("WeakerAccess")
public boolean waitForOccurrence(long timeout, TimeUnit timeUnit) throws InterruptedException {
lock.lock();
try {
if (eventFound)
return true;
if (eventWithdrawn)
return false;
found.await(timeout, timeUnit);
return (eventFound);
}
finally {
lock.unlock();
}
}
@Override
public String toString() {
return key.toString();
}
}
| 5,682 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/listening/TenantedEventListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.listening;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class TenantedEventListener {
private final Map<EventKey, EventExpectation> eventExpectations = new ConcurrentHashMap<>();
public EventExpectation expect(final EventKey eventKey) {
final EventExpectation value = new EventExpectation(eventKey);
eventExpectations.put(eventKey, value);
return value;
}
public void notify(final EventKey eventKey) {
final EventExpectation eventExpectation = eventExpectations.remove(eventKey);
if (eventExpectation != null) {
eventExpectation.setEventFound();
}
}
public void withdrawExpectation(final EventExpectation eventExpectation) {
final EventExpectation expectation = eventExpectations.remove(eventExpectation.getKey());
if (expectation != null) {
eventExpectation.setEventWithdrawn();
}
}
} | 5,683 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/config/EnableServiceException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.config;
import org.springframework.context.annotation.Import;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@SuppressWarnings("unused")
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({ServiceExceptionJavaConfiguration.class})
public @interface EnableServiceException {
}
| 5,684 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/config/ServiceExceptionFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.config;
import org.apache.fineract.cn.lang.ServiceError;
import org.apache.fineract.cn.lang.ServiceException;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.NestedServletException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
final class ServiceExceptionFilter extends OncePerRequestFilter {
ServiceExceptionFilter() {
super();
}
@Override
protected void doFilterInternal(final HttpServletRequest request,
final HttpServletResponse response,
final FilterChain filterChain)
throws ServletException, IOException {
try {
filterChain.doFilter(request, response);
} catch (final NestedServletException ex) {
if (ServiceException.class.isAssignableFrom(ex.getCause().getClass())) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") final ServiceException serviceException = ServiceException.class.cast(ex.getCause());
final ServiceError serviceError = serviceException.serviceError();
logger.info("Responding with a service error " + serviceError);
response.sendError(serviceError.getCode(), serviceError.getMessage());
} else {
logger.info("Unexpected exception caught " + ex);
throw ex;
}
}
}
}
| 5,685 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/config/TenantContextJavaConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.config;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TenantContextJavaConfiguration {
public TenantContextJavaConfiguration() {
super();
}
@Bean
public FilterRegistrationBean tenantFilterRegistration() {
final TenantHeaderFilter tenantHeaderFilter = new TenantHeaderFilter();
final FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(tenantHeaderFilter);
registration.addUrlPatterns("/*");
registration.setName("tenantHeaderFilter");
registration.setOrder(Integer.MIN_VALUE); //Before all other filters. Especially the security filter.
return registration;
}
}
| 5,686 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/config/ServiceExceptionJavaConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.config;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServiceExceptionJavaConfiguration {
public ServiceExceptionJavaConfiguration() {
super();
}
@Bean
public FilterRegistrationBean serviceExceptionFilterRegistration() {
final ServiceExceptionFilter serviceExceptionFilter = new ServiceExceptionFilter();
final FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(serviceExceptionFilter);
registration.addUrlPatterns("/*");
registration.setName("serviceExceptionFilter");
return registration;
}
}
| 5,687 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/config/EnableApplicationName.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.config;
import org.springframework.context.annotation.Import;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@SuppressWarnings("unused")
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({ApplicationNameConfiguration.class})
public @interface EnableApplicationName {
}
| 5,688 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/config/TenantHeaderFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.config;
import org.apache.fineract.cn.lang.TenantContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@SuppressWarnings("WeakerAccess")
public final class TenantHeaderFilter extends OncePerRequestFilter {
public static final String TENANT_HEADER = "X-Tenant-Identifier";
public TenantHeaderFilter() {
super();
}
@Override
protected void doFilterInternal(final HttpServletRequest request,
final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
final String tenantHeaderValue = request.getHeader(TenantHeaderFilter.TENANT_HEADER);
if (tenantHeaderValue == null || tenantHeaderValue.isEmpty()) {
response.sendError(400, "Header [" + TENANT_HEADER + "] must be given!");
} else {
TenantContextHolder.clear();
TenantContextHolder.setIdentifier(tenantHeaderValue);
}
try {
filterChain.doFilter(request, response);
} finally {
TenantContextHolder.clear();
}
}
}
| 5,689 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/config/ApplicationNameConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.config;
import org.apache.fineract.cn.lang.ApplicationName;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
@Configuration
public class ApplicationNameConfiguration {
@Bean
public ApplicationName applicationName(
@Value("${spring.application.name}") final String springApplicationName) {
return ApplicationName.fromSpringApplicationName(springApplicationName);
}
}
| 5,690 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/config/EnableTenantContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.config;
import org.springframework.context.annotation.Import;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@SuppressWarnings("unused")
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({TenantContextJavaConfiguration.class})
public @interface EnableTenantContext {
}
| 5,691 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/security/RsaPublicKeyBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.security;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class RsaPublicKeyBuilder {
private BigInteger publicKeyMod;
private BigInteger publicKeyExp;
public RsaPublicKeyBuilder setPublicKeyMod(final BigInteger publicKeyMod) {
this.publicKeyMod = publicKeyMod;
return this;
}
public RsaPublicKeyBuilder setPublicKeyExp(final BigInteger publicKeyExp) {
this.publicKeyExp = publicKeyExp;
return this;
}
public PublicKey build() {
try {
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(publicKeyMod, publicKeyExp);
return keyFactory.generatePublic(rsaPublicKeySpec);
} catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new IllegalStateException("Could not read public RSA key pair!", e);
}
}
}
| 5,692 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/security/RsaPrivateKeyBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.security;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"WeakerAccess"})
public class RsaPrivateKeyBuilder {
private BigInteger privateKeyMod;
private BigInteger privateKeyExp;
public RsaPrivateKeyBuilder setPrivateKeyMod(final BigInteger privateKeyMod) {
this.privateKeyMod = privateKeyMod;
return this;
}
public RsaPrivateKeyBuilder setPrivateKeyExp(final BigInteger privateKeyExp) {
this.privateKeyExp = privateKeyExp;
return this;
}
public PrivateKey build() {
try {
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(privateKeyMod, privateKeyExp);
return keyFactory.generatePrivate(rsaPrivateKeySpec);
} catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new IllegalStateException("Could not read private RSA key pair!", e);
}
}
}
| 5,693 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/security/RsaKeyPairFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.security;
import org.apache.fineract.cn.lang.DateConverter;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.time.Clock;
import java.time.LocalDateTime;
@SuppressWarnings({"WeakerAccess", "unused"})
public final class RsaKeyPairFactory {
private RsaKeyPairFactory() {
}
public static void main(String[] args) {
KeyPairHolder keyPair = RsaKeyPairFactory.createKeyPair();
String style = (args != null && args.length > 0) ?args[0] :"";
if ("SPRING".equalsIgnoreCase(style)) {
System.out.println("system.publicKey.exponent=" + keyPair.getPublicKeyExp());
System.out.println("system.publicKey.modulus=" + keyPair.getPublicKeyMod());
System.out.println("system.publicKey.timestamp=" + keyPair.getTimestamp());
System.out.println("system.privateKey.modulus=" + keyPair.getPrivateKeyMod());
System.out.println("system.privateKey.exponent=" + keyPair.getPrivateKeyExp());
}
else if ("UNIX".equalsIgnoreCase(style)) {
System.out.println("PUBLIC_KEY_EXPONENT=" + keyPair.getPublicKeyExp());
System.out.println("PUBLIC_KEY_MODULUS=" + keyPair.getPublicKeyMod());
System.out.println("PUBLIC_KEY_TIMESTAMP=" + keyPair.getTimestamp());
System.out.println("PRIVATE_KEY_MODULUS=" + keyPair.getPrivateKeyMod());
System.out.println("PRIVATE_KEY_EXPONENT=" + keyPair.getPrivateKeyExp());
}
}
public static KeyPairHolder createKeyPair() {
try {
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
final KeyPair keyPair = keyPairGenerator.genKeyPair();
final RSAPublicKeySpec rsaPublicKeySpec =
keyFactory.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class);
final RSAPrivateKeySpec rsaPrivateKeySpec =
keyFactory.getKeySpec(keyPair.getPrivate(), RSAPrivateKeySpec.class);
final String keyTimestamp = createKeyTimestampNow();
final RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(rsaPublicKeySpec);
final RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(rsaPrivateKeySpec);
return new KeyPairHolder(keyTimestamp, publicKey, privateKey);
} catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new IllegalStateException("RSA problem.");
}
}
private static String createKeyTimestampNow() {
final String timestamp = DateConverter.toIsoString(LocalDateTime.now(Clock.systemUTC()));
final int index = timestamp.indexOf(".");
final String timestampWithoutNanos;
if (index > 0) {
timestampWithoutNanos = timestamp.substring(0, index);
}
else {
timestampWithoutNanos = timestamp;
}
return timestampWithoutNanos.replace(':', '_');
}
public static class KeyPairHolder {
private final String timestamp;
private final RSAPublicKey publicKey;
private final RSAPrivateKey privateKey;
public KeyPairHolder(final String timestamp, final RSAPublicKey publicKey, final RSAPrivateKey privateKey) {
super();
this.timestamp = timestamp;
this.publicKey = publicKey;
this.privateKey = privateKey;
}
public RSAPublicKey publicKey() {
return publicKey;
}
public RSAPrivateKey privateKey() {
return privateKey;
}
public String getTimestamp() {
return timestamp;
}
public BigInteger getPublicKeyMod() {
return publicKey.getModulus();
}
public BigInteger getPublicKeyExp() {
return publicKey.getPublicExponent();
}
public BigInteger getPrivateKeyMod() {
return privateKey.getModulus();
}
public BigInteger getPrivateKeyExp() {
return privateKey.getPrivateExponent();
}
}
}
| 5,694 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/validation/CheckIdentifiers.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.validation;
import org.apache.fineract.cn.lang.validation.constraints.ValidIdentifiers;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;
/**
* @author Myrle Krantz
*/
public class CheckIdentifiers implements ConstraintValidator<ValidIdentifiers, List<String>> {
private int maximumLength = 32;
private boolean optional;
@Override
public void initialize(final ValidIdentifiers constraintAnnotation) {
maximumLength = constraintAnnotation.maxLength();
optional = constraintAnnotation.optional();
}
@Override
public boolean isValid(final List<String> value, final ConstraintValidatorContext context) {
if (optional && value == null)
return true;
return value != null && value.stream().allMatch(x -> x != null && CheckIdentifier.validate(x, maximumLength));
}
}
| 5,695 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/validation/CheckApplicationName.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.validation;
import org.apache.fineract.cn.lang.ApplicationName;
import org.apache.fineract.cn.lang.validation.constraints.ValidApplicationName;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* @author Myrle Krantz
*/
public class CheckApplicationName implements ConstraintValidator<ValidApplicationName, String> {
public void initialize(final ValidApplicationName constraint) {
}
public boolean isValid(final String obj, final ConstraintValidatorContext context) {
if (obj == null)
return false;
try {
ApplicationName.fromSpringApplicationName(obj);
return true;
}
catch (final IllegalArgumentException ignored)
{
return false;
}
}
}
| 5,696 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/validation/CheckIdentifier.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.validation;
import org.apache.fineract.cn.lang.validation.constraints.ValidIdentifier;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* @author Myrle Krantz
*/
public class CheckIdentifier implements ConstraintValidator<ValidIdentifier, String> {
private int maximumLength = 32;
private boolean optional = false;
@Override
public void initialize(final ValidIdentifier constraint) {
maximumLength = constraint.maxLength();
optional = constraint.optional();
}
@Override
public boolean isValid(final String obj, final ConstraintValidatorContext context) {
if (obj == null)
return optional;
return validate(obj, maximumLength);
}
static boolean validate(final String obj, final int maximumLength) {
if (obj.length() < 2)
return false;
if (obj.length() > maximumLength)
return false;
try {
return encode(obj).equals(obj);
}
catch (UnsupportedEncodingException e) {
return false; //If we can't encode with UTF-8, then there are no valid names.
}
}
static private String encode(String identifier) throws UnsupportedEncodingException {
return URLEncoder.encode(identifier, "UTF-8");
}
}
| 5,697 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/validation/CheckLocalDateTimeString.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.validation;
import org.apache.fineract.cn.lang.DateConverter;
import org.apache.fineract.cn.lang.validation.constraints.ValidLocalDateTimeString;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.DateTimeException;
/**
* @author Myrle Krantz
*/
public class CheckLocalDateTimeString implements ConstraintValidator<ValidLocalDateTimeString, String> {
public void initialize(ValidLocalDateTimeString constraint) {
}
public boolean isValid(final String obj, ConstraintValidatorContext context) {
if (obj == null)
return true;
try {
DateConverter.fromIsoString(obj);
return true;
}
catch (final DateTimeException e) {
return false;
}
}
}
| 5,698 |
0 | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/validation | Create_ds/fineract-cn-lang/src/main/java/org/apache/fineract/cn/lang/validation/constraints/ValidIdentifiers.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.lang.validation.constraints;
import org.apache.fineract.cn.lang.validation.CheckIdentifiers;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Checks that a list of identifiers is valid, in the same way that ValidIdentifier checks if a single identifier is
* valid.
*
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@Target({ FIELD, METHOD, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = CheckIdentifiers.class)
public @interface ValidIdentifiers {
String message() default "One or more invalid fineract identifiers.";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
int maxLength() default 32;
boolean optional() default false;
} | 5,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.