|
CPD Results
The following document contains the results of PMD's CPD 4.2.5.
Duplications
File |
Project |
Line |
co/codewizards/cloudstore/ls/rest/server/auth/AuthFilter.java |
co.codewizards.cloudstore.ls.rest.server |
41 |
co/codewizards/cloudstore/rest/server/service/AbstractServiceWithRepoToRepoAuth.java |
co.codewizards.cloudstore.rest.server |
68 |
if (auth == null) {
final String authorizationHeader = request.getHeader("Authorization");
if (authorizationHeader == null || authorizationHeader.isEmpty()) {
logger.debug("getAuth: There is no 'Authorization' header. Replying with a Status.UNAUTHORIZED response asking for 'Basic' authentication.");
throw newUnauthorizedException();
}
logger.debug("getAuth: 'Authorization' header: {}", authorizationHeader);
if (!authorizationHeader.startsWith("Basic"))
throw new WebApplicationException(Response.status(Status.FORBIDDEN)
.type(MediaType.APPLICATION_XML)
.entity(new Error("Only 'Basic' authentication is supported!")).build());
final String basicAuthEncoded = authorizationHeader.substring("Basic".length()).trim();
final byte[] basicAuthDecodedBA = getBasicAuthEncodedBA(basicAuthEncoded);
final StringBuilder userNameSB = new StringBuilder();
char[] password = null;
final ByteArrayInputStream in = new ByteArrayInputStream(basicAuthDecodedBA);
char[] ca = null;
CharArrayWriter caw = new CharArrayWriter(basicAuthDecodedBA.length + 1);
CharArrayReader car = null;
try {
final Reader r = new InputStreamReader(in, IOUtil.CHARSET_NAME_UTF_8);
int charsReadTotal = 0;
int charsRead;
do {
final char[] c = new char[10];
charsRead = r.read(c);
caw.write(c);
if (charsRead > 0)
charsReadTotal += charsRead;
} while (charsRead >= 0);
charsRead = 0;
car = new CharArrayReader(ca = caw.toCharArray());
int charsReadTotalCheck = 0;
while (charsRead >= 0 && charsRead < charsReadTotal) {
final char[] cbuf = new char[1];
charsRead = car.read(cbuf);
if (charsRead > 0)
charsReadTotalCheck += charsRead;
if (cbuf[0] == ':')
break;
userNameSB.append(cbuf[0]);
}
if (charsRead >= 0 && charsRead < charsReadTotal) {
password = new char[charsReadTotal - charsReadTotalCheck];
final int passwordSize = car.read(password);
if (passwordSize + charsReadTotalCheck != charsReadTotal)
throw new IllegalStateException("passwordSize and charsRead must match charsReadTotal!"
+ " passwordSize=" + passwordSize
+ ", charsRead=" + charsRead
+ ", charsReadTotal=" + charsReadTotal);//TODO for testing
}
} catch (final Exception e) {
throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_XML).entity(new Error(e)).build());
} finally {
// For extra safety: Overwrite all sensitive memory with 0.
// Unfortunately, we cannot overwrite auth.password. But at least we minimize things as much as possible.
Arrays.fill(basicAuthDecodedBA, (byte)0);
if (ca != null)
Arrays.fill(ca, (char)0);
if (caw != null) {
final char[] zeroArray = new char[caw.size()];
caw.reset();
try {
caw.write(zeroArray);
caw = null;
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
}
final Auth auth = new Auth(); |
File |
Project |
Line |
co/codewizards/cloudstore/ls/client/LocalServerClient.java |
co.codewizards.cloudstore.ls.client |
299 |
co/codewizards/cloudstore/ls/rest/server/InverseInvoker.java |
co.codewizards.cloudstore.ls.rest.server |
247 |
final ClassLoader classLoader = this.getClass().getClassLoader();
return (RemoteObjectProxy) Proxy.newProxyInstance(classLoader, interfaces,
new RemoteObjectProxyInvocationHandler(this, objectRef));
}
private Class<?>[] getInterfaces(final ObjectRef objectRef) {
ClassInfo classInfo = classInfoMap.getClassInfo(objectRef.getClassId());
if (classInfo == null) {
classInfo = objectRef.getClassInfo();
if (classInfo == null)
throw new IllegalStateException("There is no ClassInfo in the ClassInfoMap and neither in the ObjectRef! " + objectRef);
classInfoMap.putClassInfo(classInfo);
objectRef.setClassInfo(null);
}
final ClassManager classManager = objectManager.getClassManager();
final Set<String> interfaceNames = classInfo.getInterfaceNames();
final List<Class<?>> interfaces = new ArrayList<>(interfaceNames.size() + 1);
for (final String interfaceName : interfaceNames) {
Class<?> iface = null;
try {
iface = classManager.getClassOrFail(interfaceName);
} catch (RuntimeException x) {
if (ExceptionUtil.getCause(x, ClassNotFoundException.class) == null)
throw x;
}
if (iface != null)
interfaces.add(iface);
}
interfaces.add(RemoteObjectProxy.class);
return interfaces.toArray(new Class<?>[interfaces.size()]);
} |
File |
Project |
Line |
co/codewizards/cloudstore/ls/rest/client/request/AbstractRequest.java |
co.codewizards.cloudstore.ls.rest.client |
151 |
co/codewizards/cloudstore/rest/client/request/AbstractRequest.java |
co.codewizards.cloudstore.rest.client |
150 |
return getCloudStoreRestClientOrFail().getClientOrFail();
}
/**
* Encodes the given {@code path} (using {@link #urlEncode(String)}) and removes leading & trailing slashes.
* <p>
* Slashes are not encoded, but retained as they are; only the path segments (the strings between the slashes) are
* encoded.
* <p>
* Duplicate slashes are removed.
* <p>
* The result of this method can be used in both URL-paths and URL-query-parameters.
* <p>
* For example the input "/some//ex ample///path/" becomes "some/ex%20ample/path".
* @param path the path to be encoded. Must not be <code>null</code>.
* @return the encoded path. Never <code>null</code>.
*/
protected String encodePath(final String path) {
requireNonNull(path, "path");
final StringBuilder sb = new StringBuilder();
final String[] segments = path.split("/");
for (final String segment : segments) {
if (segment.isEmpty())
continue;
if (sb.length() != 0)
sb.append('/');
sb.append(urlEncode(segment));
}
return sb.toString();
}
protected void assertResponseIndicatesSuccess(final Response response) {
if (400 <= response.getStatus() && response.getStatus() <= 599) {
response.bufferEntity();
if (response.hasEntity()) {
Error error = null;
try {
error = response.readEntity(Error.class);
} catch (final Exception y) {
logger.error("handleException: " + y, y);
}
if (error != null) {
throwOriginalExceptionIfPossible(error);
throw new RemoteException(error);
}
}
throw new WebApplicationException(response);
}
}
protected void throwOriginalExceptionIfPossible(final Error error) {
RemoteExceptionUtil.throwOriginalExceptionIfPossible(error);
}
} |
File |
Project |
Line |
co/codewizards/cloudstore/core/io/InStream.java |
co.codewizards.cloudstore.core |
16 |
co/codewizards/cloudstore/core/io/InStream.java |
co.codewizards.cloudstore.core |
70 |
protected InverseInStream(final IInputStream in) {
this.in = requireNonNull(in, "in");
}
@Override
public int read() throws IOException {
return in.read();
}
@Override
public int read(byte[] b) throws IOException {
return in.read(b);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return in.read(b, off, len);
}
@Override
public long skip(long n) throws IOException {
return in.skip(n);
}
@Override
public int available() throws IOException {
return in.available();
}
@Override
public void close() throws IOException {
in.close();
}
@Override
public synchronized void mark(int readlimit) {
in.mark(readlimit);
}
@Override
public synchronized void reset() throws IOException {
in.reset();
}
@Override
public boolean markSupported() {
return in.markSupported();
} |
File |
Project |
Line |
co/codewizards/cloudstore/local/db/DerbyDatabaseAdapter.java |
co.codewizards.cloudstore.local |
42 |
co/codewizards/cloudstore/local/db/ExternalJdbcDatabaseAdapter.java |
co.codewizards.cloudstore.local |
157 |
logger.info("dropDatabase: Dropped '{}'!", databaseName);
}
private void initDriverClass() {
if (isEmpty(connectionDriverName))
return;
try {
Class.forName(connectionDriverName);
} catch (Throwable e) { // Might theoretically be a link error (i.e. a sub-class of Error instead of Exception) => catch Throwable
logger.warn("initDriverClass: " + e, e);
}
}
@Override
public Connection createConnection() throws SQLException {
if (connectionURL == null) {
initProperties();
initDriverClass();
}
if (isEmpty(connectionUserName) && isEmpty(connectionPassword))
return DriverManager.getConnection(connectionURL);
else
return DriverManager.getConnection(connectionURL, connectionUserName, connectionPassword);
}
private void initProperties() {
PersistencePropertiesProvider persistencePropertiesProvider = new PersistencePropertiesProvider(getRepositoryIdOrFail(), getLocalRootOrFail());
persistenceProperties = persistencePropertiesProvider.getPersistenceProperties();
connectionDriverName = persistenceProperties.get(PersistencePropertiesEnum.CONNECTION_DRIVER_NAME.key);
connectionURL = persistenceProperties.get(PersistencePropertiesEnum.CONNECTION_URL.key);
connectionUserName = persistenceProperties.get(PersistencePropertiesEnum.CONNECTION_USER_NAME.key);
connectionPassword = persistenceProperties.get(PersistencePropertiesEnum.CONNECTION_PASSWORD.key);
} |
File |
Project |
Line |
co/codewizards/cloudstore/ls/client/handler/InverseMethodInvocationRequestHandler.java |
co.codewizards.cloudstore.ls.client |
44 |
co/codewizards/cloudstore/ls/rest/server/service/InvokeMethodService.java |
co.codewizards.cloudstore.ls.rest.server |
38 |
final ObjectManager objectManager = inverseInvoker.getObjectManager();
final ClassManager classManager = objectManager.getClassManager();
final String className = methodInvocationRequest.getClassName();
final Class<?> clazz = className == null ? null : classManager.getClassOrFail(className);
final String methodName = methodInvocationRequest.getMethodName();
if (ObjectRef.VIRTUAL_METHOD_NAME_INC_REF_COUNT.equals(methodName)) {
final ObjectRefWithRefId[] objectRefWithRefIds = cast(methodInvocationRequest.getArguments()[0]);
for (final ObjectRefWithRefId objectRefWithRefId : objectRefWithRefIds)
objectManager.incRefCount(objectRefWithRefId.object, objectRefWithRefId.refId);
return MethodInvocationResponse.forInvocation(null, null);
}
else if (ObjectRef.VIRTUAL_METHOD_NAME_DEC_REF_COUNT.equals(methodName)) {
final ObjectRefWithRefId[] objectRefWithRefIds = cast(methodInvocationRequest.getArguments()[0]);
for (final ObjectRefWithRefId objectRefWithRefId : objectRefWithRefIds)
objectManager.decRefCount(objectRefWithRefId.object, objectRefWithRefId.refId);
return MethodInvocationResponse.forInvocation(null, null);
} |
File |
Project |
Line |
co/codewizards/cloudstore/ls/rest/client/LocalServerRestClient.java |
co.codewizards.cloudstore.ls.rest.client |
227 |
co/codewizards/cloudstore/rest/client/CloudStoreRestClient.java |
co.codewizards.cloudstore.rest.client |
259 |
return true;
}
public Invocation.Builder assignCredentials(final Invocation.Builder builder) {
final CredentialsProvider credentialsProvider = getCredentialsProviderOrFail();
builder.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_BASIC_USERNAME, credentialsProvider.getUserName());
builder.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_BASIC_PASSWORD, credentialsProvider.getPassword());
return builder;
}
private final ThreadLocal<ClientRef> clientThreadLocal = new ThreadLocal<ClientRef>();
private static class ClientRef {
public final Client client;
public int refCount = 1;
public boolean broken;
public ClientRef(final Client client) {
this.client = requireNonNull(client, "client");
}
}
/**
* Acquire a {@link Client} and bind it to the current thread.
* <p>
* <b>Important: You must {@linkplain #releaseClient() release} the client!</b> Use a try/finally block!
* @see #releaseClient()
* @see #getClientOrFail()
*/
private synchronized void acquireClient(){
final ClientRef clientRef = clientThreadLocal.get();
if (clientRef != null) {
++clientRef.refCount;
return;
}
Client client = clientCache.poll();
if (client == null) { |
File |
Project |
Line |
co/codewizards/cloudstore/ls/rest/client/request/AbstractRequest.java |
co.codewizards.cloudstore.ls.rest.client |
70 |
co/codewizards/cloudstore/rest/client/request/AbstractRequest.java |
co.codewizards.cloudstore.rest.client |
69 |
return "_" + dtoClass.getSimpleName();
}
/**
* Encodes the given {@code string}.
* <p>
* This method does <i>not</i> use {@link java.net.URLEncoder URLEncoder}, because of
* <a href="https://java.net/jira/browse/JERSEY-417">JERSEY-417</a>.
* <p>
* The result of this method can be used in both URL-paths and URL-query-parameters.
* @param string the {@code String} to be encoded. Must not be <code>null</code>.
* @return the encoded {@code String}.
*/
protected static String urlEncode(final String string) {
requireNonNull(string, "string");
// This UriComponent method is safe. It does not try to handle the '{' and '}'
// specially and with type PATH_SEGMENT, it encodes spaces using '%20' instead of '+'.
// It can therefore be used for *both* path segments *and* query parameters.
// return org.glassfish.jersey.uri.UriComponent.encode(string, UriComponent.Type.PATH_SEGMENT);
return UrlEncoder.encode(string);
}
/**
* Create a {@link WebTarget} from the given path segments.
* <p>
* This method prefixes the path with the {@link #getBaseURL() base-URL} and appends
* all path segments separated via slashes ('/').
* <p>
* We do not use <code>client.target(getBaseURL()).path("...")</code>, because the
* {@link WebTarget#path(String) path(...)} method does not encode curly braces
* (which might be part of a file name!).
* Instead it resolves them using {@linkplain WebTarget#matrixParam(String, Object...) matrix-parameters}.
* The matrix-parameters need to be encoded manually, too (at least I tried it and it failed, if I didn't).
* Because of these reasons and in order to make the calls more compact, we assemble the path
* ourselves here.
* @param pathSegments the parts of the path. May be <code>null</code>. The path segments are
* appended to the path as they are. They are not encoded at all! If you require encoding,
* use {@link #encodePath(String)} or {@link #urlEncode(String)} before! Furthermore, all path segments
* are separated with a slash inbetween them, but <i>not</i> at the end. If a single path segment
* already contains a slash, duplicate slashes might occur.
* @return the target. Never <code>null</code>.
*/
protected WebTarget createWebTarget(final String ... pathSegments) {
final Client client = getClientOrFail();
final StringBuilder sb = new StringBuilder();
sb.append(getBaseURL());
boolean first = true;
if (pathSegments != null && pathSegments.length != 0) {
for (final String pathSegment : pathSegments) {
if (!first) // the base-URL already ends with a slash!
sb.append('/');
first = false;
sb.append(pathSegment);
}
}
final WebTarget webTarget = client.target(URI.create(sb.toString()));
return webTarget;
}
/**
* Get the server's base-URL.
* <p>
* This base-URL is the base of the <code>CloudStoreREST</code> application. Hence all URLs
* beneath this base-URL are processed by the <code>CloudStoreREST</code> application.
* <p>
* In other words: All repository-names are located directly beneath this base-URL. The special services, too,
* are located directly beneath this base-URL.
* <p>
* For example, if the server's base-URL is "https://host.domain:8443/", then the test-service is
* available via "https://host.domain:8443/_test" and the repository with the alias "myrepo" is
* "https://host.domain:8443/myrepo".
* @return the base-URL. This URL always ends with "/".
*/
protected String getBaseURL() {
return getCloudStoreRestClientOrFail().getBaseUrl(); |
File |
Project |
Line |
co/codewizards/cloudstore/core/util/ReflectionUtil.java |
co.codewizards.cloudstore.core |
345 |
co/codewizards/cloudstore/core/util/ReflectionUtil.java |
co.codewizards.cloudstore.core |
391 |
public static void setFieldValue(final Object object, final String fieldName, final Object value) {
requireNonNull(object, "object");
requireNonNull(fieldName, "fieldName");
// TODO pretty inefficient implementation - make better!
String className = null;
String simpleFieldName = fieldName;
final int lastDotIndex = fieldName.lastIndexOf('.');
if (lastDotIndex >= 0) {
className = fieldName.substring(0, lastDotIndex);
simpleFieldName = fieldName.substring(lastDotIndex + 1);
}
final List<Field> declaredFields = getAllDeclaredFields(object.getClass());
for (final Field field : declaredFields) {
if (className != null && !className.equals(field.getDeclaringClass().getName()))
continue;
if (!simpleFieldName.equals(field.getName()))
continue;
field.setAccessible(true);
try { |
File |
Project |
Line |
co/codewizards/cloudstore/ls/rest/client/LocalServerRestClient.java |
co.codewizards.cloudstore.ls.rest.client |
298 |
co/codewizards/cloudstore/rest/client/CloudStoreRestClient.java |
co.codewizards.cloudstore.rest.client |
305 |
clientThreadLocal.set(new ClientRef(client));
}
/**
* Get the {@link Client} which was previously {@linkplain #acquireClient() acquired} (and not yet
* {@linkplain #releaseClient() released}) on the same thread.
* @return the {@link Client}. Never <code>null</code>.
* @throws IllegalStateException if there is no {@link Client} bound to the current thread.
* @see #acquireClient()
*/
public Client getClientOrFail() {
final ClientRef clientRef = clientThreadLocal.get();
if (clientRef == null)
throw new IllegalStateException("acquireClient() not called on the same thread (or releaseClient() already called)!");
return clientRef.client;
}
/**
* Release a {@link Client} which was previously {@linkplain #acquireClient() acquired}.
* @see #acquireClient()
*/
private synchronized void releaseClient() {
final ClientRef clientRef = clientThreadLocal.get();
if (clientRef == null)
throw new IllegalStateException("acquireClient() not called on the same thread (or releaseClient() called more often than acquireClient())!");
if (--clientRef.refCount == 0) {
clientThreadLocal.remove();
if (!clientRef.broken)
clientCache.add(clientRef.client);
}
}
private void markClientBroken() {
final ClientRef clientRef = clientThreadLocal.get();
if (clientRef == null)
throw new IllegalStateException("acquireClient() not called on the same thread (or releaseClient() called more often than acquireClient())!");
clientRef.broken = true;
} |
File |
Project |
Line |
co/codewizards/cloudstore/core/repo/local/LocalRepoRegistryImpl.java |
co.codewizards.cloudstore.core |
521 |
co/codewizards/cloudstore/core/repo/sync/RepoSyncDaemonImpl.java |
co.codewizards.cloudstore.core |
365 |
executorService.shutdownNow();
}
@Override
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
@Override
public void addPropertyChangeListener(Property property, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(property.name(), listener);
}
@Override
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(listener);
}
@Override
public void removePropertyChangeListener(Property property, PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(property.name(), listener);
}
protected void firePropertyChange(Property property, Object oldValue, Object newValue) {
propertyChangeSupport.firePropertyChange(property.name(), oldValue, newValue);
}
} |
File |
Project |
Line |
co/codewizards/cloudstore/core/io/OutStream.java |
co.codewizards.cloudstore.core |
16 |
co/codewizards/cloudstore/core/io/OutStream.java |
co.codewizards.cloudstore.core |
50 |
protected InverseOutStream(final IOutputStream out) {
this.out = requireNonNull(out, "out");
}
@Override
public void write(int b) throws IOException {
out.write(b);
}
@Override
public void write(byte[] b) throws IOException {
out.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
out.close();
} |
File |
Project |
Line |
co/codewizards/cloudstore/local/JdbcConnectionFactory.java |
co.codewizards.cloudstore.local |
51 |
co/codewizards/cloudstore/local/LocalRepoManagerImpl.java |
co.codewizards.cloudstore.local |
178 |
}
private UUID readRepositoryIdFromRepositoryPropertiesFile() {
final File repositoryPropertiesFile = createFile(getMetaDir(), REPOSITORY_PROPERTIES_FILE_NAME);
try {
final Properties repositoryProperties = new Properties();
try (InputStream in = castStream(repositoryPropertiesFile.createInputStream())) {
repositoryProperties.load(in);
}
final String repositoryIdStr = repositoryProperties.getProperty(PROP_REPOSITORY_ID);
if (isEmpty(repositoryIdStr))
throw new IllegalStateException("repositoryProperties.getProperty(PROP_REPOSITORY_ID) is empty!");
final UUID repositoryId = UUID.fromString(repositoryIdStr);
return repositoryId;
} catch (Exception x) {
throw new RuntimeException("Reading readRepositoryId from '" + repositoryPropertiesFile.getAbsolutePath() + "' failed: " + x, x);
}
} |
File |
Project |
Line |
co/codewizards/cloudstore/ls/core/provider/JavaNativeMessageBodyWriter.java |
co.codewizards.cloudstore.ls.core |
33 |
co/codewizards/cloudstore/ls/core/provider/JavaNativeWithObjectRefMessageBodyWriter.java |
co.codewizards.cloudstore.ls.core |
60 |
}
@Override
public long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
{
return -1;
}
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
// We return always true, because we declared our media-type already in the @Produces above and thus don't need to check it here.
// At least I hope we don't get consulted for media-types that were not declared in @Produces.
return true;
}
@Override
public void writeTo(
Object t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream
) throws IOException, WebApplicationException
{ |
|
|
Documentation
About
Releases
|