repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
---|---|---|---|---|---|---|
hprange/woinject | src/main/java/com/webobjects/foundation/InstantiationInterceptor.java | // Path: src/main/java/com/woinject/InjectableApplication.java
// public abstract class InjectableApplication extends ERXApplication {
// public static InjectableApplication application() {
// return (InjectableApplication) WOApplication.application();
// }
//
// private final Injector injector;
//
// /**
// * Creates an instance of an <code>InjectableApplication</code>. The methods
// * and fields annotated with the <code>@Inject</code> will be injected
// * during the application construction. Constructor injection is not
// * supported at the present time.
// *
// * @see Inject
// */
// public InjectableApplication() {
// super();
//
// injector = createInjector();
//
// injector.injectMembers(this);
// }
//
// /**
// * Creates the injector to be used by the entire application.
// * <p>
// * The <code>WOInjectModule</code> is loaded by default in addition to all
// * the <code>Module</code>s returned by the
// * {@link InjectableApplication#modules()} method.
// * <p>
// * Override this method to create your own injector.
// *
// * @return The main <code>Injector</code> for the entire application
// *
// * @see Injector
// * @see WOInjectModule
// */
// protected Injector createInjector() {
// List<Module> modules = new ArrayList<Module>();
//
// @SuppressWarnings("unchecked")
// Class<? extends WOSession> sessionClass = _sessionClass();
//
// modules.add(new WOInjectModule(sessionClass));
// modules.addAll(Arrays.asList(modules()));
//
// return Guice.createInjector(stage(), modules);
// }
//
// /**
// * Obtain the injector created for this application.
// *
// * @return The injector created during this application initialization
// */
// public Injector injector() {
// return injector;
// }
//
// /**
// * Override this method to inform what <code>Module</code>s should be loaded
// * by the injector during the initialization phase.
// *
// * @return An array of <code>Module</code>s to be loaded when creating the
// * injector
// *
// * @see InjectableApplication#createInjector()
// * @see Module
// */
// protected Module[] modules() {
// return new Module[] {};
// }
//
// /**
// * Obtain the <code>Stage</code> in which the application is running. This
// * stage is to be used by the injector.
// *
// * Override this method to inform the stage in which the application is
// * running
// *
// * @return The stage in which the application is running
// * @see Stage
// */
// protected Stage stage() {
// return isDevelopmentMode() ? Stage.DEVELOPMENT : Stage.PRODUCTION;
// }
// }
//
// Path: src/main/java/com/woinject/WOInjectException.java
// public class WOInjectException extends RuntimeException {
// public WOInjectException() {
// super();
// }
//
// public WOInjectException(String message) {
// super(message);
// }
//
// public WOInjectException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public WOInjectException(Throwable cause) {
// super(cause);
// }
// }
| import com.google.inject.Injector;
import com.woinject.InjectableApplication;
import com.woinject.WOInjectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor; | /**
* Copyright (C) 2010 hprange <[email protected]>
*
* 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.webobjects.foundation;
/**
* The InstantiatorInterceptor class creates objects and injects their
* members (methods and fields only) automatically. This class is private
* and is not intended to be used directly by users.
*
* @author <a href="mailto:[email protected]">Henrique Prange</a>
* @since 1.0
*/
class InstantiationInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(InstantiationInterceptor.class);
private static <T> Constructor<T> findConstructor(final Class<T> type, final Class<?>[] parameterTypes, boolean shouldThrow, boolean shouldLog) {
try {
return type.getConstructor(parameterTypes);
} catch (Exception exception) {
return handleException(type, exception, shouldThrow, shouldLog);
}
}
private static <T, N> N handleException(Class<T> type, Exception exception, boolean shouldThrow, boolean shouldLog) {
if (shouldLog) {
LOGGER.error("The instantiation of " + type.getName() + " class has failed.", exception);
}
if (!shouldThrow) {
return null;
}
| // Path: src/main/java/com/woinject/InjectableApplication.java
// public abstract class InjectableApplication extends ERXApplication {
// public static InjectableApplication application() {
// return (InjectableApplication) WOApplication.application();
// }
//
// private final Injector injector;
//
// /**
// * Creates an instance of an <code>InjectableApplication</code>. The methods
// * and fields annotated with the <code>@Inject</code> will be injected
// * during the application construction. Constructor injection is not
// * supported at the present time.
// *
// * @see Inject
// */
// public InjectableApplication() {
// super();
//
// injector = createInjector();
//
// injector.injectMembers(this);
// }
//
// /**
// * Creates the injector to be used by the entire application.
// * <p>
// * The <code>WOInjectModule</code> is loaded by default in addition to all
// * the <code>Module</code>s returned by the
// * {@link InjectableApplication#modules()} method.
// * <p>
// * Override this method to create your own injector.
// *
// * @return The main <code>Injector</code> for the entire application
// *
// * @see Injector
// * @see WOInjectModule
// */
// protected Injector createInjector() {
// List<Module> modules = new ArrayList<Module>();
//
// @SuppressWarnings("unchecked")
// Class<? extends WOSession> sessionClass = _sessionClass();
//
// modules.add(new WOInjectModule(sessionClass));
// modules.addAll(Arrays.asList(modules()));
//
// return Guice.createInjector(stage(), modules);
// }
//
// /**
// * Obtain the injector created for this application.
// *
// * @return The injector created during this application initialization
// */
// public Injector injector() {
// return injector;
// }
//
// /**
// * Override this method to inform what <code>Module</code>s should be loaded
// * by the injector during the initialization phase.
// *
// * @return An array of <code>Module</code>s to be loaded when creating the
// * injector
// *
// * @see InjectableApplication#createInjector()
// * @see Module
// */
// protected Module[] modules() {
// return new Module[] {};
// }
//
// /**
// * Obtain the <code>Stage</code> in which the application is running. This
// * stage is to be used by the injector.
// *
// * Override this method to inform the stage in which the application is
// * running
// *
// * @return The stage in which the application is running
// * @see Stage
// */
// protected Stage stage() {
// return isDevelopmentMode() ? Stage.DEVELOPMENT : Stage.PRODUCTION;
// }
// }
//
// Path: src/main/java/com/woinject/WOInjectException.java
// public class WOInjectException extends RuntimeException {
// public WOInjectException() {
// super();
// }
//
// public WOInjectException(String message) {
// super(message);
// }
//
// public WOInjectException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public WOInjectException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/main/java/com/webobjects/foundation/InstantiationInterceptor.java
import com.google.inject.Injector;
import com.woinject.InjectableApplication;
import com.woinject.WOInjectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
/**
* Copyright (C) 2010 hprange <[email protected]>
*
* 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.webobjects.foundation;
/**
* The InstantiatorInterceptor class creates objects and injects their
* members (methods and fields only) automatically. This class is private
* and is not intended to be used directly by users.
*
* @author <a href="mailto:[email protected]">Henrique Prange</a>
* @since 1.0
*/
class InstantiationInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(InstantiationInterceptor.class);
private static <T> Constructor<T> findConstructor(final Class<T> type, final Class<?>[] parameterTypes, boolean shouldThrow, boolean shouldLog) {
try {
return type.getConstructor(parameterTypes);
} catch (Exception exception) {
return handleException(type, exception, shouldThrow, shouldLog);
}
}
private static <T, N> N handleException(Class<T> type, Exception exception, boolean shouldThrow, boolean shouldLog) {
if (shouldLog) {
LOGGER.error("The instantiation of " + type.getName() + " class has failed.", exception);
}
if (!shouldThrow) {
return null;
}
| throw new WOInjectException("The instantiation of " + type.getName() + " class has failed.", exception); |
hprange/woinject | src/main/java/com/webobjects/foundation/InstantiationInterceptor.java | // Path: src/main/java/com/woinject/InjectableApplication.java
// public abstract class InjectableApplication extends ERXApplication {
// public static InjectableApplication application() {
// return (InjectableApplication) WOApplication.application();
// }
//
// private final Injector injector;
//
// /**
// * Creates an instance of an <code>InjectableApplication</code>. The methods
// * and fields annotated with the <code>@Inject</code> will be injected
// * during the application construction. Constructor injection is not
// * supported at the present time.
// *
// * @see Inject
// */
// public InjectableApplication() {
// super();
//
// injector = createInjector();
//
// injector.injectMembers(this);
// }
//
// /**
// * Creates the injector to be used by the entire application.
// * <p>
// * The <code>WOInjectModule</code> is loaded by default in addition to all
// * the <code>Module</code>s returned by the
// * {@link InjectableApplication#modules()} method.
// * <p>
// * Override this method to create your own injector.
// *
// * @return The main <code>Injector</code> for the entire application
// *
// * @see Injector
// * @see WOInjectModule
// */
// protected Injector createInjector() {
// List<Module> modules = new ArrayList<Module>();
//
// @SuppressWarnings("unchecked")
// Class<? extends WOSession> sessionClass = _sessionClass();
//
// modules.add(new WOInjectModule(sessionClass));
// modules.addAll(Arrays.asList(modules()));
//
// return Guice.createInjector(stage(), modules);
// }
//
// /**
// * Obtain the injector created for this application.
// *
// * @return The injector created during this application initialization
// */
// public Injector injector() {
// return injector;
// }
//
// /**
// * Override this method to inform what <code>Module</code>s should be loaded
// * by the injector during the initialization phase.
// *
// * @return An array of <code>Module</code>s to be loaded when creating the
// * injector
// *
// * @see InjectableApplication#createInjector()
// * @see Module
// */
// protected Module[] modules() {
// return new Module[] {};
// }
//
// /**
// * Obtain the <code>Stage</code> in which the application is running. This
// * stage is to be used by the injector.
// *
// * Override this method to inform the stage in which the application is
// * running
// *
// * @return The stage in which the application is running
// * @see Stage
// */
// protected Stage stage() {
// return isDevelopmentMode() ? Stage.DEVELOPMENT : Stage.PRODUCTION;
// }
// }
//
// Path: src/main/java/com/woinject/WOInjectException.java
// public class WOInjectException extends RuntimeException {
// public WOInjectException() {
// super();
// }
//
// public WOInjectException(String message) {
// super(message);
// }
//
// public WOInjectException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public WOInjectException(Throwable cause) {
// super(cause);
// }
// }
| import com.google.inject.Injector;
import com.woinject.InjectableApplication;
import com.woinject.WOInjectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor; | /**
* Copyright (C) 2010 hprange <[email protected]>
*
* 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.webobjects.foundation;
/**
* The InstantiatorInterceptor class creates objects and injects their
* members (methods and fields only) automatically. This class is private
* and is not intended to be used directly by users.
*
* @author <a href="mailto:[email protected]">Henrique Prange</a>
* @since 1.0
*/
class InstantiationInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(InstantiationInterceptor.class);
private static <T> Constructor<T> findConstructor(final Class<T> type, final Class<?>[] parameterTypes, boolean shouldThrow, boolean shouldLog) {
try {
return type.getConstructor(parameterTypes);
} catch (Exception exception) {
return handleException(type, exception, shouldThrow, shouldLog);
}
}
private static <T, N> N handleException(Class<T> type, Exception exception, boolean shouldThrow, boolean shouldLog) {
if (shouldLog) {
LOGGER.error("The instantiation of " + type.getName() + " class has failed.", exception);
}
if (!shouldThrow) {
return null;
}
throw new WOInjectException("The instantiation of " + type.getName() + " class has failed.", exception);
}
private static Injector injector() { | // Path: src/main/java/com/woinject/InjectableApplication.java
// public abstract class InjectableApplication extends ERXApplication {
// public static InjectableApplication application() {
// return (InjectableApplication) WOApplication.application();
// }
//
// private final Injector injector;
//
// /**
// * Creates an instance of an <code>InjectableApplication</code>. The methods
// * and fields annotated with the <code>@Inject</code> will be injected
// * during the application construction. Constructor injection is not
// * supported at the present time.
// *
// * @see Inject
// */
// public InjectableApplication() {
// super();
//
// injector = createInjector();
//
// injector.injectMembers(this);
// }
//
// /**
// * Creates the injector to be used by the entire application.
// * <p>
// * The <code>WOInjectModule</code> is loaded by default in addition to all
// * the <code>Module</code>s returned by the
// * {@link InjectableApplication#modules()} method.
// * <p>
// * Override this method to create your own injector.
// *
// * @return The main <code>Injector</code> for the entire application
// *
// * @see Injector
// * @see WOInjectModule
// */
// protected Injector createInjector() {
// List<Module> modules = new ArrayList<Module>();
//
// @SuppressWarnings("unchecked")
// Class<? extends WOSession> sessionClass = _sessionClass();
//
// modules.add(new WOInjectModule(sessionClass));
// modules.addAll(Arrays.asList(modules()));
//
// return Guice.createInjector(stage(), modules);
// }
//
// /**
// * Obtain the injector created for this application.
// *
// * @return The injector created during this application initialization
// */
// public Injector injector() {
// return injector;
// }
//
// /**
// * Override this method to inform what <code>Module</code>s should be loaded
// * by the injector during the initialization phase.
// *
// * @return An array of <code>Module</code>s to be loaded when creating the
// * injector
// *
// * @see InjectableApplication#createInjector()
// * @see Module
// */
// protected Module[] modules() {
// return new Module[] {};
// }
//
// /**
// * Obtain the <code>Stage</code> in which the application is running. This
// * stage is to be used by the injector.
// *
// * Override this method to inform the stage in which the application is
// * running
// *
// * @return The stage in which the application is running
// * @see Stage
// */
// protected Stage stage() {
// return isDevelopmentMode() ? Stage.DEVELOPMENT : Stage.PRODUCTION;
// }
// }
//
// Path: src/main/java/com/woinject/WOInjectException.java
// public class WOInjectException extends RuntimeException {
// public WOInjectException() {
// super();
// }
//
// public WOInjectException(String message) {
// super(message);
// }
//
// public WOInjectException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public WOInjectException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/main/java/com/webobjects/foundation/InstantiationInterceptor.java
import com.google.inject.Injector;
import com.woinject.InjectableApplication;
import com.woinject.WOInjectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
/**
* Copyright (C) 2010 hprange <[email protected]>
*
* 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.webobjects.foundation;
/**
* The InstantiatorInterceptor class creates objects and injects their
* members (methods and fields only) automatically. This class is private
* and is not intended to be used directly by users.
*
* @author <a href="mailto:[email protected]">Henrique Prange</a>
* @since 1.0
*/
class InstantiationInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(InstantiationInterceptor.class);
private static <T> Constructor<T> findConstructor(final Class<T> type, final Class<?>[] parameterTypes, boolean shouldThrow, boolean shouldLog) {
try {
return type.getConstructor(parameterTypes);
} catch (Exception exception) {
return handleException(type, exception, shouldThrow, shouldLog);
}
}
private static <T, N> N handleException(Class<T> type, Exception exception, boolean shouldThrow, boolean shouldLog) {
if (shouldLog) {
LOGGER.error("The instantiation of " + type.getName() + " class has failed.", exception);
}
if (!shouldThrow) {
return null;
}
throw new WOInjectException("The instantiation of " + type.getName() + " class has failed.", exception);
}
private static Injector injector() { | InjectableApplication application = InjectableApplication.application(); |
hprange/woinject | src/test/java/com/woinject/TestWOSessionProvider.java | // Path: src/test/java/com/woinject/stubs/StubApplication.java
// public class StubApplication extends InjectableApplication {
// private static class StubModule extends AbstractModule {
// private boolean moduleWasLoaded = false;
//
// @Override
// protected void configure() {
// moduleWasLoaded = true;
//
// bind(String.class).annotatedWith(Names.named("field")).toInstance("fieldInjected");
// bind(String.class).annotatedWith(Names.named("method")).toInstance("methodInjected");
// }
// }
//
// public static void setApplication(WOApplication application) {
// try {
// Method method = WOApplication.class.getDeclaredMethod("_setApplication", WOApplication.class);
//
// method.setAccessible(true);
//
// method.invoke(null, application);
// } catch (Exception exception) {
// throw new RuntimeException(exception);
// }
// }
//
// @Inject
// @Named("field")
// private String injectableField;
//
// private String injectableMethod;
//
// private boolean nullInjector = false;
//
// private StubModule stubModule;
//
// @Override
// protected Class<StubSession> _sessionClass() {
// return StubSession.class;
// }
//
// public String getInjectableField() {
// return injectableField;
// }
//
// public String getInjectableMethod() {
// return injectableMethod;
// }
//
// @Inject
// public void initInjectableMethod(@Named("method") String value) {
// injectableMethod = value;
// }
//
// @Override
// public Injector injector() {
// if (nullInjector) {
// return null;
// }
//
// return super.injector();
// }
//
// @Override
// protected Module[] modules() {
// stubModule = new StubModule();
//
// return new Module[] { stubModule };
// }
//
// public void setReturnNullInjector(boolean nullInjector) {
// this.nullInjector = nullInjector;
// }
//
// public boolean stubModuleWasLoaded() {
// return stubModule.moduleWasLoaded;
// }
// }
| import er.extensions.appserver.ERXSession;
import er.extensions.appserver.ERXWOContext;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import com.webobjects.appserver.WOApplication;
import com.webobjects.appserver.WOContext;
import com.woinject.stubs.StubApplication; | ERXSession.setSession(null);
ERXWOContext.setCurrentContext(null);
}
@Test
public void returnSessionFromERXSession() throws Exception {
ERXSession.setSession(session);
WOSessionProvider<ERXSession> provider = new WOSessionProvider<ERXSession>();
assertThat(provider.get(), is(session));
}
@Test
public void returnSessionFromWOContext() throws Exception {
ERXWOContext.setCurrentContext(context);
when(context._session()).thenReturn(session);
WOSessionProvider<ERXSession> provider = new WOSessionProvider<ERXSession>();
assertThat(provider.get(), is(session));
}
@Test
public void returnSessionFromSessionID() throws Exception {
ERXWOContext.setCurrentContext(context);
when(context._requestSessionID()).thenReturn("session-123");
| // Path: src/test/java/com/woinject/stubs/StubApplication.java
// public class StubApplication extends InjectableApplication {
// private static class StubModule extends AbstractModule {
// private boolean moduleWasLoaded = false;
//
// @Override
// protected void configure() {
// moduleWasLoaded = true;
//
// bind(String.class).annotatedWith(Names.named("field")).toInstance("fieldInjected");
// bind(String.class).annotatedWith(Names.named("method")).toInstance("methodInjected");
// }
// }
//
// public static void setApplication(WOApplication application) {
// try {
// Method method = WOApplication.class.getDeclaredMethod("_setApplication", WOApplication.class);
//
// method.setAccessible(true);
//
// method.invoke(null, application);
// } catch (Exception exception) {
// throw new RuntimeException(exception);
// }
// }
//
// @Inject
// @Named("field")
// private String injectableField;
//
// private String injectableMethod;
//
// private boolean nullInjector = false;
//
// private StubModule stubModule;
//
// @Override
// protected Class<StubSession> _sessionClass() {
// return StubSession.class;
// }
//
// public String getInjectableField() {
// return injectableField;
// }
//
// public String getInjectableMethod() {
// return injectableMethod;
// }
//
// @Inject
// public void initInjectableMethod(@Named("method") String value) {
// injectableMethod = value;
// }
//
// @Override
// public Injector injector() {
// if (nullInjector) {
// return null;
// }
//
// return super.injector();
// }
//
// @Override
// protected Module[] modules() {
// stubModule = new StubModule();
//
// return new Module[] { stubModule };
// }
//
// public void setReturnNullInjector(boolean nullInjector) {
// this.nullInjector = nullInjector;
// }
//
// public boolean stubModuleWasLoaded() {
// return stubModule.moduleWasLoaded;
// }
// }
// Path: src/test/java/com/woinject/TestWOSessionProvider.java
import er.extensions.appserver.ERXSession;
import er.extensions.appserver.ERXWOContext;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import com.webobjects.appserver.WOApplication;
import com.webobjects.appserver.WOContext;
import com.woinject.stubs.StubApplication;
ERXSession.setSession(null);
ERXWOContext.setCurrentContext(null);
}
@Test
public void returnSessionFromERXSession() throws Exception {
ERXSession.setSession(session);
WOSessionProvider<ERXSession> provider = new WOSessionProvider<ERXSession>();
assertThat(provider.get(), is(session));
}
@Test
public void returnSessionFromWOContext() throws Exception {
ERXWOContext.setCurrentContext(context);
when(context._session()).thenReturn(session);
WOSessionProvider<ERXSession> provider = new WOSessionProvider<ERXSession>();
assertThat(provider.get(), is(session));
}
@Test
public void returnSessionFromSessionID() throws Exception {
ERXWOContext.setCurrentContext(context);
when(context._requestSessionID()).thenReturn("session-123");
| StubApplication.setApplication(application); |
hprange/woinject | src/test/java/com/woinject/TestWOSessionScope.java | // Path: src/test/java/com/woinject/stubs/StubApplication.java
// public class StubApplication extends InjectableApplication {
// private static class StubModule extends AbstractModule {
// private boolean moduleWasLoaded = false;
//
// @Override
// protected void configure() {
// moduleWasLoaded = true;
//
// bind(String.class).annotatedWith(Names.named("field")).toInstance("fieldInjected");
// bind(String.class).annotatedWith(Names.named("method")).toInstance("methodInjected");
// }
// }
//
// public static void setApplication(WOApplication application) {
// try {
// Method method = WOApplication.class.getDeclaredMethod("_setApplication", WOApplication.class);
//
// method.setAccessible(true);
//
// method.invoke(null, application);
// } catch (Exception exception) {
// throw new RuntimeException(exception);
// }
// }
//
// @Inject
// @Named("field")
// private String injectableField;
//
// private String injectableMethod;
//
// private boolean nullInjector = false;
//
// private StubModule stubModule;
//
// @Override
// protected Class<StubSession> _sessionClass() {
// return StubSession.class;
// }
//
// public String getInjectableField() {
// return injectableField;
// }
//
// public String getInjectableMethod() {
// return injectableMethod;
// }
//
// @Inject
// public void initInjectableMethod(@Named("method") String value) {
// injectableMethod = value;
// }
//
// @Override
// public Injector injector() {
// if (nullInjector) {
// return null;
// }
//
// return super.injector();
// }
//
// @Override
// protected Module[] modules() {
// stubModule = new StubModule();
//
// return new Module[] { stubModule };
// }
//
// public void setReturnNullInjector(boolean nullInjector) {
// this.nullInjector = nullInjector;
// }
//
// public boolean stubModuleWasLoaded() {
// return stubModule.moduleWasLoaded;
// }
// }
| import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.inject.Key;
import com.google.inject.OutOfScopeException;
import com.google.inject.Provider;
import com.webobjects.appserver.WOApplication;
import com.webobjects.appserver.WOContext;
import com.webobjects.foundation.NSKeyValueCoding;
import com.woinject.stubs.StubApplication;
import er.extensions.appserver.ERXSession;
import er.extensions.appserver.ERXWOContext; | /**
* Copyright (C) 2010 hprange <[email protected]>
*
* 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.woinject;
/**
* @author <a href="mailto:[email protected]">Henrique Prange</a>
*/
@RunWith(MockitoJUnitRunner.class)
public class TestWOSessionScope extends AbstractScopeTestCase<WOSessionScope> {
@Mock
private ERXSession mockSession;
@Mock
private WOContext mockContext;
@Mock
private WOApplication application;
@Before
public void setup() {
scope = new WOSessionScope();
ERXSession.setSession(mockSession);
ERXWOContext.setCurrentContext(mockContext);
| // Path: src/test/java/com/woinject/stubs/StubApplication.java
// public class StubApplication extends InjectableApplication {
// private static class StubModule extends AbstractModule {
// private boolean moduleWasLoaded = false;
//
// @Override
// protected void configure() {
// moduleWasLoaded = true;
//
// bind(String.class).annotatedWith(Names.named("field")).toInstance("fieldInjected");
// bind(String.class).annotatedWith(Names.named("method")).toInstance("methodInjected");
// }
// }
//
// public static void setApplication(WOApplication application) {
// try {
// Method method = WOApplication.class.getDeclaredMethod("_setApplication", WOApplication.class);
//
// method.setAccessible(true);
//
// method.invoke(null, application);
// } catch (Exception exception) {
// throw new RuntimeException(exception);
// }
// }
//
// @Inject
// @Named("field")
// private String injectableField;
//
// private String injectableMethod;
//
// private boolean nullInjector = false;
//
// private StubModule stubModule;
//
// @Override
// protected Class<StubSession> _sessionClass() {
// return StubSession.class;
// }
//
// public String getInjectableField() {
// return injectableField;
// }
//
// public String getInjectableMethod() {
// return injectableMethod;
// }
//
// @Inject
// public void initInjectableMethod(@Named("method") String value) {
// injectableMethod = value;
// }
//
// @Override
// public Injector injector() {
// if (nullInjector) {
// return null;
// }
//
// return super.injector();
// }
//
// @Override
// protected Module[] modules() {
// stubModule = new StubModule();
//
// return new Module[] { stubModule };
// }
//
// public void setReturnNullInjector(boolean nullInjector) {
// this.nullInjector = nullInjector;
// }
//
// public boolean stubModuleWasLoaded() {
// return stubModule.moduleWasLoaded;
// }
// }
// Path: src/test/java/com/woinject/TestWOSessionScope.java
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.inject.Key;
import com.google.inject.OutOfScopeException;
import com.google.inject.Provider;
import com.webobjects.appserver.WOApplication;
import com.webobjects.appserver.WOContext;
import com.webobjects.foundation.NSKeyValueCoding;
import com.woinject.stubs.StubApplication;
import er.extensions.appserver.ERXSession;
import er.extensions.appserver.ERXWOContext;
/**
* Copyright (C) 2010 hprange <[email protected]>
*
* 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.woinject;
/**
* @author <a href="mailto:[email protected]">Henrique Prange</a>
*/
@RunWith(MockitoJUnitRunner.class)
public class TestWOSessionScope extends AbstractScopeTestCase<WOSessionScope> {
@Mock
private ERXSession mockSession;
@Mock
private WOContext mockContext;
@Mock
private WOApplication application;
@Before
public void setup() {
scope = new WOSessionScope();
ERXSession.setSession(mockSession);
ERXWOContext.setCurrentContext(mockContext);
| StubApplication.setApplication(application); |
hprange/woinject | src/test/java/com/woinject/TestInjectableApplication.java | // Path: src/test/java/com/woinject/stubs/StubApplication.java
// public class StubApplication extends InjectableApplication {
// private static class StubModule extends AbstractModule {
// private boolean moduleWasLoaded = false;
//
// @Override
// protected void configure() {
// moduleWasLoaded = true;
//
// bind(String.class).annotatedWith(Names.named("field")).toInstance("fieldInjected");
// bind(String.class).annotatedWith(Names.named("method")).toInstance("methodInjected");
// }
// }
//
// public static void setApplication(WOApplication application) {
// try {
// Method method = WOApplication.class.getDeclaredMethod("_setApplication", WOApplication.class);
//
// method.setAccessible(true);
//
// method.invoke(null, application);
// } catch (Exception exception) {
// throw new RuntimeException(exception);
// }
// }
//
// @Inject
// @Named("field")
// private String injectableField;
//
// private String injectableMethod;
//
// private boolean nullInjector = false;
//
// private StubModule stubModule;
//
// @Override
// protected Class<StubSession> _sessionClass() {
// return StubSession.class;
// }
//
// public String getInjectableField() {
// return injectableField;
// }
//
// public String getInjectableMethod() {
// return injectableMethod;
// }
//
// @Inject
// public void initInjectableMethod(@Named("method") String value) {
// injectableMethod = value;
// }
//
// @Override
// public Injector injector() {
// if (nullInjector) {
// return null;
// }
//
// return super.injector();
// }
//
// @Override
// protected Module[] modules() {
// stubModule = new StubModule();
//
// return new Module[] { stubModule };
// }
//
// public void setReturnNullInjector(boolean nullInjector) {
// this.nullInjector = nullInjector;
// }
//
// public boolean stubModuleWasLoaded() {
// return stubModule.moduleWasLoaded;
// }
// }
| import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import org.junit.After;
import org.junit.Test;
import com.google.inject.Injector;
import com.google.inject.Stage;
import com.woinject.stubs.StubApplication;
import er.extensions.foundation.ERXProperties; | /**
* Copyright (C) 2010 hprange <[email protected]>
*
* 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.woinject;
/**
* @author <a href="mailto:[email protected]">Henrique Prange</a>
*/
public class TestInjectableApplication extends AbstractInjectableTestCase {
private static final String DEVELOPMENT_MODE_KEY = "er.extensions.ERXApplication.developmentMode";
@Test
public void appendAndLoadStubModuleOnInjectorInitialization() throws Exception { | // Path: src/test/java/com/woinject/stubs/StubApplication.java
// public class StubApplication extends InjectableApplication {
// private static class StubModule extends AbstractModule {
// private boolean moduleWasLoaded = false;
//
// @Override
// protected void configure() {
// moduleWasLoaded = true;
//
// bind(String.class).annotatedWith(Names.named("field")).toInstance("fieldInjected");
// bind(String.class).annotatedWith(Names.named("method")).toInstance("methodInjected");
// }
// }
//
// public static void setApplication(WOApplication application) {
// try {
// Method method = WOApplication.class.getDeclaredMethod("_setApplication", WOApplication.class);
//
// method.setAccessible(true);
//
// method.invoke(null, application);
// } catch (Exception exception) {
// throw new RuntimeException(exception);
// }
// }
//
// @Inject
// @Named("field")
// private String injectableField;
//
// private String injectableMethod;
//
// private boolean nullInjector = false;
//
// private StubModule stubModule;
//
// @Override
// protected Class<StubSession> _sessionClass() {
// return StubSession.class;
// }
//
// public String getInjectableField() {
// return injectableField;
// }
//
// public String getInjectableMethod() {
// return injectableMethod;
// }
//
// @Inject
// public void initInjectableMethod(@Named("method") String value) {
// injectableMethod = value;
// }
//
// @Override
// public Injector injector() {
// if (nullInjector) {
// return null;
// }
//
// return super.injector();
// }
//
// @Override
// protected Module[] modules() {
// stubModule = new StubModule();
//
// return new Module[] { stubModule };
// }
//
// public void setReturnNullInjector(boolean nullInjector) {
// this.nullInjector = nullInjector;
// }
//
// public boolean stubModuleWasLoaded() {
// return stubModule.moduleWasLoaded;
// }
// }
// Path: src/test/java/com/woinject/TestInjectableApplication.java
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import org.junit.After;
import org.junit.Test;
import com.google.inject.Injector;
import com.google.inject.Stage;
import com.woinject.stubs.StubApplication;
import er.extensions.foundation.ERXProperties;
/**
* Copyright (C) 2010 hprange <[email protected]>
*
* 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.woinject;
/**
* @author <a href="mailto:[email protected]">Henrique Prange</a>
*/
public class TestInjectableApplication extends AbstractInjectableTestCase {
private static final String DEVELOPMENT_MODE_KEY = "er.extensions.ERXApplication.developmentMode";
@Test
public void appendAndLoadStubModuleOnInjectorInitialization() throws Exception { | assertThat(((StubApplication) application).stubModuleWasLoaded(), is(true)); |
gesellix/Nimbus-JOSE-JWT | src/test/java/com/nimbusds/jose/JWSHeaderTest.java | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
| import java.text.ParseException;
import junit.framework.TestCase;
import com.nimbusds.jose.util.Base64URL; | package com.nimbusds.jose;
/**
* Tests JWS header parsing and serialisation.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-01)
*/
public class JWSHeaderTest extends TestCase {
public void testParseJSONText() {
// Example header from JWS spec
String s = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}";
JWSHeader h = null;
try {
h = JWSHeader.parse(s);
} catch (ParseException e) {
fail(e.getMessage());
}
assertNotNull(h);
assertEquals(new JOSEObjectType("JWT"), h.getType());
assertEquals(JWSAlgorithm.HS256, h.getAlgorithm());
assertNull(h.getContentType());
assertTrue(h.getIncludedParameters().contains("alg"));
assertTrue(h.getIncludedParameters().contains("typ"));
assertEquals(2, h.getIncludedParameters().size());
}
public void testParseBase64URLText() {
// Example header from JWS spec
String s = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9";
JWSHeader h = null;
try { | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
// Path: src/test/java/com/nimbusds/jose/JWSHeaderTest.java
import java.text.ParseException;
import junit.framework.TestCase;
import com.nimbusds.jose.util.Base64URL;
package com.nimbusds.jose;
/**
* Tests JWS header parsing and serialisation.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-01)
*/
public class JWSHeaderTest extends TestCase {
public void testParseJSONText() {
// Example header from JWS spec
String s = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}";
JWSHeader h = null;
try {
h = JWSHeader.parse(s);
} catch (ParseException e) {
fail(e.getMessage());
}
assertNotNull(h);
assertEquals(new JOSEObjectType("JWT"), h.getType());
assertEquals(JWSAlgorithm.HS256, h.getAlgorithm());
assertNull(h.getContentType());
assertTrue(h.getIncludedParameters().contains("alg"));
assertTrue(h.getIncludedParameters().contains("typ"));
assertEquals(2, h.getIncludedParameters().size());
}
public void testParseBase64URLText() {
// Example header from JWS spec
String s = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9";
JWSHeader h = null;
try { | h = JWSHeader.parse(new Base64URL(s)); |
gesellix/Nimbus-JOSE-JWT | src/main/java/com/nimbusds/jose/ReadOnlyJWEHeader.java | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
| import com.nimbusds.jose.util.Base64URL; | package com.nimbusds.jose;
/**
* Read-only view of a {@link JWEHeader JWE header}.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-16)
*/
public interface ReadOnlyJWEHeader extends ReadOnlyCommonSEHeader {
/**
* Gets the algorithm ({@code alg}) parameter.
*
* @return The algorithm parameter.
*/
@Override
public JWEAlgorithm getAlgorithm();
/**
* Gets the encryption method ({@code enc}) parameter.
*
* @return The encryption method parameter.
*/
public EncryptionMethod getEncryptionMethod();
/**
* Gets the Ephemeral Public Key ({@code epk}) parameter.
*
* @return The Ephemeral Public Key parameter, {@code null} if not
* specified.
*/
public ECKey getEphemeralPublicKey();
/**
* Gets the compression algorithm ({@code zip}) parameter.
*
* @return The compression algorithm parameter, {@code null} if not
* specified.
*/
public CompressionAlgorithm getCompressionAlgorithm();
/**
* Gets the agreement PartyUInfo ({@code apu}) parameter.
*
* @return The agreement PartyUInfo parameter, {@code null} if not
* specified.
*/ | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
// Path: src/main/java/com/nimbusds/jose/ReadOnlyJWEHeader.java
import com.nimbusds.jose.util.Base64URL;
package com.nimbusds.jose;
/**
* Read-only view of a {@link JWEHeader JWE header}.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-16)
*/
public interface ReadOnlyJWEHeader extends ReadOnlyCommonSEHeader {
/**
* Gets the algorithm ({@code alg}) parameter.
*
* @return The algorithm parameter.
*/
@Override
public JWEAlgorithm getAlgorithm();
/**
* Gets the encryption method ({@code enc}) parameter.
*
* @return The encryption method parameter.
*/
public EncryptionMethod getEncryptionMethod();
/**
* Gets the Ephemeral Public Key ({@code epk}) parameter.
*
* @return The Ephemeral Public Key parameter, {@code null} if not
* specified.
*/
public ECKey getEphemeralPublicKey();
/**
* Gets the compression algorithm ({@code zip}) parameter.
*
* @return The compression algorithm parameter, {@code null} if not
* specified.
*/
public CompressionAlgorithm getCompressionAlgorithm();
/**
* Gets the agreement PartyUInfo ({@code apu}) parameter.
*
* @return The agreement PartyUInfo parameter, {@code null} if not
* specified.
*/ | public Base64URL getAgreementPartyUInfo(); |
gesellix/Nimbus-JOSE-JWT | src/main/java/com/nimbusds/jose/JWEDecrypter.java | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
| import java.util.Set;
import com.nimbusds.jose.util.Base64URL; | package com.nimbusds.jose;
/**
* Interface for decrypting JSON Web Encryption (JWE) objects.
*
* <p>Callers can query the decrypter to determine its algorithm capabilities as
* well as the JWE algorithms and header parameters that are accepted for
* processing.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-16)
*/
public interface JWEDecrypter extends JWEAlgorithmProvider {
/**
* Gets the JWE header filter associated with the decrypter. Specifies
* the names of those {@link #supportedAlgorithms supported JWE
* algorithms} and header parameters that the decrypter is configured to
* accept.
*
* <p>Attempting to {@link #decrypt decrypt} a JWE object with an
* algorithm or header parameter that is not accepted must result in a
* {@link JOSEException}.
*
* @return The JWE header filter.
*/
public JWEHeaderFilter getJWEHeaderFilter();
/**
* Decrypts the specified cipher text of a {@link JWEObject JWE Object}.
*
* @param header The JSON Web Encryption (JWE) header. Must
* specify an accepted JWE algorithm, must contain
* only accepted header parameters, and must not
* be {@code null}.
* @param encryptedKey The encrypted key, {@code null} if not required
* by the JWE algorithm.
* @param iv The initialisation vector, {@code null} if not
* required by the JWE algorithm.
* @param cipherText The cipher text to decrypt. Must not be
* {@code null}.
* @param integrityValue The integrity value, {@code null} if not
* required by the JWE algorithm.
*
* @return The clear text.
*
* @throws JOSEException If the JWE algorithm is not accepted, if a
* header parameter is not accepted, or if
* decryption failed for some other reason.
*/
public byte[] decrypt(final ReadOnlyJWEHeader header, | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
// Path: src/main/java/com/nimbusds/jose/JWEDecrypter.java
import java.util.Set;
import com.nimbusds.jose.util.Base64URL;
package com.nimbusds.jose;
/**
* Interface for decrypting JSON Web Encryption (JWE) objects.
*
* <p>Callers can query the decrypter to determine its algorithm capabilities as
* well as the JWE algorithms and header parameters that are accepted for
* processing.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-16)
*/
public interface JWEDecrypter extends JWEAlgorithmProvider {
/**
* Gets the JWE header filter associated with the decrypter. Specifies
* the names of those {@link #supportedAlgorithms supported JWE
* algorithms} and header parameters that the decrypter is configured to
* accept.
*
* <p>Attempting to {@link #decrypt decrypt} a JWE object with an
* algorithm or header parameter that is not accepted must result in a
* {@link JOSEException}.
*
* @return The JWE header filter.
*/
public JWEHeaderFilter getJWEHeaderFilter();
/**
* Decrypts the specified cipher text of a {@link JWEObject JWE Object}.
*
* @param header The JSON Web Encryption (JWE) header. Must
* specify an accepted JWE algorithm, must contain
* only accepted header parameters, and must not
* be {@code null}.
* @param encryptedKey The encrypted key, {@code null} if not required
* by the JWE algorithm.
* @param iv The initialisation vector, {@code null} if not
* required by the JWE algorithm.
* @param cipherText The cipher text to decrypt. Must not be
* {@code null}.
* @param integrityValue The integrity value, {@code null} if not
* required by the JWE algorithm.
*
* @return The clear text.
*
* @throws JOSEException If the JWE algorithm is not accepted, if a
* header parameter is not accepted, or if
* decryption failed for some other reason.
*/
public byte[] decrypt(final ReadOnlyJWEHeader header, | final Base64URL encryptedKey, |
gesellix/Nimbus-JOSE-JWT | src/test/java/com/nimbusds/jose/PlainHeaderTest.java | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
| import java.text.ParseException;
import junit.framework.TestCase;
import com.nimbusds.jose.util.Base64URL; | package com.nimbusds.jose;
/**
* Tests plain header parsing and serialisation.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-01)
*/
public class PlainHeaderTest extends TestCase {
public void testSerializeAndParse() {
PlainHeader h = new PlainHeader();
assertEquals(Algorithm.NONE, h.getAlgorithm());
assertNull(h.getType());
assertNull(h.getContentType());
h.setType(new JOSEObjectType("JWT"));
h.setContentType("application/jwt");
h.setCustomParameter("xCustom", "abc");
assertTrue(h.getIncludedParameters().contains("alg"));
assertTrue(h.getIncludedParameters().contains("typ"));
assertTrue(h.getIncludedParameters().contains("cty"));
assertTrue(h.getIncludedParameters().contains("xCustom"));
assertEquals(4, h.getIncludedParameters().size());
| // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
// Path: src/test/java/com/nimbusds/jose/PlainHeaderTest.java
import java.text.ParseException;
import junit.framework.TestCase;
import com.nimbusds.jose.util.Base64URL;
package com.nimbusds.jose;
/**
* Tests plain header parsing and serialisation.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-01)
*/
public class PlainHeaderTest extends TestCase {
public void testSerializeAndParse() {
PlainHeader h = new PlainHeader();
assertEquals(Algorithm.NONE, h.getAlgorithm());
assertNull(h.getType());
assertNull(h.getContentType());
h.setType(new JOSEObjectType("JWT"));
h.setContentType("application/jwt");
h.setCustomParameter("xCustom", "abc");
assertTrue(h.getIncludedParameters().contains("alg"));
assertTrue(h.getIncludedParameters().contains("typ"));
assertTrue(h.getIncludedParameters().contains("cty"));
assertTrue(h.getIncludedParameters().contains("xCustom"));
assertEquals(4, h.getIncludedParameters().size());
| Base64URL b64url = h.toBase64URL(); |
gesellix/Nimbus-JOSE-JWT | src/test/java/com/nimbusds/jose/crypto/DefaultJWSHeaderFilterTest.java | // Path: src/main/java/com/nimbusds/jose/JWSAlgorithm.java
// @Immutable
// public final class JWSAlgorithm extends Algorithm {
//
//
// /**
// * HMAC using SHA-256 hash algorithm (required).
// */
// public static final JWSAlgorithm HS256 = new JWSAlgorithm("HS256", Requirement.REQUIRED);
//
//
// /**
// * HMAC using SHA-384 hash algorithm (optional).
// */
// public static final JWSAlgorithm HS384 = new JWSAlgorithm("HS384", Requirement.OPTIONAL);
//
//
// /**
// * HMAC using SHA-512 hash algorithm (optional).
// */
// public static final JWSAlgorithm HS512 = new JWSAlgorithm("HS512", Requirement.OPTIONAL);
//
//
// /**
// * RSA using SHA-256 hash algorithm (recommended).
// */
// public static final JWSAlgorithm RS256 = new JWSAlgorithm("RS256", Requirement.RECOMMENDED);
//
//
// /**
// * RSA using SHA-384 hash algorithm (optional).
// */
// public static final JWSAlgorithm RS384 = new JWSAlgorithm("RS384", Requirement.OPTIONAL);
//
//
// /**
// * RSA using SHA-512 hash algorithm (optional).
// */
// public static final JWSAlgorithm RS512 = new JWSAlgorithm("RS512", Requirement.OPTIONAL);
//
//
// /**
// * ECDSA using P-256 curve and SHA-256 hash algorithm (recommended).
// */
// public static final JWSAlgorithm ES256 = new JWSAlgorithm("ES256", Requirement.RECOMMENDED);
//
//
// /**
// * ECDSA using P-384 curve and SHA-384 hash algorithm (optional).
// */
// public static final JWSAlgorithm ES384 = new JWSAlgorithm("ES384", Requirement.OPTIONAL);
//
//
// /**
// * ECDSA using P-521 curve and SHA-512 hash algorithm (optional).
// */
// public static final JWSAlgorithm ES512 = new JWSAlgorithm("ES512", Requirement.OPTIONAL);
//
//
// /**
// * Creates a new JSON Web Signature (JWS) algorithm name.
// *
// * @param name The algorithm name. Must not be {@code null}.
// * @param req The implementation requirement, {@code null} if not
// * known.
// */
// public JWSAlgorithm(final String name, final Requirement req) {
//
// super(name, req);
// }
//
//
// /**
// * Creates a new JSON Web Signature (JWS) algorithm name.
// *
// * @param name The algorithm name. Must not be {@code null}.
// */
// public JWSAlgorithm(final String name) {
//
// super(name, null);
// }
//
//
// @Override
// public boolean equals(final Object object) {
//
// return object instanceof JWSAlgorithm && this.toString().equals(object.toString());
// }
//
//
// /**
// * Parses a JWS algorithm from the specified string.
// *
// * @param s The string to parse. Must not be {@code null}.
// *
// * @return The JWS algorithm (matching standard algorithm constant, else
// * a newly created algorithm).
// */
// public static JWSAlgorithm parse(final String s) {
//
// if (s == HS256.getName())
// return HS256;
//
// else if (s == HS384.getName())
// return HS384;
//
// else if (s == HS512.getName())
// return HS512;
//
// else if (s == RS256.getName())
// return RS256;
//
// else if (s == RS384.getName())
// return RS384;
//
// else if (s == RS512.getName())
// return RS512;
//
// else if (s == ES256.getName())
// return ES256;
//
// else if (s == ES384.getName())
// return ES384;
//
// else if (s == ES512.getName())
// return ES512;
//
// else
// return new JWSAlgorithm(s);
// }
// }
//
// Path: src/main/java/com/nimbusds/jose/JWSHeaderFilter.java
// public interface JWSHeaderFilter extends HeaderFilter {
//
//
// /**
// * Gets the names of the accepted JWS algorithms. These correspond to
// * the {@code alg} JWS header parameter.
// *
// * @return The accepted JWS algorithms as a read-only set, empty set if
// * none.
// */
// public Set<JWSAlgorithm> getAcceptedAlgorithms();
//
//
// /**
// * Sets the names of the accepted JWS algorithms. These correspond to
// * the {@code alg} JWS header parameter.
// *
// * @param acceptedAlgs The accepted JWS algorithms. Must be a subset of
// * the supported algorithms and not {@code null}.
// */
// public void setAcceptedAlgorithms(Set<JWSAlgorithm> acceptedAlgs);
// }
| import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeaderFilter; | package com.nimbusds.jose.crypto;
/**
* Tests the default JWS header filter implementation.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-05)
*/
public class DefaultJWSHeaderFilterTest extends TestCase {
public void testRun() {
| // Path: src/main/java/com/nimbusds/jose/JWSAlgorithm.java
// @Immutable
// public final class JWSAlgorithm extends Algorithm {
//
//
// /**
// * HMAC using SHA-256 hash algorithm (required).
// */
// public static final JWSAlgorithm HS256 = new JWSAlgorithm("HS256", Requirement.REQUIRED);
//
//
// /**
// * HMAC using SHA-384 hash algorithm (optional).
// */
// public static final JWSAlgorithm HS384 = new JWSAlgorithm("HS384", Requirement.OPTIONAL);
//
//
// /**
// * HMAC using SHA-512 hash algorithm (optional).
// */
// public static final JWSAlgorithm HS512 = new JWSAlgorithm("HS512", Requirement.OPTIONAL);
//
//
// /**
// * RSA using SHA-256 hash algorithm (recommended).
// */
// public static final JWSAlgorithm RS256 = new JWSAlgorithm("RS256", Requirement.RECOMMENDED);
//
//
// /**
// * RSA using SHA-384 hash algorithm (optional).
// */
// public static final JWSAlgorithm RS384 = new JWSAlgorithm("RS384", Requirement.OPTIONAL);
//
//
// /**
// * RSA using SHA-512 hash algorithm (optional).
// */
// public static final JWSAlgorithm RS512 = new JWSAlgorithm("RS512", Requirement.OPTIONAL);
//
//
// /**
// * ECDSA using P-256 curve and SHA-256 hash algorithm (recommended).
// */
// public static final JWSAlgorithm ES256 = new JWSAlgorithm("ES256", Requirement.RECOMMENDED);
//
//
// /**
// * ECDSA using P-384 curve and SHA-384 hash algorithm (optional).
// */
// public static final JWSAlgorithm ES384 = new JWSAlgorithm("ES384", Requirement.OPTIONAL);
//
//
// /**
// * ECDSA using P-521 curve and SHA-512 hash algorithm (optional).
// */
// public static final JWSAlgorithm ES512 = new JWSAlgorithm("ES512", Requirement.OPTIONAL);
//
//
// /**
// * Creates a new JSON Web Signature (JWS) algorithm name.
// *
// * @param name The algorithm name. Must not be {@code null}.
// * @param req The implementation requirement, {@code null} if not
// * known.
// */
// public JWSAlgorithm(final String name, final Requirement req) {
//
// super(name, req);
// }
//
//
// /**
// * Creates a new JSON Web Signature (JWS) algorithm name.
// *
// * @param name The algorithm name. Must not be {@code null}.
// */
// public JWSAlgorithm(final String name) {
//
// super(name, null);
// }
//
//
// @Override
// public boolean equals(final Object object) {
//
// return object instanceof JWSAlgorithm && this.toString().equals(object.toString());
// }
//
//
// /**
// * Parses a JWS algorithm from the specified string.
// *
// * @param s The string to parse. Must not be {@code null}.
// *
// * @return The JWS algorithm (matching standard algorithm constant, else
// * a newly created algorithm).
// */
// public static JWSAlgorithm parse(final String s) {
//
// if (s == HS256.getName())
// return HS256;
//
// else if (s == HS384.getName())
// return HS384;
//
// else if (s == HS512.getName())
// return HS512;
//
// else if (s == RS256.getName())
// return RS256;
//
// else if (s == RS384.getName())
// return RS384;
//
// else if (s == RS512.getName())
// return RS512;
//
// else if (s == ES256.getName())
// return ES256;
//
// else if (s == ES384.getName())
// return ES384;
//
// else if (s == ES512.getName())
// return ES512;
//
// else
// return new JWSAlgorithm(s);
// }
// }
//
// Path: src/main/java/com/nimbusds/jose/JWSHeaderFilter.java
// public interface JWSHeaderFilter extends HeaderFilter {
//
//
// /**
// * Gets the names of the accepted JWS algorithms. These correspond to
// * the {@code alg} JWS header parameter.
// *
// * @return The accepted JWS algorithms as a read-only set, empty set if
// * none.
// */
// public Set<JWSAlgorithm> getAcceptedAlgorithms();
//
//
// /**
// * Sets the names of the accepted JWS algorithms. These correspond to
// * the {@code alg} JWS header parameter.
// *
// * @param acceptedAlgs The accepted JWS algorithms. Must be a subset of
// * the supported algorithms and not {@code null}.
// */
// public void setAcceptedAlgorithms(Set<JWSAlgorithm> acceptedAlgs);
// }
// Path: src/test/java/com/nimbusds/jose/crypto/DefaultJWSHeaderFilterTest.java
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeaderFilter;
package com.nimbusds.jose.crypto;
/**
* Tests the default JWS header filter implementation.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-05)
*/
public class DefaultJWSHeaderFilterTest extends TestCase {
public void testRun() {
| Set<JWSAlgorithm> supportedAlgs = new HashSet<JWSAlgorithm>(); |
gesellix/Nimbus-JOSE-JWT | src/test/java/com/nimbusds/jose/JOSEObjectTest.java | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
| import java.text.ParseException;
import junit.framework.TestCase;
import com.nimbusds.jose.util.Base64URL; | package com.nimbusds.jose;
/**
* Tests JOSE object methods.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-16)
*/
public class JOSEObjectTest extends TestCase {
public void testSplitThreeParts() {
// Implies JWS
String s = "abc.def.ghi";
| // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
// Path: src/test/java/com/nimbusds/jose/JOSEObjectTest.java
import java.text.ParseException;
import junit.framework.TestCase;
import com.nimbusds.jose.util.Base64URL;
package com.nimbusds.jose;
/**
* Tests JOSE object methods.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-16)
*/
public class JOSEObjectTest extends TestCase {
public void testSplitThreeParts() {
// Implies JWS
String s = "abc.def.ghi";
| Base64URL[] parts = null; |
gesellix/Nimbus-JOSE-JWT | src/main/java/com/nimbusds/jose/PlainObject.java | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
| import java.text.ParseException;
import net.jcip.annotations.ThreadSafe;
import com.nimbusds.jose.util.Base64URL; | package com.nimbusds.jose;
/**
* Plaintext (unsecured) JOSE object. This class is thread-safe.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-23)
*/
@ThreadSafe
public class PlainObject extends JOSEObject {
/**
* The header.
*/
private final PlainHeader header;
/**
* Creates a new plaintext JOSE object with a default {@link PlainHeader}
* and the specified payload.
*
* @param payload The payload. Must not be {@code null}.
*/
public PlainObject(final Payload payload) {
if (payload == null)
throw new IllegalArgumentException("The payload must not be null");
setPayload(payload);
header = new PlainHeader();
}
/**
* Creates a new plaintext JOSE object with the specified header and
* payload.
*
* @param header The plaintext header. Must not be {@code null}.
* @param payload The payload. Must not be {@code null}.
*/
public PlainObject(final PlainHeader header, final Payload payload) {
if (header == null)
throw new IllegalArgumentException("The plain header must not be null");
this.header = header;
if (payload == null)
throw new IllegalArgumentException("The payload must not be null");
setPayload(payload);
}
/**
* Creates a new plaintext JOSE object with the specified Base64URL-encoded
* parts.
*
* @param firstPart The first part, corresponding to the plaintext header.
* Must not be {@code null}.
* @param secondPart The second part, corresponding to the payload. Must
* not be {@code null}.
*
* @throws ParseException If parsing of the serialised parts failed.
*/ | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
// Path: src/main/java/com/nimbusds/jose/PlainObject.java
import java.text.ParseException;
import net.jcip.annotations.ThreadSafe;
import com.nimbusds.jose.util.Base64URL;
package com.nimbusds.jose;
/**
* Plaintext (unsecured) JOSE object. This class is thread-safe.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-23)
*/
@ThreadSafe
public class PlainObject extends JOSEObject {
/**
* The header.
*/
private final PlainHeader header;
/**
* Creates a new plaintext JOSE object with a default {@link PlainHeader}
* and the specified payload.
*
* @param payload The payload. Must not be {@code null}.
*/
public PlainObject(final Payload payload) {
if (payload == null)
throw new IllegalArgumentException("The payload must not be null");
setPayload(payload);
header = new PlainHeader();
}
/**
* Creates a new plaintext JOSE object with the specified header and
* payload.
*
* @param header The plaintext header. Must not be {@code null}.
* @param payload The payload. Must not be {@code null}.
*/
public PlainObject(final PlainHeader header, final Payload payload) {
if (header == null)
throw new IllegalArgumentException("The plain header must not be null");
this.header = header;
if (payload == null)
throw new IllegalArgumentException("The payload must not be null");
setPayload(payload);
}
/**
* Creates a new plaintext JOSE object with the specified Base64URL-encoded
* parts.
*
* @param firstPart The first part, corresponding to the plaintext header.
* Must not be {@code null}.
* @param secondPart The second part, corresponding to the payload. Must
* not be {@code null}.
*
* @throws ParseException If parsing of the serialised parts failed.
*/ | public PlainObject(final Base64URL firstPart, final Base64URL secondPart) |
gesellix/Nimbus-JOSE-JWT | src/test/java/com/nimbusds/jose/JWKSetTest.java | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
| import com.nimbusds.jose.util.Base64URL;
import java.text.ParseException;
import java.util.List;
import junit.framework.TestCase; | assertEquals("4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", ecKey.getY().toString());
key = keyList.get(1);
assertNotNull(key);
assertTrue(key instanceof RSAKey);
assertEquals("2011-04-29", key.getKeyID());
assertNull(key.getKeyUse());
RSAKey rsaKey = (RSAKey)key;
assertEquals("0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx" +
"4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMs" +
"tn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2" +
"QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbI" +
"SD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqb" +
"w0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
rsaKey.getModulus().toString());
assertEquals("AQAB", rsaKey.getExponent().toString());
}
public void testSerializeAndParse() {
ECKey ecKey = new ECKey(ECKey.Curve.P_256, | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
// Path: src/test/java/com/nimbusds/jose/JWKSetTest.java
import com.nimbusds.jose.util.Base64URL;
import java.text.ParseException;
import java.util.List;
import junit.framework.TestCase;
assertEquals("4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", ecKey.getY().toString());
key = keyList.get(1);
assertNotNull(key);
assertTrue(key instanceof RSAKey);
assertEquals("2011-04-29", key.getKeyID());
assertNull(key.getKeyUse());
RSAKey rsaKey = (RSAKey)key;
assertEquals("0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx" +
"4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMs" +
"tn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2" +
"QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbI" +
"SD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqb" +
"w0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
rsaKey.getModulus().toString());
assertEquals("AQAB", rsaKey.getExponent().toString());
}
public void testSerializeAndParse() {
ECKey ecKey = new ECKey(ECKey.Curve.P_256, | new Base64URL("abc"), |
gesellix/Nimbus-JOSE-JWT | src/main/java/com/nimbusds/jose/JWEObject.java | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
| import java.text.ParseException;
import net.jcip.annotations.ThreadSafe;
import com.nimbusds.jose.util.Base64URL; | package com.nimbusds.jose;
/**
* JSON Web Encryption (JWE) object. This class is thread-safe.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-23)
*/
@ThreadSafe
public class JWEObject extends JOSEObject {
/**
* Enumeration of the states of a JSON Web Encryption (JWE) object.
*/
public static enum State {
/**
* The JWE object is created but not encrypted yet.
*/
UNENCRYPTED,
/**
* The JWE object is encrypted.
*/
ENCRYPTED,
/**
* The JWE object is decrypted.
*/
DECRYPTED;
}
/**
* The header.
*/
private final JWEHeader header;
/**
* The encrypted key, {@code null} if not computed or applicable.
*/ | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
// Path: src/main/java/com/nimbusds/jose/JWEObject.java
import java.text.ParseException;
import net.jcip.annotations.ThreadSafe;
import com.nimbusds.jose.util.Base64URL;
package com.nimbusds.jose;
/**
* JSON Web Encryption (JWE) object. This class is thread-safe.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-23)
*/
@ThreadSafe
public class JWEObject extends JOSEObject {
/**
* Enumeration of the states of a JSON Web Encryption (JWE) object.
*/
public static enum State {
/**
* The JWE object is created but not encrypted yet.
*/
UNENCRYPTED,
/**
* The JWE object is encrypted.
*/
ENCRYPTED,
/**
* The JWE object is decrypted.
*/
DECRYPTED;
}
/**
* The header.
*/
private final JWEHeader header;
/**
* The encrypted key, {@code null} if not computed or applicable.
*/ | private Base64URL encryptedKey; |
gesellix/Nimbus-JOSE-JWT | src/main/java/com/nimbusds/jose/JWSObject.java | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
| import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Set;
import net.jcip.annotations.ThreadSafe;
import com.nimbusds.jose.util.Base64URL; | package com.nimbusds.jose;
/**
* JSON Web Signature (JWS) object. This class is thread-safe.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-23)
*/
@ThreadSafe
public class JWSObject extends JOSEObject {
/**
* Enumeration of the states of a JSON Web Signature (JWS) object.
*/
public static enum State {
/**
* The JWS object is created but not signed yet.
*/
UNSIGNED,
/**
* The JWS object is signed but its signature is not verified.
*/
SIGNED,
/**
* The JWS object is signed and its signature was successfully verified.
*/
VERIFIED;
}
/**
* The header.
*/
private final JWSHeader header;
/**
* The signable content of this JWS object.
*
* <p>Format:
*
* <pre>
* [header-base64url].[payload-base64url]
* </pre>
*/
private byte[] signableContent;
/**
* The signature, {@code null} if not signed.
*/ | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
// Path: src/main/java/com/nimbusds/jose/JWSObject.java
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Set;
import net.jcip.annotations.ThreadSafe;
import com.nimbusds.jose.util.Base64URL;
package com.nimbusds.jose;
/**
* JSON Web Signature (JWS) object. This class is thread-safe.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-23)
*/
@ThreadSafe
public class JWSObject extends JOSEObject {
/**
* Enumeration of the states of a JSON Web Signature (JWS) object.
*/
public static enum State {
/**
* The JWS object is created but not signed yet.
*/
UNSIGNED,
/**
* The JWS object is signed but its signature is not verified.
*/
SIGNED,
/**
* The JWS object is signed and its signature was successfully verified.
*/
VERIFIED;
}
/**
* The header.
*/
private final JWSHeader header;
/**
* The signable content of this JWS object.
*
* <p>Format:
*
* <pre>
* [header-base64url].[payload-base64url]
* </pre>
*/
private byte[] signableContent;
/**
* The signature, {@code null} if not signed.
*/ | private Base64URL signature; |
gesellix/Nimbus-JOSE-JWT | src/main/java/com/nimbusds/jose/JWECryptoParts.java | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
| import net.jcip.annotations.Immutable;
import com.nimbusds.jose.util.Base64URL; | package com.nimbusds.jose;
/**
* The cryptographic parts of a JSON Web Encryption (JWE) object. This class is
* an immutable simple wrapper for returning the cipher text, initialisation
* vector (IV), encrypted key and integrity value from {@link JWEEncrypter}
* implementations.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-23)
*/
@Immutable
public final class JWECryptoParts {
/**
* The encrypted key (optional).
*/ | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
// Path: src/main/java/com/nimbusds/jose/JWECryptoParts.java
import net.jcip.annotations.Immutable;
import com.nimbusds.jose.util.Base64URL;
package com.nimbusds.jose;
/**
* The cryptographic parts of a JSON Web Encryption (JWE) object. This class is
* an immutable simple wrapper for returning the cipher text, initialisation
* vector (IV), encrypted key and integrity value from {@link JWEEncrypter}
* implementations.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-23)
*/
@Immutable
public final class JWECryptoParts {
/**
* The encrypted key (optional).
*/ | private final Base64URL encryptedKey; |
gesellix/Nimbus-JOSE-JWT | src/main/java/com/nimbusds/jose/crypto/DefaultJWSHeaderFilter.java | // Path: src/main/java/com/nimbusds/jose/JWSAlgorithm.java
// @Immutable
// public final class JWSAlgorithm extends Algorithm {
//
//
// /**
// * HMAC using SHA-256 hash algorithm (required).
// */
// public static final JWSAlgorithm HS256 = new JWSAlgorithm("HS256", Requirement.REQUIRED);
//
//
// /**
// * HMAC using SHA-384 hash algorithm (optional).
// */
// public static final JWSAlgorithm HS384 = new JWSAlgorithm("HS384", Requirement.OPTIONAL);
//
//
// /**
// * HMAC using SHA-512 hash algorithm (optional).
// */
// public static final JWSAlgorithm HS512 = new JWSAlgorithm("HS512", Requirement.OPTIONAL);
//
//
// /**
// * RSA using SHA-256 hash algorithm (recommended).
// */
// public static final JWSAlgorithm RS256 = new JWSAlgorithm("RS256", Requirement.RECOMMENDED);
//
//
// /**
// * RSA using SHA-384 hash algorithm (optional).
// */
// public static final JWSAlgorithm RS384 = new JWSAlgorithm("RS384", Requirement.OPTIONAL);
//
//
// /**
// * RSA using SHA-512 hash algorithm (optional).
// */
// public static final JWSAlgorithm RS512 = new JWSAlgorithm("RS512", Requirement.OPTIONAL);
//
//
// /**
// * ECDSA using P-256 curve and SHA-256 hash algorithm (recommended).
// */
// public static final JWSAlgorithm ES256 = new JWSAlgorithm("ES256", Requirement.RECOMMENDED);
//
//
// /**
// * ECDSA using P-384 curve and SHA-384 hash algorithm (optional).
// */
// public static final JWSAlgorithm ES384 = new JWSAlgorithm("ES384", Requirement.OPTIONAL);
//
//
// /**
// * ECDSA using P-521 curve and SHA-512 hash algorithm (optional).
// */
// public static final JWSAlgorithm ES512 = new JWSAlgorithm("ES512", Requirement.OPTIONAL);
//
//
// /**
// * Creates a new JSON Web Signature (JWS) algorithm name.
// *
// * @param name The algorithm name. Must not be {@code null}.
// * @param req The implementation requirement, {@code null} if not
// * known.
// */
// public JWSAlgorithm(final String name, final Requirement req) {
//
// super(name, req);
// }
//
//
// /**
// * Creates a new JSON Web Signature (JWS) algorithm name.
// *
// * @param name The algorithm name. Must not be {@code null}.
// */
// public JWSAlgorithm(final String name) {
//
// super(name, null);
// }
//
//
// @Override
// public boolean equals(final Object object) {
//
// return object instanceof JWSAlgorithm && this.toString().equals(object.toString());
// }
//
//
// /**
// * Parses a JWS algorithm from the specified string.
// *
// * @param s The string to parse. Must not be {@code null}.
// *
// * @return The JWS algorithm (matching standard algorithm constant, else
// * a newly created algorithm).
// */
// public static JWSAlgorithm parse(final String s) {
//
// if (s == HS256.getName())
// return HS256;
//
// else if (s == HS384.getName())
// return HS384;
//
// else if (s == HS512.getName())
// return HS512;
//
// else if (s == RS256.getName())
// return RS256;
//
// else if (s == RS384.getName())
// return RS384;
//
// else if (s == RS512.getName())
// return RS512;
//
// else if (s == ES256.getName())
// return ES256;
//
// else if (s == ES384.getName())
// return ES384;
//
// else if (s == ES512.getName())
// return ES512;
//
// else
// return new JWSAlgorithm(s);
// }
// }
//
// Path: src/main/java/com/nimbusds/jose/JWSHeaderFilter.java
// public interface JWSHeaderFilter extends HeaderFilter {
//
//
// /**
// * Gets the names of the accepted JWS algorithms. These correspond to
// * the {@code alg} JWS header parameter.
// *
// * @return The accepted JWS algorithms as a read-only set, empty set if
// * none.
// */
// public Set<JWSAlgorithm> getAcceptedAlgorithms();
//
//
// /**
// * Sets the names of the accepted JWS algorithms. These correspond to
// * the {@code alg} JWS header parameter.
// *
// * @param acceptedAlgs The accepted JWS algorithms. Must be a subset of
// * the supported algorithms and not {@code null}.
// */
// public void setAcceptedAlgorithms(Set<JWSAlgorithm> acceptedAlgs);
// }
| import java.util.Collections;
import java.util.Set;
import net.jcip.annotations.ThreadSafe;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeaderFilter; | package com.nimbusds.jose.crypto;
/**
* JSON Web Signature (JWS) header filter implementation. This class is
* thread-safe.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-23)
*/
@ThreadSafe
class DefaultJWSHeaderFilter implements JWSHeaderFilter {
/**
* The supported algorithms. Used to bound the subset of the accepted
* ones.
*/ | // Path: src/main/java/com/nimbusds/jose/JWSAlgorithm.java
// @Immutable
// public final class JWSAlgorithm extends Algorithm {
//
//
// /**
// * HMAC using SHA-256 hash algorithm (required).
// */
// public static final JWSAlgorithm HS256 = new JWSAlgorithm("HS256", Requirement.REQUIRED);
//
//
// /**
// * HMAC using SHA-384 hash algorithm (optional).
// */
// public static final JWSAlgorithm HS384 = new JWSAlgorithm("HS384", Requirement.OPTIONAL);
//
//
// /**
// * HMAC using SHA-512 hash algorithm (optional).
// */
// public static final JWSAlgorithm HS512 = new JWSAlgorithm("HS512", Requirement.OPTIONAL);
//
//
// /**
// * RSA using SHA-256 hash algorithm (recommended).
// */
// public static final JWSAlgorithm RS256 = new JWSAlgorithm("RS256", Requirement.RECOMMENDED);
//
//
// /**
// * RSA using SHA-384 hash algorithm (optional).
// */
// public static final JWSAlgorithm RS384 = new JWSAlgorithm("RS384", Requirement.OPTIONAL);
//
//
// /**
// * RSA using SHA-512 hash algorithm (optional).
// */
// public static final JWSAlgorithm RS512 = new JWSAlgorithm("RS512", Requirement.OPTIONAL);
//
//
// /**
// * ECDSA using P-256 curve and SHA-256 hash algorithm (recommended).
// */
// public static final JWSAlgorithm ES256 = new JWSAlgorithm("ES256", Requirement.RECOMMENDED);
//
//
// /**
// * ECDSA using P-384 curve and SHA-384 hash algorithm (optional).
// */
// public static final JWSAlgorithm ES384 = new JWSAlgorithm("ES384", Requirement.OPTIONAL);
//
//
// /**
// * ECDSA using P-521 curve and SHA-512 hash algorithm (optional).
// */
// public static final JWSAlgorithm ES512 = new JWSAlgorithm("ES512", Requirement.OPTIONAL);
//
//
// /**
// * Creates a new JSON Web Signature (JWS) algorithm name.
// *
// * @param name The algorithm name. Must not be {@code null}.
// * @param req The implementation requirement, {@code null} if not
// * known.
// */
// public JWSAlgorithm(final String name, final Requirement req) {
//
// super(name, req);
// }
//
//
// /**
// * Creates a new JSON Web Signature (JWS) algorithm name.
// *
// * @param name The algorithm name. Must not be {@code null}.
// */
// public JWSAlgorithm(final String name) {
//
// super(name, null);
// }
//
//
// @Override
// public boolean equals(final Object object) {
//
// return object instanceof JWSAlgorithm && this.toString().equals(object.toString());
// }
//
//
// /**
// * Parses a JWS algorithm from the specified string.
// *
// * @param s The string to parse. Must not be {@code null}.
// *
// * @return The JWS algorithm (matching standard algorithm constant, else
// * a newly created algorithm).
// */
// public static JWSAlgorithm parse(final String s) {
//
// if (s == HS256.getName())
// return HS256;
//
// else if (s == HS384.getName())
// return HS384;
//
// else if (s == HS512.getName())
// return HS512;
//
// else if (s == RS256.getName())
// return RS256;
//
// else if (s == RS384.getName())
// return RS384;
//
// else if (s == RS512.getName())
// return RS512;
//
// else if (s == ES256.getName())
// return ES256;
//
// else if (s == ES384.getName())
// return ES384;
//
// else if (s == ES512.getName())
// return ES512;
//
// else
// return new JWSAlgorithm(s);
// }
// }
//
// Path: src/main/java/com/nimbusds/jose/JWSHeaderFilter.java
// public interface JWSHeaderFilter extends HeaderFilter {
//
//
// /**
// * Gets the names of the accepted JWS algorithms. These correspond to
// * the {@code alg} JWS header parameter.
// *
// * @return The accepted JWS algorithms as a read-only set, empty set if
// * none.
// */
// public Set<JWSAlgorithm> getAcceptedAlgorithms();
//
//
// /**
// * Sets the names of the accepted JWS algorithms. These correspond to
// * the {@code alg} JWS header parameter.
// *
// * @param acceptedAlgs The accepted JWS algorithms. Must be a subset of
// * the supported algorithms and not {@code null}.
// */
// public void setAcceptedAlgorithms(Set<JWSAlgorithm> acceptedAlgs);
// }
// Path: src/main/java/com/nimbusds/jose/crypto/DefaultJWSHeaderFilter.java
import java.util.Collections;
import java.util.Set;
import net.jcip.annotations.ThreadSafe;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeaderFilter;
package com.nimbusds.jose.crypto;
/**
* JSON Web Signature (JWS) header filter implementation. This class is
* thread-safe.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-23)
*/
@ThreadSafe
class DefaultJWSHeaderFilter implements JWSHeaderFilter {
/**
* The supported algorithms. Used to bound the subset of the accepted
* ones.
*/ | private final Set<JWSAlgorithm> algs; |
gesellix/Nimbus-JOSE-JWT | src/main/java/com/nimbusds/jose/JWSVerifier.java | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
| import com.nimbusds.jose.util.Base64URL; | package com.nimbusds.jose;
/**
* Interface for verifying JSON Web Signature (JWS) objects.
*
* <p>Callers can query the verifier to determine its algorithm capabilities as
* well as the JWS algorithms and header parameters that are accepted for
* processing.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-23)
*/
public interface JWSVerifier extends JWSAlgorithmProvider {
/**
* Gets the JWS header filter associated with the verifier. Specifies the
* names of those {@link #supportedAlgorithms supported JWS algorithms} and
* header parameters that the verifier is configured to accept.
*
* <p>Attempting to {@link #verify verify} a JWS object signature with an
* algorithm or header parameter that is not accepted must result in a
* {@link JOSEException}.
*
* @return The JWS header filter.
*/
public JWSHeaderFilter getJWSHeaderFilter();
/**
* Verifies the specified {@link JWSObject#getSignature signature} of a
* {@link JWSObject JWS object}.
*
* @param header The JSON Web Signature (JWS) header. Must
* specify an accepted JWS algorithm, must contain
* only accepted header parameters, and must not be
* {@code null}.
* @param signedContent The signed content. Must not be {@code null}.
* @param signature The signature part of the JWS object. Must not
* be {@code null}.
*
* @return {@code true} if the signature was successfully verified, else
* {@code false}.
*
* @throws JOSEException If the JWS algorithm is not accepted, if a header
* parameter is not accepted, or if signature
* verification failed for some other reason.
*/
public boolean verify(final ReadOnlyJWSHeader header,
final byte[] signedContent, | // Path: src/main/java/com/nimbusds/jose/util/Base64URL.java
// @Immutable
// public class Base64URL implements JSONAware {
//
//
// /**
// * UTF-8 is the required charset for all JWTs.
// */
// private static final String CHARSET = "utf-8";
//
//
// /**
// * The Base64URL value.
// */
// private final String value;
//
//
// /**
// * Creates a new Base64URL-encoded object.
// *
// * @param base64URL The Base64URL-encoded object value. The value is not
// * validated for having characters from a Base64URL
// * alphabet. Must not be {@code null}.
// */
// public Base64URL(final String base64URL) {
//
// if (base64URL == null)
// throw new IllegalArgumentException("The Base64URL value must not be null");
//
// value = base64URL;
// }
//
//
// /**
// * Decodes this Base64URL object to a byte array.
// *
// * @return The resulting byte array.
// */
// public byte[] decode() {
//
// return Base64.decodeBase64(value);
// }
//
//
// /**
// * Decodes this Base64URL object to a string.
// *
// * @return The resulting string, in the UTF-8 character set.
// */
// public String decodeToString() {
//
// try {
// return new String(decode(), CHARSET);
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return "";
// }
// }
//
//
// /**
// * Returns a JSON string representation of this object.
// *
// * @return The JSON string representation of this object.
// */
// public String toJSONString() {
//
// return "\"" + JSONValue.escape(value) + "\"";
// }
//
//
// /**
// * Returns a Base64URL string representation of this object.
// *
// * @return The Base64URL string representation.
// */
// public String toString() {
//
// return value;
// }
//
//
// /**
// * Overrides {@code Object.hashCode()}.
// *
// * @return The object hash code.
// */
// public int hashCode() {
//
// return value.hashCode();
// }
//
//
// /**
// * Overrides {@code Object.equals()}.
// *
// * @param object The object to compare to.
// *
// * @return {@code true} if the objects have the same value, otherwise
// * {@code false}.
// */
// public boolean equals(final Object object) {
//
// return object instanceof Base64URL && this.toString().equals(object.toString());
// }
//
//
// /**
// * Base64URL-encode the specified string.
// *
// * @param text The string to encode. Must be in the UTF-8 character set
// * and not {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final String text) {
//
// try {
// return encode(text.getBytes(CHARSET));
//
// } catch (UnsupportedEncodingException e) {
//
// // UTF-8 should always be supported
// return null;
// }
// }
//
//
// /**
// * Base64URL-encode the specified byte array.
// *
// * @param bytes The byte array to encode. Must not be {@code null}.
// *
// * @return The resulting Base64URL object.
// */
// public static Base64URL encode(final byte[] bytes) {
//
// return new Base64URL(Base64.encodeBase64URLSafeString(bytes));
// }
// }
// Path: src/main/java/com/nimbusds/jose/JWSVerifier.java
import com.nimbusds.jose.util.Base64URL;
package com.nimbusds.jose;
/**
* Interface for verifying JSON Web Signature (JWS) objects.
*
* <p>Callers can query the verifier to determine its algorithm capabilities as
* well as the JWS algorithms and header parameters that are accepted for
* processing.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-23)
*/
public interface JWSVerifier extends JWSAlgorithmProvider {
/**
* Gets the JWS header filter associated with the verifier. Specifies the
* names of those {@link #supportedAlgorithms supported JWS algorithms} and
* header parameters that the verifier is configured to accept.
*
* <p>Attempting to {@link #verify verify} a JWS object signature with an
* algorithm or header parameter that is not accepted must result in a
* {@link JOSEException}.
*
* @return The JWS header filter.
*/
public JWSHeaderFilter getJWSHeaderFilter();
/**
* Verifies the specified {@link JWSObject#getSignature signature} of a
* {@link JWSObject JWS object}.
*
* @param header The JSON Web Signature (JWS) header. Must
* specify an accepted JWS algorithm, must contain
* only accepted header parameters, and must not be
* {@code null}.
* @param signedContent The signed content. Must not be {@code null}.
* @param signature The signature part of the JWS object. Must not
* be {@code null}.
*
* @return {@code true} if the signature was successfully verified, else
* {@code false}.
*
* @throws JOSEException If the JWS algorithm is not accepted, if a header
* parameter is not accepted, or if signature
* verification failed for some other reason.
*/
public boolean verify(final ReadOnlyJWSHeader header,
final byte[] signedContent, | final Base64URL signature) |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/GoOfflineMojo.java | // Path: src/main/java/org/simplify4u/plugins/pgp/SignatureCheckResult.java
// @Value
// @Builder
// public class SignatureCheckResult {
//
// @NonNull
// ArtifactInfo artifact;
//
// KeyInfo key;
// /**
// * Last address for key search.
// */
// String keyShowUrl;
//
// SignatureInfo signature;
//
// @NonNull
// SignatureStatus status;
//
// @JsonIgnore
// Throwable errorCause;
//
// public String getErrorMessage() {
// return Optional.ofNullable(errorCause).map(Throwable::getMessage).orElse(null);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureStatus.java
// public enum SignatureStatus {
// ARTIFACT_NOT_RESOLVED,
// SIGNATURE_NOT_RESOLVED,
// KEY_NOT_FOUND,
// ERROR,
// SIGNATURE_ERROR,
// SIGNATURE_VALID,
// SIGNATURE_INVALID,
// RESOLVED
// }
| import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.simplify4u.plugins.pgp.SignatureCheckResult;
import org.simplify4u.plugins.pgp.SignatureStatus; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins;
/**
* Resolve OpenPGP signature and keys of all project and plugins dependencies.
* <p>
* Verification of signature in this goal will not occurs. In case of any problem only warn will be reported.
*
* @author Slawomir Jaranowski
* @since 1.13.0
*/
@Slf4j
@Mojo(name = GoOfflineMojo.MOJO_NAME, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true)
public class GoOfflineMojo extends AbstractVerifyMojo<Void> {
public static final String MOJO_NAME = "go-offline";
@Override
protected String getMojoName() {
return MOJO_NAME;
}
@Override
protected void shouldProcess(Set<Artifact> artifacts, Runnable runnable) {
runnable.run();
}
@Override
protected Void processArtifactSignature(Artifact artifact, Artifact ascArtifact) { | // Path: src/main/java/org/simplify4u/plugins/pgp/SignatureCheckResult.java
// @Value
// @Builder
// public class SignatureCheckResult {
//
// @NonNull
// ArtifactInfo artifact;
//
// KeyInfo key;
// /**
// * Last address for key search.
// */
// String keyShowUrl;
//
// SignatureInfo signature;
//
// @NonNull
// SignatureStatus status;
//
// @JsonIgnore
// Throwable errorCause;
//
// public String getErrorMessage() {
// return Optional.ofNullable(errorCause).map(Throwable::getMessage).orElse(null);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureStatus.java
// public enum SignatureStatus {
// ARTIFACT_NOT_RESOLVED,
// SIGNATURE_NOT_RESOLVED,
// KEY_NOT_FOUND,
// ERROR,
// SIGNATURE_ERROR,
// SIGNATURE_VALID,
// SIGNATURE_INVALID,
// RESOLVED
// }
// Path: src/main/java/org/simplify4u/plugins/GoOfflineMojo.java
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.simplify4u.plugins.pgp.SignatureCheckResult;
import org.simplify4u.plugins.pgp.SignatureStatus;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins;
/**
* Resolve OpenPGP signature and keys of all project and plugins dependencies.
* <p>
* Verification of signature in this goal will not occurs. In case of any problem only warn will be reported.
*
* @author Slawomir Jaranowski
* @since 1.13.0
*/
@Slf4j
@Mojo(name = GoOfflineMojo.MOJO_NAME, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true)
public class GoOfflineMojo extends AbstractVerifyMojo<Void> {
public static final String MOJO_NAME = "go-offline";
@Override
protected String getMojoName() {
return MOJO_NAME;
}
@Override
protected void shouldProcess(Set<Artifact> artifacts, Runnable runnable) {
runnable.run();
}
@Override
protected Void processArtifactSignature(Artifact artifact, Artifact ascArtifact) { | SignatureCheckResult checkResult = signatureUtils.resolveSignature(artifact, ascArtifact, pgpKeysCache); |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/GoOfflineMojo.java | // Path: src/main/java/org/simplify4u/plugins/pgp/SignatureCheckResult.java
// @Value
// @Builder
// public class SignatureCheckResult {
//
// @NonNull
// ArtifactInfo artifact;
//
// KeyInfo key;
// /**
// * Last address for key search.
// */
// String keyShowUrl;
//
// SignatureInfo signature;
//
// @NonNull
// SignatureStatus status;
//
// @JsonIgnore
// Throwable errorCause;
//
// public String getErrorMessage() {
// return Optional.ofNullable(errorCause).map(Throwable::getMessage).orElse(null);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureStatus.java
// public enum SignatureStatus {
// ARTIFACT_NOT_RESOLVED,
// SIGNATURE_NOT_RESOLVED,
// KEY_NOT_FOUND,
// ERROR,
// SIGNATURE_ERROR,
// SIGNATURE_VALID,
// SIGNATURE_INVALID,
// RESOLVED
// }
| import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.simplify4u.plugins.pgp.SignatureCheckResult;
import org.simplify4u.plugins.pgp.SignatureStatus; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins;
/**
* Resolve OpenPGP signature and keys of all project and plugins dependencies.
* <p>
* Verification of signature in this goal will not occurs. In case of any problem only warn will be reported.
*
* @author Slawomir Jaranowski
* @since 1.13.0
*/
@Slf4j
@Mojo(name = GoOfflineMojo.MOJO_NAME, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true)
public class GoOfflineMojo extends AbstractVerifyMojo<Void> {
public static final String MOJO_NAME = "go-offline";
@Override
protected String getMojoName() {
return MOJO_NAME;
}
@Override
protected void shouldProcess(Set<Artifact> artifacts, Runnable runnable) {
runnable.run();
}
@Override
protected Void processArtifactSignature(Artifact artifact, Artifact ascArtifact) {
SignatureCheckResult checkResult = signatureUtils.resolveSignature(artifact, ascArtifact, pgpKeysCache); | // Path: src/main/java/org/simplify4u/plugins/pgp/SignatureCheckResult.java
// @Value
// @Builder
// public class SignatureCheckResult {
//
// @NonNull
// ArtifactInfo artifact;
//
// KeyInfo key;
// /**
// * Last address for key search.
// */
// String keyShowUrl;
//
// SignatureInfo signature;
//
// @NonNull
// SignatureStatus status;
//
// @JsonIgnore
// Throwable errorCause;
//
// public String getErrorMessage() {
// return Optional.ofNullable(errorCause).map(Throwable::getMessage).orElse(null);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureStatus.java
// public enum SignatureStatus {
// ARTIFACT_NOT_RESOLVED,
// SIGNATURE_NOT_RESOLVED,
// KEY_NOT_FOUND,
// ERROR,
// SIGNATURE_ERROR,
// SIGNATURE_VALID,
// SIGNATURE_INVALID,
// RESOLVED
// }
// Path: src/main/java/org/simplify4u/plugins/GoOfflineMojo.java
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.simplify4u.plugins.pgp.SignatureCheckResult;
import org.simplify4u.plugins.pgp.SignatureStatus;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins;
/**
* Resolve OpenPGP signature and keys of all project and plugins dependencies.
* <p>
* Verification of signature in this goal will not occurs. In case of any problem only warn will be reported.
*
* @author Slawomir Jaranowski
* @since 1.13.0
*/
@Slf4j
@Mojo(name = GoOfflineMojo.MOJO_NAME, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true)
public class GoOfflineMojo extends AbstractVerifyMojo<Void> {
public static final String MOJO_NAME = "go-offline";
@Override
protected String getMojoName() {
return MOJO_NAME;
}
@Override
protected void shouldProcess(Set<Artifact> artifacts, Runnable runnable) {
runnable.run();
}
@Override
protected Void processArtifactSignature(Artifact artifact, Artifact ascArtifact) {
SignatureCheckResult checkResult = signatureUtils.resolveSignature(artifact, ascArtifact, pgpKeysCache); | if (checkResult.getStatus() != SignatureStatus.RESOLVED) { |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/pgp/ReportsUtilsTest.java | // Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static SignatureCheckResult.SignatureCheckResultBuilder aSignatureCheckResultBuilder(Date date) {
// return SignatureCheckResult.builder()
// .artifact(ArtifactInfo.builder()
// .groupId("groupId")
// .artifactId("artifactId")
// .type("jar")
// .classifier("classifier")
// .version("1.0")
// .build())
// .signature(SignatureInfo.builder()
// .version(4)
// .keyId(KeyId.from(0x1234L))
// .hashAlgorithm(HashAlgorithmTags.MD5)
// .keyAlgorithm(PublicKeyAlgorithmTags.RSA_GENERAL)
// .date(date)
// .build())
// .key(KeyInfo.builder()
// .version(4)
// .fingerprint(new KeyFingerprint("0x12345678901234567890"))
// .master(new KeyFingerprint("0x09876543210987654321"))
// .algorithm(PublicKeyAlgorithmTags.RSA_GENERAL)
// .uids(Collections.singleton("Test uid <[email protected]>"))
// .bits(2048)
// .date(date)
// .build())
// .status(SignatureStatus.SIGNATURE_VALID)
// .keyShowUrl("https://example.com/key");
// }
| import java.io.File;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.simplify4u.plugins.TestUtils.aSignatureCheckResultBuilder;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.pgp;
public class ReportsUtilsTest {
private ReportsUtils reportsUtils = new ReportsUtils();
private File reportFile;
@BeforeMethod
void setup() throws IOException {
reportFile = File.createTempFile("report-test", ".json");
reportFile.deleteOnExit();
}
@AfterMethod
void cleanup() {
reportFile.delete();
}
@Test
void shouldGenerateEmptyArray() throws IOException {
reportsUtils.writeReportAsJson(reportFile, Collections.emptyList());
assertThat(reportFile).hasContent("[]");
}
@Test
void nullCollectionThrowNPE() {
assertThatThrownBy(() -> reportsUtils.writeReportAsJson(reportFile, null))
.isExactlyInstanceOf(NullPointerException.class);
}
@Test
void shouldGenerateReport() throws IOException {
File expectedReport = new File(getClass().getResource("/test-report.json").getFile());
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2020-06-05T11:22:33.444+00:00[UTC]");
Date date1 = Date.from(zonedDateTime.toInstant());
Date date2 = Date.from(zonedDateTime.minusDays(44).minusHours(1).toInstant());
| // Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static SignatureCheckResult.SignatureCheckResultBuilder aSignatureCheckResultBuilder(Date date) {
// return SignatureCheckResult.builder()
// .artifact(ArtifactInfo.builder()
// .groupId("groupId")
// .artifactId("artifactId")
// .type("jar")
// .classifier("classifier")
// .version("1.0")
// .build())
// .signature(SignatureInfo.builder()
// .version(4)
// .keyId(KeyId.from(0x1234L))
// .hashAlgorithm(HashAlgorithmTags.MD5)
// .keyAlgorithm(PublicKeyAlgorithmTags.RSA_GENERAL)
// .date(date)
// .build())
// .key(KeyInfo.builder()
// .version(4)
// .fingerprint(new KeyFingerprint("0x12345678901234567890"))
// .master(new KeyFingerprint("0x09876543210987654321"))
// .algorithm(PublicKeyAlgorithmTags.RSA_GENERAL)
// .uids(Collections.singleton("Test uid <[email protected]>"))
// .bits(2048)
// .date(date)
// .build())
// .status(SignatureStatus.SIGNATURE_VALID)
// .keyShowUrl("https://example.com/key");
// }
// Path: src/test/java/org/simplify4u/plugins/pgp/ReportsUtilsTest.java
import java.io.File;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.simplify4u.plugins.TestUtils.aSignatureCheckResultBuilder;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.pgp;
public class ReportsUtilsTest {
private ReportsUtils reportsUtils = new ReportsUtils();
private File reportFile;
@BeforeMethod
void setup() throws IOException {
reportFile = File.createTempFile("report-test", ".json");
reportFile.deleteOnExit();
}
@AfterMethod
void cleanup() {
reportFile.delete();
}
@Test
void shouldGenerateEmptyArray() throws IOException {
reportsUtils.writeReportAsJson(reportFile, Collections.emptyList());
assertThat(reportFile).hasContent("[]");
}
@Test
void nullCollectionThrowNPE() {
assertThatThrownBy(() -> reportsUtils.writeReportAsJson(reportFile, null))
.isExactlyInstanceOf(NullPointerException.class);
}
@Test
void shouldGenerateReport() throws IOException {
File expectedReport = new File(getClass().getResource("/test-report.json").getFile());
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2020-06-05T11:22:33.444+00:00[UTC]");
Date date1 = Date.from(zonedDateTime.toInstant());
Date date2 = Date.from(zonedDateTime.minusDays(44).minusHours(1).toInstant());
| SignatureCheckResult checkResult1 = aSignatureCheckResultBuilder(date1) |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/pgp/PublicKeyUtils.java | // Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// @UtilityClass
// public class HexUtils {
//
// /**
// * Convert byte array of fingerprint to string of hex
// * @param bytes fingerprint
// * @return fingerprint as string
// */
// public static String fingerprintToString(byte[] bytes) {
// StringBuilder ret = new StringBuilder();
// ret.append("0x");
// for (byte b : bytes) {
// ret.append(String.format("%02X", b));
// }
// return ret.toString();
// }
//
// /**
// * Convert fingerprint in string format to byte array.
// * @param key fingerprint as string
// * @return fingerprint as byte array
// */
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator;
import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider;
import org.simplify4u.plugins.utils.HexUtils; | /*
* Copyright 2020-2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.pgp;
/**
* Utility for PGPPublicKey
*/
@Slf4j
public final class PublicKeyUtils {
private PublicKeyUtils() {
// No need to instantiate utility class.
}
/**
* Generate string version of key fingerprint
*
* @param publicKey given key
*
* @return fingerprint as string
*/
static String fingerprint(PGPPublicKey publicKey) { | // Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// @UtilityClass
// public class HexUtils {
//
// /**
// * Convert byte array of fingerprint to string of hex
// * @param bytes fingerprint
// * @return fingerprint as string
// */
// public static String fingerprintToString(byte[] bytes) {
// StringBuilder ret = new StringBuilder();
// ret.append("0x");
// for (byte b : bytes) {
// ret.append(String.format("%02X", b));
// }
// return ret.toString();
// }
//
// /**
// * Convert fingerprint in string format to byte array.
// * @param key fingerprint as string
// * @return fingerprint as byte array
// */
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
// }
// Path: src/main/java/org/simplify4u/plugins/pgp/PublicKeyUtils.java
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator;
import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider;
import org.simplify4u.plugins.utils.HexUtils;
/*
* Copyright 2020-2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.pgp;
/**
* Utility for PGPPublicKey
*/
@Slf4j
public final class PublicKeyUtils {
private PublicKeyUtils() {
// No need to instantiate utility class.
}
/**
* Generate string version of key fingerprint
*
* @param publicKey given key
*
* @return fingerprint as string
*/
static String fingerprint(PGPPublicKey publicKey) { | return HexUtils.fingerprintToString(publicKey.getFingerprint()); |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/keysmap/KeyItems.java | // Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.simplify4u.plugins.pgp.KeyInfo; | }
/**
* Add keys from another KeyItems.
*
* @param keyItems a keyItem with key to add
* @param keysMapContext a context of current processing
*
* @return a current object instance
*/
public KeyItems addKeys(KeyItems keyItems, KeysMapContext keysMapContext) {
keyItems.keys.forEach(key -> addKey(key, keysMapContext));
return this;
}
/**
* Add key to list only if not exist.
*
* @param keyItem a key to add
* @param keysMapContext a context of current processing
*/
private void addKey(KeyItem keyItem, KeysMapContext keysMapContext) {
if (!keys.contains(keyItem)) {
keys.add(keyItem);
} else {
LOGGER.warn("Duplicate key item: {} in: {}", keyItem, keysMapContext);
}
}
| // Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
// Path: src/main/java/org/simplify4u/plugins/keysmap/KeyItems.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.simplify4u.plugins.pgp.KeyInfo;
}
/**
* Add keys from another KeyItems.
*
* @param keyItems a keyItem with key to add
* @param keysMapContext a context of current processing
*
* @return a current object instance
*/
public KeyItems addKeys(KeyItems keyItems, KeysMapContext keysMapContext) {
keyItems.keys.forEach(key -> addKey(key, keysMapContext));
return this;
}
/**
* Add key to list only if not exist.
*
* @param keyItem a key to add
* @param keysMapContext a context of current processing
*/
private void addKey(KeyItem keyItem, KeysMapContext keysMapContext) {
if (!keys.contains(keyItem)) {
keys.add(keyItem);
} else {
LOGGER.warn("Duplicate key item: {} in: {}", keyItem, keysMapContext);
}
}
| public boolean isKeyMatch(KeyInfo keyInfo) { |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/ShowMojo.java | // Path: src/main/java/org/simplify4u/plugins/pgp/ArtifactInfo.java
// @Value
// @Builder
// public class ArtifactInfo {
//
// @NonNull
// String groupId;
//
// @NonNull
// String artifactId;
//
// @NonNull
// String type;
//
// @NonNull
// String version;
//
// String classifier;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureCheckResult.java
// @Value
// @Builder
// public class SignatureCheckResult {
//
// @NonNull
// ArtifactInfo artifact;
//
// KeyInfo key;
// /**
// * Last address for key search.
// */
// String keyShowUrl;
//
// SignatureInfo signature;
//
// @NonNull
// SignatureStatus status;
//
// @JsonIgnore
// Throwable errorCause;
//
// public String getErrorMessage() {
// return Optional.ofNullable(errorCause).map(Throwable::getMessage).orElse(null);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureInfo.java
// @Value
// @Builder
// public class SignatureInfo {
//
// int hashAlgorithm;
// int keyAlgorithm;
// KeyId keyId;
// Date date;
// int version;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureStatus.java
// public enum SignatureStatus {
// ARTIFACT_NOT_RESOLVED,
// SIGNATURE_NOT_RESOLVED,
// KEY_NOT_FOUND,
// ERROR,
// SIGNATURE_ERROR,
// SIGNATURE_VALID,
// SIGNATURE_INVALID,
// RESOLVED
// }
| import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.inject.Inject;
import io.vavr.control.Try;
import lombok.AccessLevel;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.shared.utils.logging.MessageBuilder;
import org.apache.maven.shared.utils.logging.MessageUtils;
import org.bouncycastle.openpgp.PGPUtil;
import org.simplify4u.plugins.pgp.ArtifactInfo;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.pgp.SignatureCheckResult;
import org.simplify4u.plugins.pgp.SignatureInfo;
import org.simplify4u.plugins.pgp.SignatureStatus; | }
@Override
protected void executeConfiguredMojo() {
Set<Artifact> artifactsToCheck = new HashSet<>();
Artifact artifactToCheck = prepareArtifactToCheck();
artifactsToCheck.add(artifactResolver.resolveArtifact(artifactToCheck));
if (showPom && artifactToCheck.isResolved()) {
artifactsToCheck.add(artifactResolver.resolvePom(artifactToCheck));
}
Map<Artifact, Artifact> artifactMap = artifactResolver.resolveSignatures(artifactsToCheck);
Boolean result = artifactMap.entrySet().stream()
.map(this::processArtifact)
.reduce(true, (a, b) -> a && b);
if (Boolean.FALSE.equals(result)) {
throw new PGPMojoException("Some of artifact can't be checked");
}
}
private boolean processArtifact(Map.Entry<Artifact, Artifact> artifactEntry) {
Artifact artifactToCheck = artifactEntry.getKey();
Artifact sig = artifactEntry.getValue();
| // Path: src/main/java/org/simplify4u/plugins/pgp/ArtifactInfo.java
// @Value
// @Builder
// public class ArtifactInfo {
//
// @NonNull
// String groupId;
//
// @NonNull
// String artifactId;
//
// @NonNull
// String type;
//
// @NonNull
// String version;
//
// String classifier;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureCheckResult.java
// @Value
// @Builder
// public class SignatureCheckResult {
//
// @NonNull
// ArtifactInfo artifact;
//
// KeyInfo key;
// /**
// * Last address for key search.
// */
// String keyShowUrl;
//
// SignatureInfo signature;
//
// @NonNull
// SignatureStatus status;
//
// @JsonIgnore
// Throwable errorCause;
//
// public String getErrorMessage() {
// return Optional.ofNullable(errorCause).map(Throwable::getMessage).orElse(null);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureInfo.java
// @Value
// @Builder
// public class SignatureInfo {
//
// int hashAlgorithm;
// int keyAlgorithm;
// KeyId keyId;
// Date date;
// int version;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureStatus.java
// public enum SignatureStatus {
// ARTIFACT_NOT_RESOLVED,
// SIGNATURE_NOT_RESOLVED,
// KEY_NOT_FOUND,
// ERROR,
// SIGNATURE_ERROR,
// SIGNATURE_VALID,
// SIGNATURE_INVALID,
// RESOLVED
// }
// Path: src/main/java/org/simplify4u/plugins/ShowMojo.java
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.inject.Inject;
import io.vavr.control.Try;
import lombok.AccessLevel;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.shared.utils.logging.MessageBuilder;
import org.apache.maven.shared.utils.logging.MessageUtils;
import org.bouncycastle.openpgp.PGPUtil;
import org.simplify4u.plugins.pgp.ArtifactInfo;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.pgp.SignatureCheckResult;
import org.simplify4u.plugins.pgp.SignatureInfo;
import org.simplify4u.plugins.pgp.SignatureStatus;
}
@Override
protected void executeConfiguredMojo() {
Set<Artifact> artifactsToCheck = new HashSet<>();
Artifact artifactToCheck = prepareArtifactToCheck();
artifactsToCheck.add(artifactResolver.resolveArtifact(artifactToCheck));
if (showPom && artifactToCheck.isResolved()) {
artifactsToCheck.add(artifactResolver.resolvePom(artifactToCheck));
}
Map<Artifact, Artifact> artifactMap = artifactResolver.resolveSignatures(artifactsToCheck);
Boolean result = artifactMap.entrySet().stream()
.map(this::processArtifact)
.reduce(true, (a, b) -> a && b);
if (Boolean.FALSE.equals(result)) {
throw new PGPMojoException("Some of artifact can't be checked");
}
}
private boolean processArtifact(Map.Entry<Artifact, Artifact> artifactEntry) {
Artifact artifactToCheck = artifactEntry.getKey();
Artifact sig = artifactEntry.getValue();
| SignatureCheckResult signatureCheckResult = signatureUtils.checkSignature(artifactToCheck, sig, pgpKeysCache); |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/ShowMojo.java | // Path: src/main/java/org/simplify4u/plugins/pgp/ArtifactInfo.java
// @Value
// @Builder
// public class ArtifactInfo {
//
// @NonNull
// String groupId;
//
// @NonNull
// String artifactId;
//
// @NonNull
// String type;
//
// @NonNull
// String version;
//
// String classifier;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureCheckResult.java
// @Value
// @Builder
// public class SignatureCheckResult {
//
// @NonNull
// ArtifactInfo artifact;
//
// KeyInfo key;
// /**
// * Last address for key search.
// */
// String keyShowUrl;
//
// SignatureInfo signature;
//
// @NonNull
// SignatureStatus status;
//
// @JsonIgnore
// Throwable errorCause;
//
// public String getErrorMessage() {
// return Optional.ofNullable(errorCause).map(Throwable::getMessage).orElse(null);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureInfo.java
// @Value
// @Builder
// public class SignatureInfo {
//
// int hashAlgorithm;
// int keyAlgorithm;
// KeyId keyId;
// Date date;
// int version;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureStatus.java
// public enum SignatureStatus {
// ARTIFACT_NOT_RESOLVED,
// SIGNATURE_NOT_RESOLVED,
// KEY_NOT_FOUND,
// ERROR,
// SIGNATURE_ERROR,
// SIGNATURE_VALID,
// SIGNATURE_INVALID,
// RESOLVED
// }
| import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.inject.Inject;
import io.vavr.control.Try;
import lombok.AccessLevel;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.shared.utils.logging.MessageBuilder;
import org.apache.maven.shared.utils.logging.MessageUtils;
import org.bouncycastle.openpgp.PGPUtil;
import org.simplify4u.plugins.pgp.ArtifactInfo;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.pgp.SignatureCheckResult;
import org.simplify4u.plugins.pgp.SignatureInfo;
import org.simplify4u.plugins.pgp.SignatureStatus; | Artifact artifactToCheck = prepareArtifactToCheck();
artifactsToCheck.add(artifactResolver.resolveArtifact(artifactToCheck));
if (showPom && artifactToCheck.isResolved()) {
artifactsToCheck.add(artifactResolver.resolvePom(artifactToCheck));
}
Map<Artifact, Artifact> artifactMap = artifactResolver.resolveSignatures(artifactsToCheck);
Boolean result = artifactMap.entrySet().stream()
.map(this::processArtifact)
.reduce(true, (a, b) -> a && b);
if (Boolean.FALSE.equals(result)) {
throw new PGPMojoException("Some of artifact can't be checked");
}
}
private boolean processArtifact(Map.Entry<Artifact, Artifact> artifactEntry) {
Artifact artifactToCheck = artifactEntry.getKey();
Artifact sig = artifactEntry.getValue();
SignatureCheckResult signatureCheckResult = signatureUtils.checkSignature(artifactToCheck, sig, pgpKeysCache);
MessageBuilder messageBuilder = MessageUtils.buffer();
messageBuilder.newline();
messageBuilder.newline();
| // Path: src/main/java/org/simplify4u/plugins/pgp/ArtifactInfo.java
// @Value
// @Builder
// public class ArtifactInfo {
//
// @NonNull
// String groupId;
//
// @NonNull
// String artifactId;
//
// @NonNull
// String type;
//
// @NonNull
// String version;
//
// String classifier;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureCheckResult.java
// @Value
// @Builder
// public class SignatureCheckResult {
//
// @NonNull
// ArtifactInfo artifact;
//
// KeyInfo key;
// /**
// * Last address for key search.
// */
// String keyShowUrl;
//
// SignatureInfo signature;
//
// @NonNull
// SignatureStatus status;
//
// @JsonIgnore
// Throwable errorCause;
//
// public String getErrorMessage() {
// return Optional.ofNullable(errorCause).map(Throwable::getMessage).orElse(null);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureInfo.java
// @Value
// @Builder
// public class SignatureInfo {
//
// int hashAlgorithm;
// int keyAlgorithm;
// KeyId keyId;
// Date date;
// int version;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureStatus.java
// public enum SignatureStatus {
// ARTIFACT_NOT_RESOLVED,
// SIGNATURE_NOT_RESOLVED,
// KEY_NOT_FOUND,
// ERROR,
// SIGNATURE_ERROR,
// SIGNATURE_VALID,
// SIGNATURE_INVALID,
// RESOLVED
// }
// Path: src/main/java/org/simplify4u/plugins/ShowMojo.java
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.inject.Inject;
import io.vavr.control.Try;
import lombok.AccessLevel;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.shared.utils.logging.MessageBuilder;
import org.apache.maven.shared.utils.logging.MessageUtils;
import org.bouncycastle.openpgp.PGPUtil;
import org.simplify4u.plugins.pgp.ArtifactInfo;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.pgp.SignatureCheckResult;
import org.simplify4u.plugins.pgp.SignatureInfo;
import org.simplify4u.plugins.pgp.SignatureStatus;
Artifact artifactToCheck = prepareArtifactToCheck();
artifactsToCheck.add(artifactResolver.resolveArtifact(artifactToCheck));
if (showPom && artifactToCheck.isResolved()) {
artifactsToCheck.add(artifactResolver.resolvePom(artifactToCheck));
}
Map<Artifact, Artifact> artifactMap = artifactResolver.resolveSignatures(artifactsToCheck);
Boolean result = artifactMap.entrySet().stream()
.map(this::processArtifact)
.reduce(true, (a, b) -> a && b);
if (Boolean.FALSE.equals(result)) {
throw new PGPMojoException("Some of artifact can't be checked");
}
}
private boolean processArtifact(Map.Entry<Artifact, Artifact> artifactEntry) {
Artifact artifactToCheck = artifactEntry.getKey();
Artifact sig = artifactEntry.getValue();
SignatureCheckResult signatureCheckResult = signatureUtils.checkSignature(artifactToCheck, sig, pgpKeysCache);
MessageBuilder messageBuilder = MessageUtils.buffer();
messageBuilder.newline();
messageBuilder.newline();
| ArtifactInfo artifactInfo = signatureCheckResult.getArtifact(); |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/ShowMojo.java | // Path: src/main/java/org/simplify4u/plugins/pgp/ArtifactInfo.java
// @Value
// @Builder
// public class ArtifactInfo {
//
// @NonNull
// String groupId;
//
// @NonNull
// String artifactId;
//
// @NonNull
// String type;
//
// @NonNull
// String version;
//
// String classifier;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureCheckResult.java
// @Value
// @Builder
// public class SignatureCheckResult {
//
// @NonNull
// ArtifactInfo artifact;
//
// KeyInfo key;
// /**
// * Last address for key search.
// */
// String keyShowUrl;
//
// SignatureInfo signature;
//
// @NonNull
// SignatureStatus status;
//
// @JsonIgnore
// Throwable errorCause;
//
// public String getErrorMessage() {
// return Optional.ofNullable(errorCause).map(Throwable::getMessage).orElse(null);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureInfo.java
// @Value
// @Builder
// public class SignatureInfo {
//
// int hashAlgorithm;
// int keyAlgorithm;
// KeyId keyId;
// Date date;
// int version;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureStatus.java
// public enum SignatureStatus {
// ARTIFACT_NOT_RESOLVED,
// SIGNATURE_NOT_RESOLVED,
// KEY_NOT_FOUND,
// ERROR,
// SIGNATURE_ERROR,
// SIGNATURE_VALID,
// SIGNATURE_INVALID,
// RESOLVED
// }
| import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.inject.Inject;
import io.vavr.control.Try;
import lombok.AccessLevel;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.shared.utils.logging.MessageBuilder;
import org.apache.maven.shared.utils.logging.MessageUtils;
import org.bouncycastle.openpgp.PGPUtil;
import org.simplify4u.plugins.pgp.ArtifactInfo;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.pgp.SignatureCheckResult;
import org.simplify4u.plugins.pgp.SignatureInfo;
import org.simplify4u.plugins.pgp.SignatureStatus; |
Boolean result = artifactMap.entrySet().stream()
.map(this::processArtifact)
.reduce(true, (a, b) -> a && b);
if (Boolean.FALSE.equals(result)) {
throw new PGPMojoException("Some of artifact can't be checked");
}
}
private boolean processArtifact(Map.Entry<Artifact, Artifact> artifactEntry) {
Artifact artifactToCheck = artifactEntry.getKey();
Artifact sig = artifactEntry.getValue();
SignatureCheckResult signatureCheckResult = signatureUtils.checkSignature(artifactToCheck, sig, pgpKeysCache);
MessageBuilder messageBuilder = MessageUtils.buffer();
messageBuilder.newline();
messageBuilder.newline();
ArtifactInfo artifactInfo = signatureCheckResult.getArtifact();
messageBuilder.a("Artifact:").newline();
messageBuilder.a("\tgroupId: ").strong(artifactInfo.getGroupId()).newline();
messageBuilder.a("\tartifactId: ").strong(artifactInfo.getArtifactId()).newline();
messageBuilder.a("\ttype: ").strong(artifactInfo.getType()).newline();
Optional.ofNullable(artifactInfo.getClassifier()).ifPresent(
classifier -> messageBuilder.a("\tclassifier: ").strong(classifier).newline());
messageBuilder.a("\tversion: ").strong(artifactInfo.getVersion()).newline(); | // Path: src/main/java/org/simplify4u/plugins/pgp/ArtifactInfo.java
// @Value
// @Builder
// public class ArtifactInfo {
//
// @NonNull
// String groupId;
//
// @NonNull
// String artifactId;
//
// @NonNull
// String type;
//
// @NonNull
// String version;
//
// String classifier;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureCheckResult.java
// @Value
// @Builder
// public class SignatureCheckResult {
//
// @NonNull
// ArtifactInfo artifact;
//
// KeyInfo key;
// /**
// * Last address for key search.
// */
// String keyShowUrl;
//
// SignatureInfo signature;
//
// @NonNull
// SignatureStatus status;
//
// @JsonIgnore
// Throwable errorCause;
//
// public String getErrorMessage() {
// return Optional.ofNullable(errorCause).map(Throwable::getMessage).orElse(null);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureInfo.java
// @Value
// @Builder
// public class SignatureInfo {
//
// int hashAlgorithm;
// int keyAlgorithm;
// KeyId keyId;
// Date date;
// int version;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureStatus.java
// public enum SignatureStatus {
// ARTIFACT_NOT_RESOLVED,
// SIGNATURE_NOT_RESOLVED,
// KEY_NOT_FOUND,
// ERROR,
// SIGNATURE_ERROR,
// SIGNATURE_VALID,
// SIGNATURE_INVALID,
// RESOLVED
// }
// Path: src/main/java/org/simplify4u/plugins/ShowMojo.java
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.inject.Inject;
import io.vavr.control.Try;
import lombok.AccessLevel;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.shared.utils.logging.MessageBuilder;
import org.apache.maven.shared.utils.logging.MessageUtils;
import org.bouncycastle.openpgp.PGPUtil;
import org.simplify4u.plugins.pgp.ArtifactInfo;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.pgp.SignatureCheckResult;
import org.simplify4u.plugins.pgp.SignatureInfo;
import org.simplify4u.plugins.pgp.SignatureStatus;
Boolean result = artifactMap.entrySet().stream()
.map(this::processArtifact)
.reduce(true, (a, b) -> a && b);
if (Boolean.FALSE.equals(result)) {
throw new PGPMojoException("Some of artifact can't be checked");
}
}
private boolean processArtifact(Map.Entry<Artifact, Artifact> artifactEntry) {
Artifact artifactToCheck = artifactEntry.getKey();
Artifact sig = artifactEntry.getValue();
SignatureCheckResult signatureCheckResult = signatureUtils.checkSignature(artifactToCheck, sig, pgpKeysCache);
MessageBuilder messageBuilder = MessageUtils.buffer();
messageBuilder.newline();
messageBuilder.newline();
ArtifactInfo artifactInfo = signatureCheckResult.getArtifact();
messageBuilder.a("Artifact:").newline();
messageBuilder.a("\tgroupId: ").strong(artifactInfo.getGroupId()).newline();
messageBuilder.a("\tartifactId: ").strong(artifactInfo.getArtifactId()).newline();
messageBuilder.a("\ttype: ").strong(artifactInfo.getType()).newline();
Optional.ofNullable(artifactInfo.getClassifier()).ifPresent(
classifier -> messageBuilder.a("\tclassifier: ").strong(classifier).newline());
messageBuilder.a("\tversion: ").strong(artifactInfo.getVersion()).newline(); | if (signatureCheckResult.getStatus() == SignatureStatus.ARTIFACT_NOT_RESOLVED) { |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/ShowMojo.java | // Path: src/main/java/org/simplify4u/plugins/pgp/ArtifactInfo.java
// @Value
// @Builder
// public class ArtifactInfo {
//
// @NonNull
// String groupId;
//
// @NonNull
// String artifactId;
//
// @NonNull
// String type;
//
// @NonNull
// String version;
//
// String classifier;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureCheckResult.java
// @Value
// @Builder
// public class SignatureCheckResult {
//
// @NonNull
// ArtifactInfo artifact;
//
// KeyInfo key;
// /**
// * Last address for key search.
// */
// String keyShowUrl;
//
// SignatureInfo signature;
//
// @NonNull
// SignatureStatus status;
//
// @JsonIgnore
// Throwable errorCause;
//
// public String getErrorMessage() {
// return Optional.ofNullable(errorCause).map(Throwable::getMessage).orElse(null);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureInfo.java
// @Value
// @Builder
// public class SignatureInfo {
//
// int hashAlgorithm;
// int keyAlgorithm;
// KeyId keyId;
// Date date;
// int version;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureStatus.java
// public enum SignatureStatus {
// ARTIFACT_NOT_RESOLVED,
// SIGNATURE_NOT_RESOLVED,
// KEY_NOT_FOUND,
// ERROR,
// SIGNATURE_ERROR,
// SIGNATURE_VALID,
// SIGNATURE_INVALID,
// RESOLVED
// }
| import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.inject.Inject;
import io.vavr.control.Try;
import lombok.AccessLevel;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.shared.utils.logging.MessageBuilder;
import org.apache.maven.shared.utils.logging.MessageUtils;
import org.bouncycastle.openpgp.PGPUtil;
import org.simplify4u.plugins.pgp.ArtifactInfo;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.pgp.SignatureCheckResult;
import org.simplify4u.plugins.pgp.SignatureInfo;
import org.simplify4u.plugins.pgp.SignatureStatus; | throw new PGPMojoException("Some of artifact can't be checked");
}
}
private boolean processArtifact(Map.Entry<Artifact, Artifact> artifactEntry) {
Artifact artifactToCheck = artifactEntry.getKey();
Artifact sig = artifactEntry.getValue();
SignatureCheckResult signatureCheckResult = signatureUtils.checkSignature(artifactToCheck, sig, pgpKeysCache);
MessageBuilder messageBuilder = MessageUtils.buffer();
messageBuilder.newline();
messageBuilder.newline();
ArtifactInfo artifactInfo = signatureCheckResult.getArtifact();
messageBuilder.a("Artifact:").newline();
messageBuilder.a("\tgroupId: ").strong(artifactInfo.getGroupId()).newline();
messageBuilder.a("\tartifactId: ").strong(artifactInfo.getArtifactId()).newline();
messageBuilder.a("\ttype: ").strong(artifactInfo.getType()).newline();
Optional.ofNullable(artifactInfo.getClassifier()).ifPresent(
classifier -> messageBuilder.a("\tclassifier: ").strong(classifier).newline());
messageBuilder.a("\tversion: ").strong(artifactInfo.getVersion()).newline();
if (signatureCheckResult.getStatus() == SignatureStatus.ARTIFACT_NOT_RESOLVED) {
messageBuilder.a("\t").failure("artifact was not resolved - try mvn -U ...").newline();
}
messageBuilder.newline();
| // Path: src/main/java/org/simplify4u/plugins/pgp/ArtifactInfo.java
// @Value
// @Builder
// public class ArtifactInfo {
//
// @NonNull
// String groupId;
//
// @NonNull
// String artifactId;
//
// @NonNull
// String type;
//
// @NonNull
// String version;
//
// String classifier;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureCheckResult.java
// @Value
// @Builder
// public class SignatureCheckResult {
//
// @NonNull
// ArtifactInfo artifact;
//
// KeyInfo key;
// /**
// * Last address for key search.
// */
// String keyShowUrl;
//
// SignatureInfo signature;
//
// @NonNull
// SignatureStatus status;
//
// @JsonIgnore
// Throwable errorCause;
//
// public String getErrorMessage() {
// return Optional.ofNullable(errorCause).map(Throwable::getMessage).orElse(null);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureInfo.java
// @Value
// @Builder
// public class SignatureInfo {
//
// int hashAlgorithm;
// int keyAlgorithm;
// KeyId keyId;
// Date date;
// int version;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureStatus.java
// public enum SignatureStatus {
// ARTIFACT_NOT_RESOLVED,
// SIGNATURE_NOT_RESOLVED,
// KEY_NOT_FOUND,
// ERROR,
// SIGNATURE_ERROR,
// SIGNATURE_VALID,
// SIGNATURE_INVALID,
// RESOLVED
// }
// Path: src/main/java/org/simplify4u/plugins/ShowMojo.java
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.inject.Inject;
import io.vavr.control.Try;
import lombok.AccessLevel;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.shared.utils.logging.MessageBuilder;
import org.apache.maven.shared.utils.logging.MessageUtils;
import org.bouncycastle.openpgp.PGPUtil;
import org.simplify4u.plugins.pgp.ArtifactInfo;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.pgp.SignatureCheckResult;
import org.simplify4u.plugins.pgp.SignatureInfo;
import org.simplify4u.plugins.pgp.SignatureStatus;
throw new PGPMojoException("Some of artifact can't be checked");
}
}
private boolean processArtifact(Map.Entry<Artifact, Artifact> artifactEntry) {
Artifact artifactToCheck = artifactEntry.getKey();
Artifact sig = artifactEntry.getValue();
SignatureCheckResult signatureCheckResult = signatureUtils.checkSignature(artifactToCheck, sig, pgpKeysCache);
MessageBuilder messageBuilder = MessageUtils.buffer();
messageBuilder.newline();
messageBuilder.newline();
ArtifactInfo artifactInfo = signatureCheckResult.getArtifact();
messageBuilder.a("Artifact:").newline();
messageBuilder.a("\tgroupId: ").strong(artifactInfo.getGroupId()).newline();
messageBuilder.a("\tartifactId: ").strong(artifactInfo.getArtifactId()).newline();
messageBuilder.a("\ttype: ").strong(artifactInfo.getType()).newline();
Optional.ofNullable(artifactInfo.getClassifier()).ifPresent(
classifier -> messageBuilder.a("\tclassifier: ").strong(classifier).newline());
messageBuilder.a("\tversion: ").strong(artifactInfo.getVersion()).newline();
if (signatureCheckResult.getStatus() == SignatureStatus.ARTIFACT_NOT_RESOLVED) {
messageBuilder.a("\t").failure("artifact was not resolved - try mvn -U ...").newline();
}
messageBuilder.newline();
| SignatureInfo signature = signatureCheckResult.getSignature(); |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/ShowMojo.java | // Path: src/main/java/org/simplify4u/plugins/pgp/ArtifactInfo.java
// @Value
// @Builder
// public class ArtifactInfo {
//
// @NonNull
// String groupId;
//
// @NonNull
// String artifactId;
//
// @NonNull
// String type;
//
// @NonNull
// String version;
//
// String classifier;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureCheckResult.java
// @Value
// @Builder
// public class SignatureCheckResult {
//
// @NonNull
// ArtifactInfo artifact;
//
// KeyInfo key;
// /**
// * Last address for key search.
// */
// String keyShowUrl;
//
// SignatureInfo signature;
//
// @NonNull
// SignatureStatus status;
//
// @JsonIgnore
// Throwable errorCause;
//
// public String getErrorMessage() {
// return Optional.ofNullable(errorCause).map(Throwable::getMessage).orElse(null);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureInfo.java
// @Value
// @Builder
// public class SignatureInfo {
//
// int hashAlgorithm;
// int keyAlgorithm;
// KeyId keyId;
// Date date;
// int version;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureStatus.java
// public enum SignatureStatus {
// ARTIFACT_NOT_RESOLVED,
// SIGNATURE_NOT_RESOLVED,
// KEY_NOT_FOUND,
// ERROR,
// SIGNATURE_ERROR,
// SIGNATURE_VALID,
// SIGNATURE_INVALID,
// RESOLVED
// }
| import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.inject.Inject;
import io.vavr.control.Try;
import lombok.AccessLevel;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.shared.utils.logging.MessageBuilder;
import org.apache.maven.shared.utils.logging.MessageUtils;
import org.bouncycastle.openpgp.PGPUtil;
import org.simplify4u.plugins.pgp.ArtifactInfo;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.pgp.SignatureCheckResult;
import org.simplify4u.plugins.pgp.SignatureInfo;
import org.simplify4u.plugins.pgp.SignatureStatus; | if (signatureCheckResult.getStatus() == SignatureStatus.ARTIFACT_NOT_RESOLVED) {
messageBuilder.a("\t").failure("artifact was not resolved - try mvn -U ...").newline();
}
messageBuilder.newline();
SignatureInfo signature = signatureCheckResult.getSignature();
if (signature != null) {
messageBuilder.a("PGP signature:").newline();
messageBuilder.a("\tversion: ").strong(signature.getVersion()).newline();
messageBuilder.a("\talgorithm: ")
.strong(Try.of(() ->
PGPUtil.getSignatureName(signature.getKeyAlgorithm(), signature.getHashAlgorithm())).get())
.newline();
messageBuilder.a("\tkeyId: ").strong(signature.getKeyId()).newline();
messageBuilder.a("\tcreate date: ").strong(signature.getDate()).newline();
messageBuilder.a("\tstatus: ");
if (signatureCheckResult.getStatus() == SignatureStatus.SIGNATURE_VALID) {
messageBuilder.success("valid");
} else {
messageBuilder.failure("invalid");
}
messageBuilder.newline();
} else if (signatureCheckResult.getStatus() == SignatureStatus.SIGNATURE_NOT_RESOLVED) {
messageBuilder.a("\t")
.failure("PGP signature was not resolved - try mvn -U ...").newline();
}
messageBuilder.newline();
| // Path: src/main/java/org/simplify4u/plugins/pgp/ArtifactInfo.java
// @Value
// @Builder
// public class ArtifactInfo {
//
// @NonNull
// String groupId;
//
// @NonNull
// String artifactId;
//
// @NonNull
// String type;
//
// @NonNull
// String version;
//
// String classifier;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureCheckResult.java
// @Value
// @Builder
// public class SignatureCheckResult {
//
// @NonNull
// ArtifactInfo artifact;
//
// KeyInfo key;
// /**
// * Last address for key search.
// */
// String keyShowUrl;
//
// SignatureInfo signature;
//
// @NonNull
// SignatureStatus status;
//
// @JsonIgnore
// Throwable errorCause;
//
// public String getErrorMessage() {
// return Optional.ofNullable(errorCause).map(Throwable::getMessage).orElse(null);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureInfo.java
// @Value
// @Builder
// public class SignatureInfo {
//
// int hashAlgorithm;
// int keyAlgorithm;
// KeyId keyId;
// Date date;
// int version;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/SignatureStatus.java
// public enum SignatureStatus {
// ARTIFACT_NOT_RESOLVED,
// SIGNATURE_NOT_RESOLVED,
// KEY_NOT_FOUND,
// ERROR,
// SIGNATURE_ERROR,
// SIGNATURE_VALID,
// SIGNATURE_INVALID,
// RESOLVED
// }
// Path: src/main/java/org/simplify4u/plugins/ShowMojo.java
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.inject.Inject;
import io.vavr.control.Try;
import lombok.AccessLevel;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.shared.utils.logging.MessageBuilder;
import org.apache.maven.shared.utils.logging.MessageUtils;
import org.bouncycastle.openpgp.PGPUtil;
import org.simplify4u.plugins.pgp.ArtifactInfo;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.pgp.SignatureCheckResult;
import org.simplify4u.plugins.pgp.SignatureInfo;
import org.simplify4u.plugins.pgp.SignatureStatus;
if (signatureCheckResult.getStatus() == SignatureStatus.ARTIFACT_NOT_RESOLVED) {
messageBuilder.a("\t").failure("artifact was not resolved - try mvn -U ...").newline();
}
messageBuilder.newline();
SignatureInfo signature = signatureCheckResult.getSignature();
if (signature != null) {
messageBuilder.a("PGP signature:").newline();
messageBuilder.a("\tversion: ").strong(signature.getVersion()).newline();
messageBuilder.a("\talgorithm: ")
.strong(Try.of(() ->
PGPUtil.getSignatureName(signature.getKeyAlgorithm(), signature.getHashAlgorithm())).get())
.newline();
messageBuilder.a("\tkeyId: ").strong(signature.getKeyId()).newline();
messageBuilder.a("\tcreate date: ").strong(signature.getDate()).newline();
messageBuilder.a("\tstatus: ");
if (signatureCheckResult.getStatus() == SignatureStatus.SIGNATURE_VALID) {
messageBuilder.success("valid");
} else {
messageBuilder.failure("invalid");
}
messageBuilder.newline();
} else if (signatureCheckResult.getStatus() == SignatureStatus.SIGNATURE_NOT_RESOLVED) {
messageBuilder.a("\t")
.failure("PGP signature was not resolved - try mvn -U ...").newline();
}
messageBuilder.newline();
| KeyInfo key = signatureCheckResult.getKey(); |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/keysmap/KeyItemFingerprint.java | // Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// @UtilityClass
// public class HexUtils {
//
// /**
// * Convert byte array of fingerprint to string of hex
// * @param bytes fingerprint
// * @return fingerprint as string
// */
// public static String fingerprintToString(byte[] bytes) {
// StringBuilder ret = new StringBuilder();
// ret.append("0x");
// for (byte b : bytes) {
// ret.append(String.format("%02X", b));
// }
// return ret.toString();
// }
//
// /**
// * Convert fingerprint in string format to byte array.
// * @param key fingerprint as string
// * @return fingerprint as byte array
// */
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
// }
| import java.util.Optional;
import static org.simplify4u.plugins.utils.HexUtils.stringToFingerprint;
import lombok.EqualsAndHashCode;
import org.simplify4u.plugins.pgp.KeyFingerprint;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.utils.HexUtils; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* Represent key as fingerprint for given artifact pattern.
*/
@EqualsAndHashCode
class KeyItemFingerprint implements KeyItem {
private final byte[] fingerPrint;
public KeyItemFingerprint(String key) { | // Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// @UtilityClass
// public class HexUtils {
//
// /**
// * Convert byte array of fingerprint to string of hex
// * @param bytes fingerprint
// * @return fingerprint as string
// */
// public static String fingerprintToString(byte[] bytes) {
// StringBuilder ret = new StringBuilder();
// ret.append("0x");
// for (byte b : bytes) {
// ret.append(String.format("%02X", b));
// }
// return ret.toString();
// }
//
// /**
// * Convert fingerprint in string format to byte array.
// * @param key fingerprint as string
// * @return fingerprint as byte array
// */
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
// }
// Path: src/main/java/org/simplify4u/plugins/keysmap/KeyItemFingerprint.java
import java.util.Optional;
import static org.simplify4u.plugins.utils.HexUtils.stringToFingerprint;
import lombok.EqualsAndHashCode;
import org.simplify4u.plugins.pgp.KeyFingerprint;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.utils.HexUtils;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* Represent key as fingerprint for given artifact pattern.
*/
@EqualsAndHashCode
class KeyItemFingerprint implements KeyItem {
private final byte[] fingerPrint;
public KeyItemFingerprint(String key) { | fingerPrint = stringToFingerprint(key); |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/keysmap/KeyItemFingerprint.java | // Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// @UtilityClass
// public class HexUtils {
//
// /**
// * Convert byte array of fingerprint to string of hex
// * @param bytes fingerprint
// * @return fingerprint as string
// */
// public static String fingerprintToString(byte[] bytes) {
// StringBuilder ret = new StringBuilder();
// ret.append("0x");
// for (byte b : bytes) {
// ret.append(String.format("%02X", b));
// }
// return ret.toString();
// }
//
// /**
// * Convert fingerprint in string format to byte array.
// * @param key fingerprint as string
// * @return fingerprint as byte array
// */
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
// }
| import java.util.Optional;
import static org.simplify4u.plugins.utils.HexUtils.stringToFingerprint;
import lombok.EqualsAndHashCode;
import org.simplify4u.plugins.pgp.KeyFingerprint;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.utils.HexUtils; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* Represent key as fingerprint for given artifact pattern.
*/
@EqualsAndHashCode
class KeyItemFingerprint implements KeyItem {
private final byte[] fingerPrint;
public KeyItemFingerprint(String key) {
fingerPrint = stringToFingerprint(key);
}
@Override | // Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// @UtilityClass
// public class HexUtils {
//
// /**
// * Convert byte array of fingerprint to string of hex
// * @param bytes fingerprint
// * @return fingerprint as string
// */
// public static String fingerprintToString(byte[] bytes) {
// StringBuilder ret = new StringBuilder();
// ret.append("0x");
// for (byte b : bytes) {
// ret.append(String.format("%02X", b));
// }
// return ret.toString();
// }
//
// /**
// * Convert fingerprint in string format to byte array.
// * @param key fingerprint as string
// * @return fingerprint as byte array
// */
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
// }
// Path: src/main/java/org/simplify4u/plugins/keysmap/KeyItemFingerprint.java
import java.util.Optional;
import static org.simplify4u.plugins.utils.HexUtils.stringToFingerprint;
import lombok.EqualsAndHashCode;
import org.simplify4u.plugins.pgp.KeyFingerprint;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.utils.HexUtils;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* Represent key as fingerprint for given artifact pattern.
*/
@EqualsAndHashCode
class KeyItemFingerprint implements KeyItem {
private final byte[] fingerPrint;
public KeyItemFingerprint(String key) {
fingerPrint = stringToFingerprint(key);
}
@Override | public boolean isKeyMatch(KeyInfo keyInfo) { |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/keysmap/KeyItemFingerprint.java | // Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// @UtilityClass
// public class HexUtils {
//
// /**
// * Convert byte array of fingerprint to string of hex
// * @param bytes fingerprint
// * @return fingerprint as string
// */
// public static String fingerprintToString(byte[] bytes) {
// StringBuilder ret = new StringBuilder();
// ret.append("0x");
// for (byte b : bytes) {
// ret.append(String.format("%02X", b));
// }
// return ret.toString();
// }
//
// /**
// * Convert fingerprint in string format to byte array.
// * @param key fingerprint as string
// * @return fingerprint as byte array
// */
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
// }
| import java.util.Optional;
import static org.simplify4u.plugins.utils.HexUtils.stringToFingerprint;
import lombok.EqualsAndHashCode;
import org.simplify4u.plugins.pgp.KeyFingerprint;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.utils.HexUtils; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* Represent key as fingerprint for given artifact pattern.
*/
@EqualsAndHashCode
class KeyItemFingerprint implements KeyItem {
private final byte[] fingerPrint;
public KeyItemFingerprint(String key) {
fingerPrint = stringToFingerprint(key);
}
@Override
public boolean isKeyMatch(KeyInfo keyInfo) {
return compareWith(keyInfo.getMaster()) || compareWith(keyInfo.getFingerprint()) ;
}
| // Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// @UtilityClass
// public class HexUtils {
//
// /**
// * Convert byte array of fingerprint to string of hex
// * @param bytes fingerprint
// * @return fingerprint as string
// */
// public static String fingerprintToString(byte[] bytes) {
// StringBuilder ret = new StringBuilder();
// ret.append("0x");
// for (byte b : bytes) {
// ret.append(String.format("%02X", b));
// }
// return ret.toString();
// }
//
// /**
// * Convert fingerprint in string format to byte array.
// * @param key fingerprint as string
// * @return fingerprint as byte array
// */
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
// }
// Path: src/main/java/org/simplify4u/plugins/keysmap/KeyItemFingerprint.java
import java.util.Optional;
import static org.simplify4u.plugins.utils.HexUtils.stringToFingerprint;
import lombok.EqualsAndHashCode;
import org.simplify4u.plugins.pgp.KeyFingerprint;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.utils.HexUtils;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* Represent key as fingerprint for given artifact pattern.
*/
@EqualsAndHashCode
class KeyItemFingerprint implements KeyItem {
private final byte[] fingerPrint;
public KeyItemFingerprint(String key) {
fingerPrint = stringToFingerprint(key);
}
@Override
public boolean isKeyMatch(KeyInfo keyInfo) {
return compareWith(keyInfo.getMaster()) || compareWith(keyInfo.getFingerprint()) ;
}
| private boolean compareWith(KeyFingerprint fingerprint) { |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/keysmap/KeyItemFingerprint.java | // Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// @UtilityClass
// public class HexUtils {
//
// /**
// * Convert byte array of fingerprint to string of hex
// * @param bytes fingerprint
// * @return fingerprint as string
// */
// public static String fingerprintToString(byte[] bytes) {
// StringBuilder ret = new StringBuilder();
// ret.append("0x");
// for (byte b : bytes) {
// ret.append(String.format("%02X", b));
// }
// return ret.toString();
// }
//
// /**
// * Convert fingerprint in string format to byte array.
// * @param key fingerprint as string
// * @return fingerprint as byte array
// */
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
// }
| import java.util.Optional;
import static org.simplify4u.plugins.utils.HexUtils.stringToFingerprint;
import lombok.EqualsAndHashCode;
import org.simplify4u.plugins.pgp.KeyFingerprint;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.utils.HexUtils; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* Represent key as fingerprint for given artifact pattern.
*/
@EqualsAndHashCode
class KeyItemFingerprint implements KeyItem {
private final byte[] fingerPrint;
public KeyItemFingerprint(String key) {
fingerPrint = stringToFingerprint(key);
}
@Override
public boolean isKeyMatch(KeyInfo keyInfo) {
return compareWith(keyInfo.getMaster()) || compareWith(keyInfo.getFingerprint()) ;
}
private boolean compareWith(KeyFingerprint fingerprint) {
return Optional.ofNullable(fingerprint)
.map(KeyFingerprint::getFingerprint)
.map(this::compareWith)
.orElse(false);
}
private boolean compareWith(byte[] keyBytes) {
for (int i = 1; i <= fingerPrint.length && i <= keyBytes.length; i++) {
if (fingerPrint[fingerPrint.length - i] != keyBytes[keyBytes.length - i]) {
return false;
}
}
return true;
}
@Override
public String toString() { | // Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
//
// Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// @UtilityClass
// public class HexUtils {
//
// /**
// * Convert byte array of fingerprint to string of hex
// * @param bytes fingerprint
// * @return fingerprint as string
// */
// public static String fingerprintToString(byte[] bytes) {
// StringBuilder ret = new StringBuilder();
// ret.append("0x");
// for (byte b : bytes) {
// ret.append(String.format("%02X", b));
// }
// return ret.toString();
// }
//
// /**
// * Convert fingerprint in string format to byte array.
// * @param key fingerprint as string
// * @return fingerprint as byte array
// */
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
// }
// Path: src/main/java/org/simplify4u/plugins/keysmap/KeyItemFingerprint.java
import java.util.Optional;
import static org.simplify4u.plugins.utils.HexUtils.stringToFingerprint;
import lombok.EqualsAndHashCode;
import org.simplify4u.plugins.pgp.KeyFingerprint;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.simplify4u.plugins.utils.HexUtils;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* Represent key as fingerprint for given artifact pattern.
*/
@EqualsAndHashCode
class KeyItemFingerprint implements KeyItem {
private final byte[] fingerPrint;
public KeyItemFingerprint(String key) {
fingerPrint = stringToFingerprint(key);
}
@Override
public boolean isKeyMatch(KeyInfo keyInfo) {
return compareWith(keyInfo.getMaster()) || compareWith(keyInfo.getFingerprint()) ;
}
private boolean compareWith(KeyFingerprint fingerprint) {
return Optional.ofNullable(fingerprint)
.map(KeyFingerprint::getFingerprint)
.map(this::compareWith)
.orElse(false);
}
private boolean compareWith(byte[] keyBytes) {
for (int i = 1; i <= fingerPrint.length && i <= keyBytes.length; i++) {
if (fingerPrint[fingerPrint.length - i] != keyBytes[keyBytes.length - i]) {
return false;
}
}
return true;
}
@Override
public String toString() { | return HexUtils.fingerprintToString(fingerPrint); |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/pgp/KeyId.java | // Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// public static String fingerprintToString(byte[] bytes) {
// StringBuilder ret = new StringBuilder();
// ret.append("0x");
// for (byte b : bytes) {
// ret.append(String.format("%02X", b));
// }
// return ret.toString();
// }
| import static org.simplify4u.plugins.utils.HexUtils.fingerprintToString;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.EqualsAndHashCode;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection; | KeyIdFingerprint(byte[] fingerprint) {
this.fingerprint = fingerprint;
}
@Override
public String getHashPath() {
StringBuilder ret = new StringBuilder();
ret.append(String.format("%02X/", fingerprint[0]));
ret.append(String.format("%02X/", fingerprint[1]));
for (byte b: fingerprint) {
ret.append(String.format("%02X", b));
}
ret.append(".asc");
return ret.toString();
}
@Override
public PGPPublicKey getKeyFromRing(PGPPublicKeyRing publicKeyRing) {
return publicKeyRing.getPublicKey(fingerprint);
}
@Override
public PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection)
throws PGPException {
return pgpRingCollection.getPublicKeyRing(fingerprint);
}
@Override
@JsonValue
public String toString() { | // Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// public static String fingerprintToString(byte[] bytes) {
// StringBuilder ret = new StringBuilder();
// ret.append("0x");
// for (byte b : bytes) {
// ret.append(String.format("%02X", b));
// }
// return ret.toString();
// }
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyId.java
import static org.simplify4u.plugins.utils.HexUtils.fingerprintToString;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.EqualsAndHashCode;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
KeyIdFingerprint(byte[] fingerprint) {
this.fingerprint = fingerprint;
}
@Override
public String getHashPath() {
StringBuilder ret = new StringBuilder();
ret.append(String.format("%02X/", fingerprint[0]));
ret.append(String.format("%02X/", fingerprint[1]));
for (byte b: fingerprint) {
ret.append(String.format("%02X", b));
}
ret.append(".asc");
return ret.toString();
}
@Override
public PGPPublicKey getKeyFromRing(PGPPublicKeyRing publicKeyRing) {
return publicKeyRing.getPublicKey(fingerprint);
}
@Override
public PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection)
throws PGPException {
return pgpRingCollection.getPublicKeyRing(fingerprint);
}
@Override
@JsonValue
public String toString() { | return fingerprintToString(fingerprint); |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/keysmap/KeyItemAnyKey.java | // Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
| import lombok.EqualsAndHashCode;
import org.simplify4u.plugins.pgp.KeyInfo; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* Special key value.
* <p>
* Given artifact pattern can has any kay.
*/
@EqualsAndHashCode
class KeyItemAnyKey implements KeyItem {
public static final String DESC = "any";
@Override | // Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
// Path: src/main/java/org/simplify4u/plugins/keysmap/KeyItemAnyKey.java
import lombok.EqualsAndHashCode;
import org.simplify4u.plugins.pgp.KeyInfo;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* Special key value.
* <p>
* Given artifact pattern can has any kay.
*/
@EqualsAndHashCode
class KeyItemAnyKey implements KeyItem {
public static final String DESC = "any";
@Override | public boolean isKeyMatch(KeyInfo keyInfo) { |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/keysmap/KeysMapTest.java | // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeyInfo aKeyInfo(String fingerprint) {
// return KeyInfo.builder().fingerprint(new KeyFingerprint(fingerprint)).build();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeysMapLocationConfig aKeysMapLocationConfig(String location) {
// KeysMapLocationConfig config = new KeysMapLocationConfig();
// config.set(location);
// return config;
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import static org.simplify4u.plugins.TestUtils.aKeyInfo;
import static org.simplify4u.plugins.TestUtils.aKeysMapLocationConfig;
import org.codehaus.plexus.resource.ResourceManager;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.slf4j.Logger;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test; | /*
* Copyright 2020 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* @author Slawomir Jaranowski.
*/
@Listeners(MockitoTestNGListener.class)
public class KeysMapTest {
@Mock
private ResourceManager resourceManager;
@Mock(name = "org.simplify4u.plugins.keysmap.KeysMap")
private Logger loggerKeysMap;
@Mock(name = "org.simplify4u.plugins.keysmap.KeyItems")
private Logger loggerKeyItems;
@InjectMocks
private KeysMap keysMap;
@Test
public void isComponentSet() {
assertThat(keysMap).isNotNull();
}
@Test
public void nullLocationTest() throws Exception {
assertThatThrownBy(() -> keysMap.load(null))
.isExactlyInstanceOf(NullPointerException.class);
verifyNoInteractions(resourceManager); | // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeyInfo aKeyInfo(String fingerprint) {
// return KeyInfo.builder().fingerprint(new KeyFingerprint(fingerprint)).build();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeysMapLocationConfig aKeysMapLocationConfig(String location) {
// KeysMapLocationConfig config = new KeysMapLocationConfig();
// config.set(location);
// return config;
// }
// Path: src/test/java/org/simplify4u/plugins/keysmap/KeysMapTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import static org.simplify4u.plugins.TestUtils.aKeyInfo;
import static org.simplify4u.plugins.TestUtils.aKeysMapLocationConfig;
import org.codehaus.plexus.resource.ResourceManager;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.slf4j.Logger;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
/*
* Copyright 2020 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* @author Slawomir Jaranowski.
*/
@Listeners(MockitoTestNGListener.class)
public class KeysMapTest {
@Mock
private ResourceManager resourceManager;
@Mock(name = "org.simplify4u.plugins.keysmap.KeysMap")
private Logger loggerKeysMap;
@Mock(name = "org.simplify4u.plugins.keysmap.KeyItems")
private Logger loggerKeyItems;
@InjectMocks
private KeysMap keysMap;
@Test
public void isComponentSet() {
assertThat(keysMap).isNotNull();
}
@Test
public void nullLocationTest() throws Exception {
assertThatThrownBy(() -> keysMap.load(null))
.isExactlyInstanceOf(NullPointerException.class);
verifyNoInteractions(resourceManager); | assertThat(keysMap.isValidKey(testArtifact().build(), null)).isTrue(); |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/keysmap/KeysMapTest.java | // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeyInfo aKeyInfo(String fingerprint) {
// return KeyInfo.builder().fingerprint(new KeyFingerprint(fingerprint)).build();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeysMapLocationConfig aKeysMapLocationConfig(String location) {
// KeysMapLocationConfig config = new KeysMapLocationConfig();
// config.set(location);
// return config;
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import static org.simplify4u.plugins.TestUtils.aKeyInfo;
import static org.simplify4u.plugins.TestUtils.aKeysMapLocationConfig;
import org.codehaus.plexus.resource.ResourceManager;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.slf4j.Logger;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test; | /*
* Copyright 2020 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* @author Slawomir Jaranowski.
*/
@Listeners(MockitoTestNGListener.class)
public class KeysMapTest {
@Mock
private ResourceManager resourceManager;
@Mock(name = "org.simplify4u.plugins.keysmap.KeysMap")
private Logger loggerKeysMap;
@Mock(name = "org.simplify4u.plugins.keysmap.KeyItems")
private Logger loggerKeyItems;
@InjectMocks
private KeysMap keysMap;
@Test
public void isComponentSet() {
assertThat(keysMap).isNotNull();
}
@Test
public void nullLocationTest() throws Exception {
assertThatThrownBy(() -> keysMap.load(null))
.isExactlyInstanceOf(NullPointerException.class);
verifyNoInteractions(resourceManager);
assertThat(keysMap.isValidKey(testArtifact().build(), null)).isTrue();
}
@Test
public void emptyLocationTest() throws Exception { | // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeyInfo aKeyInfo(String fingerprint) {
// return KeyInfo.builder().fingerprint(new KeyFingerprint(fingerprint)).build();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeysMapLocationConfig aKeysMapLocationConfig(String location) {
// KeysMapLocationConfig config = new KeysMapLocationConfig();
// config.set(location);
// return config;
// }
// Path: src/test/java/org/simplify4u/plugins/keysmap/KeysMapTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import static org.simplify4u.plugins.TestUtils.aKeyInfo;
import static org.simplify4u.plugins.TestUtils.aKeysMapLocationConfig;
import org.codehaus.plexus.resource.ResourceManager;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.slf4j.Logger;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
/*
* Copyright 2020 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* @author Slawomir Jaranowski.
*/
@Listeners(MockitoTestNGListener.class)
public class KeysMapTest {
@Mock
private ResourceManager resourceManager;
@Mock(name = "org.simplify4u.plugins.keysmap.KeysMap")
private Logger loggerKeysMap;
@Mock(name = "org.simplify4u.plugins.keysmap.KeyItems")
private Logger loggerKeyItems;
@InjectMocks
private KeysMap keysMap;
@Test
public void isComponentSet() {
assertThat(keysMap).isNotNull();
}
@Test
public void nullLocationTest() throws Exception {
assertThatThrownBy(() -> keysMap.load(null))
.isExactlyInstanceOf(NullPointerException.class);
verifyNoInteractions(resourceManager);
assertThat(keysMap.isValidKey(testArtifact().build(), null)).isTrue();
}
@Test
public void emptyLocationTest() throws Exception { | keysMap.load(aKeysMapLocationConfig("")); |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/keysmap/KeysMapTest.java | // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeyInfo aKeyInfo(String fingerprint) {
// return KeyInfo.builder().fingerprint(new KeyFingerprint(fingerprint)).build();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeysMapLocationConfig aKeysMapLocationConfig(String location) {
// KeysMapLocationConfig config = new KeysMapLocationConfig();
// config.set(location);
// return config;
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import static org.simplify4u.plugins.TestUtils.aKeyInfo;
import static org.simplify4u.plugins.TestUtils.aKeysMapLocationConfig;
import org.codehaus.plexus.resource.ResourceManager;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.slf4j.Logger;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test; | public void nullLocationTest() throws Exception {
assertThatThrownBy(() -> keysMap.load(null))
.isExactlyInstanceOf(NullPointerException.class);
verifyNoInteractions(resourceManager);
assertThat(keysMap.isValidKey(testArtifact().build(), null)).isTrue();
}
@Test
public void emptyLocationTest() throws Exception {
keysMap.load(aKeysMapLocationConfig(""));
verifyNoInteractions(resourceManager);
assertThat(keysMap.isValidKey(testArtifact().build(), null)).isTrue();
}
@Test
public void validKeyFromMap() throws Exception {
doAnswer(invocation -> getClass().getResourceAsStream(invocation.getArgument(0)))
.when(resourceManager).getResourceAsInputStream(anyString());
keysMap.load(aKeysMapLocationConfig("/keysMap.list"));
verify(resourceManager).getResourceAsInputStream(anyString());
assertThat(
keysMap.isValidKey(
testArtifact().groupId("junit").artifactId("junit").version("4.12").build(), | // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeyInfo aKeyInfo(String fingerprint) {
// return KeyInfo.builder().fingerprint(new KeyFingerprint(fingerprint)).build();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeysMapLocationConfig aKeysMapLocationConfig(String location) {
// KeysMapLocationConfig config = new KeysMapLocationConfig();
// config.set(location);
// return config;
// }
// Path: src/test/java/org/simplify4u/plugins/keysmap/KeysMapTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import static org.simplify4u.plugins.TestUtils.aKeyInfo;
import static org.simplify4u.plugins.TestUtils.aKeysMapLocationConfig;
import org.codehaus.plexus.resource.ResourceManager;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.slf4j.Logger;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
public void nullLocationTest() throws Exception {
assertThatThrownBy(() -> keysMap.load(null))
.isExactlyInstanceOf(NullPointerException.class);
verifyNoInteractions(resourceManager);
assertThat(keysMap.isValidKey(testArtifact().build(), null)).isTrue();
}
@Test
public void emptyLocationTest() throws Exception {
keysMap.load(aKeysMapLocationConfig(""));
verifyNoInteractions(resourceManager);
assertThat(keysMap.isValidKey(testArtifact().build(), null)).isTrue();
}
@Test
public void validKeyFromMap() throws Exception {
doAnswer(invocation -> getClass().getResourceAsStream(invocation.getArgument(0)))
.when(resourceManager).getResourceAsInputStream(anyString());
keysMap.load(aKeysMapLocationConfig("/keysMap.list"));
verify(resourceManager).getResourceAsInputStream(anyString());
assertThat(
keysMap.isValidKey(
testArtifact().groupId("junit").artifactId("junit").version("4.12").build(), | aKeyInfo("0x123456789abcdef0")) |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/utils/MavenCompilerUtilsTest.java | // Path: src/main/java/org/simplify4u/plugins/utils/MavenCompilerUtils.java
// public static boolean checkCompilerPlugin(Plugin plugin) {
// return GROUPID.equals(plugin.getGroupId()) && ARTIFACTID.equals(plugin.getArtifactId());
// }
//
// Path: src/main/java/org/simplify4u/plugins/utils/MavenCompilerUtils.java
// public static Set<Artifact> extractAnnotationProcessors(RepositorySystem system, Plugin plugin) {
// requireNonNull(system);
// if (!checkCompilerPlugin(plugin)) {
// throw new IllegalArgumentException("Plugin is not '" + GROUPID + ":" + ARTIFACTID + "'.");
// }
// final Object config = plugin.getConfiguration();
// if (config == null) {
// return emptySet();
// }
// if (config instanceof Xpp3Dom) {
// return stream(((Xpp3Dom) config).getChildren("annotationProcessorPaths"))
// .flatMap(aggregate -> stream(aggregate.getChildren("path")))
// .map(processor -> system.createArtifact(
// extractChildValue(processor, "groupId"),
// extractChildValue(processor, "artifactId"),
// extractChildValue(processor, "version"),
// PACKAGING))
// // A path specification is automatically ignored in maven-compiler-plugin if version is absent,
// // therefore there is little use in logging incomplete paths that are filtered out.
// .filter(a -> !a.getGroupId().isEmpty())
// .filter(a -> !a.getArtifactId().isEmpty())
// .filter(a -> !a.getVersion().isEmpty())
// .collect(Collectors.toSet());
// }
// // It is expected that this will never occur due to all Configuration instances of all plugins being provided as
// // XML document. If this happens to occur on very old plugin versions, we can safely add the type support and
// // simply return an empty set.
// throw new UnsupportedOperationException("Please report that an unsupported type of configuration container" +
// " was encountered: " + config.getClass());
// }
| import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertThrows;
import static org.testng.Assert.assertTrue;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Plugin;
import org.apache.maven.repository.RepositorySystem;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.testng.annotations.Test;
import java.util.Set;
import static java.util.Collections.emptySet;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.simplify4u.plugins.utils.MavenCompilerUtils.checkCompilerPlugin;
import static org.simplify4u.plugins.utils.MavenCompilerUtils.extractAnnotationProcessors;
import static org.testng.Assert.assertEquals; | /*
* Copyright 2019 Danny van Heumen
*
* 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 org.simplify4u.plugins.utils;
@SuppressWarnings({"ConstantConditions", "SameParameterValue"})
public final class MavenCompilerUtilsTest {
@Test
public void testCheckCompilerPlugin() { | // Path: src/main/java/org/simplify4u/plugins/utils/MavenCompilerUtils.java
// public static boolean checkCompilerPlugin(Plugin plugin) {
// return GROUPID.equals(plugin.getGroupId()) && ARTIFACTID.equals(plugin.getArtifactId());
// }
//
// Path: src/main/java/org/simplify4u/plugins/utils/MavenCompilerUtils.java
// public static Set<Artifact> extractAnnotationProcessors(RepositorySystem system, Plugin plugin) {
// requireNonNull(system);
// if (!checkCompilerPlugin(plugin)) {
// throw new IllegalArgumentException("Plugin is not '" + GROUPID + ":" + ARTIFACTID + "'.");
// }
// final Object config = plugin.getConfiguration();
// if (config == null) {
// return emptySet();
// }
// if (config instanceof Xpp3Dom) {
// return stream(((Xpp3Dom) config).getChildren("annotationProcessorPaths"))
// .flatMap(aggregate -> stream(aggregate.getChildren("path")))
// .map(processor -> system.createArtifact(
// extractChildValue(processor, "groupId"),
// extractChildValue(processor, "artifactId"),
// extractChildValue(processor, "version"),
// PACKAGING))
// // A path specification is automatically ignored in maven-compiler-plugin if version is absent,
// // therefore there is little use in logging incomplete paths that are filtered out.
// .filter(a -> !a.getGroupId().isEmpty())
// .filter(a -> !a.getArtifactId().isEmpty())
// .filter(a -> !a.getVersion().isEmpty())
// .collect(Collectors.toSet());
// }
// // It is expected that this will never occur due to all Configuration instances of all plugins being provided as
// // XML document. If this happens to occur on very old plugin versions, we can safely add the type support and
// // simply return an empty set.
// throw new UnsupportedOperationException("Please report that an unsupported type of configuration container" +
// " was encountered: " + config.getClass());
// }
// Path: src/test/java/org/simplify4u/plugins/utils/MavenCompilerUtilsTest.java
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertThrows;
import static org.testng.Assert.assertTrue;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Plugin;
import org.apache.maven.repository.RepositorySystem;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.testng.annotations.Test;
import java.util.Set;
import static java.util.Collections.emptySet;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.simplify4u.plugins.utils.MavenCompilerUtils.checkCompilerPlugin;
import static org.simplify4u.plugins.utils.MavenCompilerUtils.extractAnnotationProcessors;
import static org.testng.Assert.assertEquals;
/*
* Copyright 2019 Danny van Heumen
*
* 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 org.simplify4u.plugins.utils;
@SuppressWarnings({"ConstantConditions", "SameParameterValue"})
public final class MavenCompilerUtilsTest {
@Test
public void testCheckCompilerPlugin() { | assertThrows(NullPointerException.class, () -> checkCompilerPlugin(null)); |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/utils/MavenCompilerUtilsTest.java | // Path: src/main/java/org/simplify4u/plugins/utils/MavenCompilerUtils.java
// public static boolean checkCompilerPlugin(Plugin plugin) {
// return GROUPID.equals(plugin.getGroupId()) && ARTIFACTID.equals(plugin.getArtifactId());
// }
//
// Path: src/main/java/org/simplify4u/plugins/utils/MavenCompilerUtils.java
// public static Set<Artifact> extractAnnotationProcessors(RepositorySystem system, Plugin plugin) {
// requireNonNull(system);
// if (!checkCompilerPlugin(plugin)) {
// throw new IllegalArgumentException("Plugin is not '" + GROUPID + ":" + ARTIFACTID + "'.");
// }
// final Object config = plugin.getConfiguration();
// if (config == null) {
// return emptySet();
// }
// if (config instanceof Xpp3Dom) {
// return stream(((Xpp3Dom) config).getChildren("annotationProcessorPaths"))
// .flatMap(aggregate -> stream(aggregate.getChildren("path")))
// .map(processor -> system.createArtifact(
// extractChildValue(processor, "groupId"),
// extractChildValue(processor, "artifactId"),
// extractChildValue(processor, "version"),
// PACKAGING))
// // A path specification is automatically ignored in maven-compiler-plugin if version is absent,
// // therefore there is little use in logging incomplete paths that are filtered out.
// .filter(a -> !a.getGroupId().isEmpty())
// .filter(a -> !a.getArtifactId().isEmpty())
// .filter(a -> !a.getVersion().isEmpty())
// .collect(Collectors.toSet());
// }
// // It is expected that this will never occur due to all Configuration instances of all plugins being provided as
// // XML document. If this happens to occur on very old plugin versions, we can safely add the type support and
// // simply return an empty set.
// throw new UnsupportedOperationException("Please report that an unsupported type of configuration container" +
// " was encountered: " + config.getClass());
// }
| import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertThrows;
import static org.testng.Assert.assertTrue;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Plugin;
import org.apache.maven.repository.RepositorySystem;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.testng.annotations.Test;
import java.util.Set;
import static java.util.Collections.emptySet;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.simplify4u.plugins.utils.MavenCompilerUtils.checkCompilerPlugin;
import static org.simplify4u.plugins.utils.MavenCompilerUtils.extractAnnotationProcessors;
import static org.testng.Assert.assertEquals; | /*
* Copyright 2019 Danny van Heumen
*
* 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 org.simplify4u.plugins.utils;
@SuppressWarnings({"ConstantConditions", "SameParameterValue"})
public final class MavenCompilerUtilsTest {
@Test
public void testCheckCompilerPlugin() {
assertThrows(NullPointerException.class, () -> checkCompilerPlugin(null));
final Plugin compilerPlugin = mock(Plugin.class);
when(compilerPlugin.getGroupId()).thenReturn("org.apache.maven.plugins");
when(compilerPlugin.getArtifactId()).thenReturn("maven-compiler-plugin");
when(compilerPlugin.getVersion()).thenReturn("3.8.1");
assertTrue(checkCompilerPlugin(compilerPlugin));
final Plugin otherPlugin = mock(Plugin.class);
when(otherPlugin.getGroupId()).thenReturn("org.apache.maven.plugin");
when(otherPlugin.getArtifactId()).thenReturn("some-other-plugin");
when(otherPlugin.getVersion()).thenReturn("3.5.9");
assertFalse(checkCompilerPlugin(otherPlugin));
}
@Test
public void testExtractAnnotationProcessorsIllegalInputs() { | // Path: src/main/java/org/simplify4u/plugins/utils/MavenCompilerUtils.java
// public static boolean checkCompilerPlugin(Plugin plugin) {
// return GROUPID.equals(plugin.getGroupId()) && ARTIFACTID.equals(plugin.getArtifactId());
// }
//
// Path: src/main/java/org/simplify4u/plugins/utils/MavenCompilerUtils.java
// public static Set<Artifact> extractAnnotationProcessors(RepositorySystem system, Plugin plugin) {
// requireNonNull(system);
// if (!checkCompilerPlugin(plugin)) {
// throw new IllegalArgumentException("Plugin is not '" + GROUPID + ":" + ARTIFACTID + "'.");
// }
// final Object config = plugin.getConfiguration();
// if (config == null) {
// return emptySet();
// }
// if (config instanceof Xpp3Dom) {
// return stream(((Xpp3Dom) config).getChildren("annotationProcessorPaths"))
// .flatMap(aggregate -> stream(aggregate.getChildren("path")))
// .map(processor -> system.createArtifact(
// extractChildValue(processor, "groupId"),
// extractChildValue(processor, "artifactId"),
// extractChildValue(processor, "version"),
// PACKAGING))
// // A path specification is automatically ignored in maven-compiler-plugin if version is absent,
// // therefore there is little use in logging incomplete paths that are filtered out.
// .filter(a -> !a.getGroupId().isEmpty())
// .filter(a -> !a.getArtifactId().isEmpty())
// .filter(a -> !a.getVersion().isEmpty())
// .collect(Collectors.toSet());
// }
// // It is expected that this will never occur due to all Configuration instances of all plugins being provided as
// // XML document. If this happens to occur on very old plugin versions, we can safely add the type support and
// // simply return an empty set.
// throw new UnsupportedOperationException("Please report that an unsupported type of configuration container" +
// " was encountered: " + config.getClass());
// }
// Path: src/test/java/org/simplify4u/plugins/utils/MavenCompilerUtilsTest.java
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertThrows;
import static org.testng.Assert.assertTrue;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Plugin;
import org.apache.maven.repository.RepositorySystem;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.testng.annotations.Test;
import java.util.Set;
import static java.util.Collections.emptySet;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.simplify4u.plugins.utils.MavenCompilerUtils.checkCompilerPlugin;
import static org.simplify4u.plugins.utils.MavenCompilerUtils.extractAnnotationProcessors;
import static org.testng.Assert.assertEquals;
/*
* Copyright 2019 Danny van Heumen
*
* 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 org.simplify4u.plugins.utils;
@SuppressWarnings({"ConstantConditions", "SameParameterValue"})
public final class MavenCompilerUtilsTest {
@Test
public void testCheckCompilerPlugin() {
assertThrows(NullPointerException.class, () -> checkCompilerPlugin(null));
final Plugin compilerPlugin = mock(Plugin.class);
when(compilerPlugin.getGroupId()).thenReturn("org.apache.maven.plugins");
when(compilerPlugin.getArtifactId()).thenReturn("maven-compiler-plugin");
when(compilerPlugin.getVersion()).thenReturn("3.8.1");
assertTrue(checkCompilerPlugin(compilerPlugin));
final Plugin otherPlugin = mock(Plugin.class);
when(otherPlugin.getGroupId()).thenReturn("org.apache.maven.plugin");
when(otherPlugin.getArtifactId()).thenReturn("some-other-plugin");
when(otherPlugin.getVersion()).thenReturn("3.5.9");
assertFalse(checkCompilerPlugin(otherPlugin));
}
@Test
public void testExtractAnnotationProcessorsIllegalInputs() { | assertThrows(NullPointerException.class, () -> extractAnnotationProcessors(null, null)); |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/keysmap/KeysMapMultiTest.java | // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeysMapLocationConfig aKeysMapLocationConfig(String location) {
// KeysMapLocationConfig config = new KeysMapLocationConfig();
// config.set(location);
// return config;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
| import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import static org.simplify4u.plugins.TestUtils.aKeysMapLocationConfig;
import org.apache.maven.artifact.Artifact;
import org.codehaus.plexus.resource.ResourceManager;
import org.codehaus.plexus.resource.loader.ResourceNotFoundException;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.pgp.KeyFingerprint; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
@Listeners(MockitoTestNGListener.class)
public class KeysMapMultiTest {
@Mock
private ResourceManager resourceManager;
@InjectMocks
private KeysMap keysMap;
@BeforeMethod
public void setup() throws ResourceNotFoundException {
doAnswer(invocation -> getClass().getResourceAsStream(invocation.getArgument(0)))
.when(resourceManager).getResourceAsInputStream(anyString());
}
@Test
public void loadMultipleKeysMapShouldContainsAllItems() throws ResourceNotFoundException, IOException {
| // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeysMapLocationConfig aKeysMapLocationConfig(String location) {
// KeysMapLocationConfig config = new KeysMapLocationConfig();
// config.set(location);
// return config;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
// Path: src/test/java/org/simplify4u/plugins/keysmap/KeysMapMultiTest.java
import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import static org.simplify4u.plugins.TestUtils.aKeysMapLocationConfig;
import org.apache.maven.artifact.Artifact;
import org.codehaus.plexus.resource.ResourceManager;
import org.codehaus.plexus.resource.loader.ResourceNotFoundException;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.pgp.KeyFingerprint;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
@Listeners(MockitoTestNGListener.class)
public class KeysMapMultiTest {
@Mock
private ResourceManager resourceManager;
@InjectMocks
private KeysMap keysMap;
@BeforeMethod
public void setup() throws ResourceNotFoundException {
doAnswer(invocation -> getClass().getResourceAsStream(invocation.getArgument(0)))
.when(resourceManager).getResourceAsInputStream(anyString());
}
@Test
public void loadMultipleKeysMapShouldContainsAllItems() throws ResourceNotFoundException, IOException {
| keysMap.load(aKeysMapLocationConfig("/keysMapMulti1.list")); |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/keysmap/KeysMapMultiTest.java | // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeysMapLocationConfig aKeysMapLocationConfig(String location) {
// KeysMapLocationConfig config = new KeysMapLocationConfig();
// config.set(location);
// return config;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
| import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import static org.simplify4u.plugins.TestUtils.aKeysMapLocationConfig;
import org.apache.maven.artifact.Artifact;
import org.codehaus.plexus.resource.ResourceManager;
import org.codehaus.plexus.resource.loader.ResourceNotFoundException;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.pgp.KeyFingerprint; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
@Listeners(MockitoTestNGListener.class)
public class KeysMapMultiTest {
@Mock
private ResourceManager resourceManager;
@InjectMocks
private KeysMap keysMap;
@BeforeMethod
public void setup() throws ResourceNotFoundException {
doAnswer(invocation -> getClass().getResourceAsStream(invocation.getArgument(0)))
.when(resourceManager).getResourceAsInputStream(anyString());
}
@Test
public void loadMultipleKeysMapShouldContainsAllItems() throws ResourceNotFoundException, IOException {
keysMap.load(aKeysMapLocationConfig("/keysMapMulti1.list"));
keysMap.load(aKeysMapLocationConfig("/keysMapMulti2.list"));
assertThat(keysMap.size()).isEqualTo(9);
}
@DataProvider
public static Object[][] artifactWithKeyToTest() {
return new Object[][]{ | // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeysMapLocationConfig aKeysMapLocationConfig(String location) {
// KeysMapLocationConfig config = new KeysMapLocationConfig();
// config.set(location);
// return config;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
// Path: src/test/java/org/simplify4u/plugins/keysmap/KeysMapMultiTest.java
import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import static org.simplify4u.plugins.TestUtils.aKeysMapLocationConfig;
import org.apache.maven.artifact.Artifact;
import org.codehaus.plexus.resource.ResourceManager;
import org.codehaus.plexus.resource.loader.ResourceNotFoundException;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.pgp.KeyFingerprint;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
@Listeners(MockitoTestNGListener.class)
public class KeysMapMultiTest {
@Mock
private ResourceManager resourceManager;
@InjectMocks
private KeysMap keysMap;
@BeforeMethod
public void setup() throws ResourceNotFoundException {
doAnswer(invocation -> getClass().getResourceAsStream(invocation.getArgument(0)))
.when(resourceManager).getResourceAsInputStream(anyString());
}
@Test
public void loadMultipleKeysMapShouldContainsAllItems() throws ResourceNotFoundException, IOException {
keysMap.load(aKeysMapLocationConfig("/keysMapMulti1.list"));
keysMap.load(aKeysMapLocationConfig("/keysMapMulti2.list"));
assertThat(keysMap.size()).isEqualTo(9);
}
@DataProvider
public static Object[][] artifactWithKeyToTest() {
return new Object[][]{ | {testArtifact().build(), |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/keysmap/KeysMapMultiTest.java | // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeysMapLocationConfig aKeysMapLocationConfig(String location) {
// KeysMapLocationConfig config = new KeysMapLocationConfig();
// config.set(location);
// return config;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
| import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import static org.simplify4u.plugins.TestUtils.aKeysMapLocationConfig;
import org.apache.maven.artifact.Artifact;
import org.codehaus.plexus.resource.ResourceManager;
import org.codehaus.plexus.resource.loader.ResourceNotFoundException;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.pgp.KeyFingerprint; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
@Listeners(MockitoTestNGListener.class)
public class KeysMapMultiTest {
@Mock
private ResourceManager resourceManager;
@InjectMocks
private KeysMap keysMap;
@BeforeMethod
public void setup() throws ResourceNotFoundException {
doAnswer(invocation -> getClass().getResourceAsStream(invocation.getArgument(0)))
.when(resourceManager).getResourceAsInputStream(anyString());
}
@Test
public void loadMultipleKeysMapShouldContainsAllItems() throws ResourceNotFoundException, IOException {
keysMap.load(aKeysMapLocationConfig("/keysMapMulti1.list"));
keysMap.load(aKeysMapLocationConfig("/keysMapMulti2.list"));
assertThat(keysMap.size()).isEqualTo(9);
}
@DataProvider
public static Object[][] artifactWithKeyToTest() {
return new Object[][]{
{testArtifact().build(), | // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeysMapLocationConfig aKeysMapLocationConfig(String location) {
// KeysMapLocationConfig config = new KeysMapLocationConfig();
// config.set(location);
// return config;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
// Path: src/test/java/org/simplify4u/plugins/keysmap/KeysMapMultiTest.java
import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import static org.simplify4u.plugins.TestUtils.aKeysMapLocationConfig;
import org.apache.maven.artifact.Artifact;
import org.codehaus.plexus.resource.ResourceManager;
import org.codehaus.plexus.resource.loader.ResourceNotFoundException;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.pgp.KeyFingerprint;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
@Listeners(MockitoTestNGListener.class)
public class KeysMapMultiTest {
@Mock
private ResourceManager resourceManager;
@InjectMocks
private KeysMap keysMap;
@BeforeMethod
public void setup() throws ResourceNotFoundException {
doAnswer(invocation -> getClass().getResourceAsStream(invocation.getArgument(0)))
.when(resourceManager).getResourceAsInputStream(anyString());
}
@Test
public void loadMultipleKeysMapShouldContainsAllItems() throws ResourceNotFoundException, IOException {
keysMap.load(aKeysMapLocationConfig("/keysMapMulti1.list"));
keysMap.load(aKeysMapLocationConfig("/keysMapMulti2.list"));
assertThat(keysMap.size()).isEqualTo(9);
}
@DataProvider
public static Object[][] artifactWithKeyToTest() {
return new Object[][]{
{testArtifact().build(), | new KeyFingerprint("0x1111 1111 1111 1111")}, |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/keysmap/KeysMapMultiTest.java | // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeysMapLocationConfig aKeysMapLocationConfig(String location) {
// KeysMapLocationConfig config = new KeysMapLocationConfig();
// config.set(location);
// return config;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
| import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import static org.simplify4u.plugins.TestUtils.aKeysMapLocationConfig;
import org.apache.maven.artifact.Artifact;
import org.codehaus.plexus.resource.ResourceManager;
import org.codehaus.plexus.resource.loader.ResourceNotFoundException;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.pgp.KeyFingerprint; | {testArtifact().build(),
new KeyFingerprint("0x1111 1111 3333 3333")},
{testArtifact().artifactId("test1").build(),
new KeyFingerprint("0x1111 1111 4444 4444")},
{testArtifact().build(),
new KeyFingerprint("0x2222 2222 1111 1111")},
{testArtifact().build(),
new KeyFingerprint("0x2222 2222 2222 2222")},
{testArtifact().build(),
new KeyFingerprint("0x2222 2222 3333 3333")},
{testArtifact().groupId("test.group2").build(),
new KeyFingerprint("0x2222 2222 4444 4444")},
{testArtifact().artifactId("bad-sig").build(),
new KeyFingerprint("0x2222 2222 5555 5555")},
{testArtifact().groupId("test.group7").artifactId("test7").build(),
new KeyFingerprint("0x7777 7777 7777 7777")}
};
}
@Test(dataProvider = "artifactWithKeyToTest")
public void keyShouldBeValid(Artifact artifact, KeyFingerprint keyFingerprint)
throws ResourceNotFoundException, IOException {
| // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
//
// Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeysMapLocationConfig aKeysMapLocationConfig(String location) {
// KeysMapLocationConfig config = new KeysMapLocationConfig();
// config.set(location);
// return config;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
// Path: src/test/java/org/simplify4u/plugins/keysmap/KeysMapMultiTest.java
import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import static org.simplify4u.plugins.TestUtils.aKeysMapLocationConfig;
import org.apache.maven.artifact.Artifact;
import org.codehaus.plexus.resource.ResourceManager;
import org.codehaus.plexus.resource.loader.ResourceNotFoundException;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.pgp.KeyFingerprint;
{testArtifact().build(),
new KeyFingerprint("0x1111 1111 3333 3333")},
{testArtifact().artifactId("test1").build(),
new KeyFingerprint("0x1111 1111 4444 4444")},
{testArtifact().build(),
new KeyFingerprint("0x2222 2222 1111 1111")},
{testArtifact().build(),
new KeyFingerprint("0x2222 2222 2222 2222")},
{testArtifact().build(),
new KeyFingerprint("0x2222 2222 3333 3333")},
{testArtifact().groupId("test.group2").build(),
new KeyFingerprint("0x2222 2222 4444 4444")},
{testArtifact().artifactId("bad-sig").build(),
new KeyFingerprint("0x2222 2222 5555 5555")},
{testArtifact().groupId("test.group7").artifactId("test7").build(),
new KeyFingerprint("0x7777 7777 7777 7777")}
};
}
@Test(dataProvider = "artifactWithKeyToTest")
public void keyShouldBeValid(Artifact artifact, KeyFingerprint keyFingerprint)
throws ResourceNotFoundException, IOException {
| KeyInfo key = KeyInfo.builder().fingerprint(keyFingerprint).build(); |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/keysmap/KeyItemsTest.java | // Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
| import java.io.IOException;
import java.util.Collections;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.bouncycastle.openpgp.PGPException;
import org.simplify4u.plugins.pgp.KeyFingerprint;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* @author Slawomir Jaranowski.
*/
public class KeyItemsTest {
@DataProvider(name = "keys")
public Object[][] keys() {
return new Object[][]{
{"*", "0x123456789abcdef0", true},
{"", "0x123456789abcdef0", false},
{"any", "0x123456789abcdef0", true},
{"Any", "0x123456789abcdef0", true},
{"0x123456789abcdef0", "0x123456789abcdef0", true},
{"noSig, 0x123456789abcdef0", "0x123456789abcdef0", true},
{"noKey, 0x123456789abcdef0", "0x123456789abcdef0", true},
{"badSig, 0x123456789abcdef0", "0x123456789abcdef0", true},
{"0x123456789abcdef0,0x0fedcba987654321", "0x123456789abcdef0", true},
{"0x123456789abcdef0, 0x0fedcba987654321", "0x123456789abcdef0", true},
{"0x123456789abcdef0", "0x231456789abcdef0", false},
{"0x12 34 56 78 9a bc de f0", "0x123456789abcdef0", true},
{"0x123456789abcdef0, *", "0x231456789abcdef0", true},
{"0x123456789abcdef0, 0x0fedcba987654321", "0x321456789abcdef0", false},
{"0x0000000000000001", "0x0000000000000001", true}
};
}
@Test(dataProvider = "keys")
public void testIsKeyMatch(String strKeys, String key, boolean match) throws Exception {
KeyItems keyItems = new KeyItems().addKeys(strKeys, null);
assertThat(keyItems.isKeyMatch(aKeyInfo(key))).as("isKeyMatch").isEqualTo(match);
}
| // Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
// Path: src/test/java/org/simplify4u/plugins/keysmap/KeyItemsTest.java
import java.io.IOException;
import java.util.Collections;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.bouncycastle.openpgp.PGPException;
import org.simplify4u.plugins.pgp.KeyFingerprint;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* @author Slawomir Jaranowski.
*/
public class KeyItemsTest {
@DataProvider(name = "keys")
public Object[][] keys() {
return new Object[][]{
{"*", "0x123456789abcdef0", true},
{"", "0x123456789abcdef0", false},
{"any", "0x123456789abcdef0", true},
{"Any", "0x123456789abcdef0", true},
{"0x123456789abcdef0", "0x123456789abcdef0", true},
{"noSig, 0x123456789abcdef0", "0x123456789abcdef0", true},
{"noKey, 0x123456789abcdef0", "0x123456789abcdef0", true},
{"badSig, 0x123456789abcdef0", "0x123456789abcdef0", true},
{"0x123456789abcdef0,0x0fedcba987654321", "0x123456789abcdef0", true},
{"0x123456789abcdef0, 0x0fedcba987654321", "0x123456789abcdef0", true},
{"0x123456789abcdef0", "0x231456789abcdef0", false},
{"0x12 34 56 78 9a bc de f0", "0x123456789abcdef0", true},
{"0x123456789abcdef0, *", "0x231456789abcdef0", true},
{"0x123456789abcdef0, 0x0fedcba987654321", "0x321456789abcdef0", false},
{"0x0000000000000001", "0x0000000000000001", true}
};
}
@Test(dataProvider = "keys")
public void testIsKeyMatch(String strKeys, String key, boolean match) throws Exception {
KeyItems keyItems = new KeyItems().addKeys(strKeys, null);
assertThat(keyItems.isKeyMatch(aKeyInfo(key))).as("isKeyMatch").isEqualTo(match);
}
| private KeyInfo aKeyInfo(String fingerprint) { |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/keysmap/KeyItemsTest.java | // Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
| import java.io.IOException;
import java.util.Collections;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.bouncycastle.openpgp.PGPException;
import org.simplify4u.plugins.pgp.KeyFingerprint;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* @author Slawomir Jaranowski.
*/
public class KeyItemsTest {
@DataProvider(name = "keys")
public Object[][] keys() {
return new Object[][]{
{"*", "0x123456789abcdef0", true},
{"", "0x123456789abcdef0", false},
{"any", "0x123456789abcdef0", true},
{"Any", "0x123456789abcdef0", true},
{"0x123456789abcdef0", "0x123456789abcdef0", true},
{"noSig, 0x123456789abcdef0", "0x123456789abcdef0", true},
{"noKey, 0x123456789abcdef0", "0x123456789abcdef0", true},
{"badSig, 0x123456789abcdef0", "0x123456789abcdef0", true},
{"0x123456789abcdef0,0x0fedcba987654321", "0x123456789abcdef0", true},
{"0x123456789abcdef0, 0x0fedcba987654321", "0x123456789abcdef0", true},
{"0x123456789abcdef0", "0x231456789abcdef0", false},
{"0x12 34 56 78 9a bc de f0", "0x123456789abcdef0", true},
{"0x123456789abcdef0, *", "0x231456789abcdef0", true},
{"0x123456789abcdef0, 0x0fedcba987654321", "0x321456789abcdef0", false},
{"0x0000000000000001", "0x0000000000000001", true}
};
}
@Test(dataProvider = "keys")
public void testIsKeyMatch(String strKeys, String key, boolean match) throws Exception {
KeyItems keyItems = new KeyItems().addKeys(strKeys, null);
assertThat(keyItems.isKeyMatch(aKeyInfo(key))).as("isKeyMatch").isEqualTo(match);
}
private KeyInfo aKeyInfo(String fingerprint) { | // Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
// @Value
// @RequiredArgsConstructor
// public class KeyFingerprint {
//
// byte[] fingerprint;
//
// /**
// * Construct a key fingerprint from string representation.
// * @param strFingerprint a key fingerprint as string
// */
// public KeyFingerprint(String strFingerprint) {
// fingerprint = HexUtils.stringToFingerprint(strFingerprint);
// }
//
// @JsonValue
// public String toString() {
// return HexUtils.fingerprintToString(fingerprint);
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
// Path: src/test/java/org/simplify4u/plugins/keysmap/KeyItemsTest.java
import java.io.IOException;
import java.util.Collections;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.bouncycastle.openpgp.PGPException;
import org.simplify4u.plugins.pgp.KeyFingerprint;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* @author Slawomir Jaranowski.
*/
public class KeyItemsTest {
@DataProvider(name = "keys")
public Object[][] keys() {
return new Object[][]{
{"*", "0x123456789abcdef0", true},
{"", "0x123456789abcdef0", false},
{"any", "0x123456789abcdef0", true},
{"Any", "0x123456789abcdef0", true},
{"0x123456789abcdef0", "0x123456789abcdef0", true},
{"noSig, 0x123456789abcdef0", "0x123456789abcdef0", true},
{"noKey, 0x123456789abcdef0", "0x123456789abcdef0", true},
{"badSig, 0x123456789abcdef0", "0x123456789abcdef0", true},
{"0x123456789abcdef0,0x0fedcba987654321", "0x123456789abcdef0", true},
{"0x123456789abcdef0, 0x0fedcba987654321", "0x123456789abcdef0", true},
{"0x123456789abcdef0", "0x231456789abcdef0", false},
{"0x12 34 56 78 9a bc de f0", "0x123456789abcdef0", true},
{"0x123456789abcdef0, *", "0x231456789abcdef0", true},
{"0x123456789abcdef0, 0x0fedcba987654321", "0x321456789abcdef0", false},
{"0x0000000000000001", "0x0000000000000001", true}
};
}
@Test(dataProvider = "keys")
public void testIsKeyMatch(String strKeys, String key, boolean match) throws Exception {
KeyItems keyItems = new KeyItems().addKeys(strKeys, null);
assertThat(keyItems.isKeyMatch(aKeyInfo(key))).as("isKeyMatch").isEqualTo(match);
}
private KeyInfo aKeyInfo(String fingerprint) { | return KeyInfo.builder().fingerprint(new KeyFingerprint(fingerprint)).build(); |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/keysmap/ArtifactPatternTest.java | // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; | /*
* Copyright 2020-2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* @author Slawomir Jaranowski.
*/
public class ArtifactPatternTest {
@DataProvider(name = "lists")
public Object[][] artifactsList() {
return new Object[][]{ | // Path: src/test/java/org/simplify4u/plugins/TestArtifactBuilder.java
// public static TestArtifactBuilder testArtifact() {
// return new TestArtifactBuilder();
// }
// Path: src/test/java/org/simplify4u/plugins/keysmap/ArtifactPatternTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.simplify4u.plugins.TestArtifactBuilder.testArtifact;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/*
* Copyright 2020-2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* @author Slawomir Jaranowski.
*/
public class ArtifactPatternTest {
@DataProvider(name = "lists")
public Object[][] artifactsList() {
return new Object[][]{ | {"Test.Group:tesT:*", testArtifact().build(), true}, |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/keyserver/KeyServerClientSettingsTest.java | // Path: src/test/java/org/simplify4u/plugins/utils/ProxyUtil.java
// public static Proxy makeMavenProxy(String proxyUser, String proxyPassword, String id, boolean active) {
// Proxy proxy = new Proxy();
// proxy.setHost("localhost");
// proxy.setActive(active);
// proxy.setNonProxyHosts("*");
// proxy.setUsername(proxyUser);
// proxy.setPassword(proxyPassword);
// proxy.setId(id);
// proxy.setProtocol("http");
// return proxy;
// }
| import org.mockito.testng.MockitoTestNGListener;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.simplify4u.plugins.utils.ProxyUtil.makeMavenProxy;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.settings.Proxy;
import org.apache.maven.settings.Settings;
import org.mockito.Mock; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keyserver;
/**
* test on methods in the mojo itself
*/
@Listeners(MockitoTestNGListener.class)
public class KeyServerClientSettingsTest {
@Mock
private MavenSession mavenSession;
@Mock
private Settings settings;
/**
* test that if we set a proxy, we want to ensure that it is the right one from our config
*
*/
@Test
public void testIfProxyDeterminationWorksUsingIDs() {
List<Proxy> proxies = Arrays.asList( | // Path: src/test/java/org/simplify4u/plugins/utils/ProxyUtil.java
// public static Proxy makeMavenProxy(String proxyUser, String proxyPassword, String id, boolean active) {
// Proxy proxy = new Proxy();
// proxy.setHost("localhost");
// proxy.setActive(active);
// proxy.setNonProxyHosts("*");
// proxy.setUsername(proxyUser);
// proxy.setPassword(proxyPassword);
// proxy.setId(id);
// proxy.setProtocol("http");
// return proxy;
// }
// Path: src/test/java/org/simplify4u/plugins/keyserver/KeyServerClientSettingsTest.java
import org.mockito.testng.MockitoTestNGListener;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.simplify4u.plugins.utils.ProxyUtil.makeMavenProxy;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.settings.Proxy;
import org.apache.maven.settings.Settings;
import org.mockito.Mock;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keyserver;
/**
* test on methods in the mojo itself
*/
@Listeners(MockitoTestNGListener.class)
public class KeyServerClientSettingsTest {
@Mock
private MavenSession mavenSession;
@Mock
private Settings settings;
/**
* test that if we set a proxy, we want to ensure that it is the right one from our config
*
*/
@Test
public void testIfProxyDeterminationWorksUsingIDs() {
List<Proxy> proxies = Arrays.asList( | makeMavenProxy(null, null, "p1", true), |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/keysmap/KeysMap.java | // Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
| import org.apache.maven.artifact.Artifact;
import org.codehaus.plexus.resource.ResourceManager;
import org.codehaus.plexus.resource.loader.ResourceNotFoundException;
import org.simplify4u.plugins.pgp.KeyInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Named;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j; | * @param artifact artifact to test
*
* @return key missing status
*/
public boolean isKeyMissing(Artifact artifact) {
ArtifactData artifactData = new ArtifactData(artifact);
return items.entrySet().stream()
.filter(entry -> entry.getKey().isMatch(artifactData))
.anyMatch(entry -> entry.getValue().isKeyMissing());
}
public boolean isWithKey(Artifact artifact) {
ArtifactData artifactData = new ArtifactData(artifact);
return items.entrySet().stream()
.filter(entry -> entry.getKey().isMatch(artifactData))
.anyMatch(entry -> !entry.getValue().isNoSignature());
}
/**
* Test if given key is trust for artifact.
*
* @param artifact a artifact
* @param keyInfo a key which is used to sign artifact
*
* @return a key trust status
*/ | // Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
// Path: src/main/java/org/simplify4u/plugins/keysmap/KeysMap.java
import org.apache.maven.artifact.Artifact;
import org.codehaus.plexus.resource.ResourceManager;
import org.codehaus.plexus.resource.loader.ResourceNotFoundException;
import org.simplify4u.plugins.pgp.KeyInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Named;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
* @param artifact artifact to test
*
* @return key missing status
*/
public boolean isKeyMissing(Artifact artifact) {
ArtifactData artifactData = new ArtifactData(artifact);
return items.entrySet().stream()
.filter(entry -> entry.getKey().isMatch(artifactData))
.anyMatch(entry -> entry.getValue().isKeyMissing());
}
public boolean isWithKey(Artifact artifact) {
ArtifactData artifactData = new ArtifactData(artifact);
return items.entrySet().stream()
.filter(entry -> entry.getKey().isMatch(artifactData))
.anyMatch(entry -> !entry.getValue().isNoSignature());
}
/**
* Test if given key is trust for artifact.
*
* @param artifact a artifact
* @param keyInfo a key which is used to sign artifact
*
* @return a key trust status
*/ | public boolean isValidKey(Artifact artifact, KeyInfo keyInfo) { |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/keyserver/PGPKeysServerClientTest.java | // Path: src/test/java/org/simplify4u/plugins/utils/ProxyUtil.java
// public static Proxy makeMavenProxy(String proxyUser, String proxyPassword, String id, boolean active) {
// Proxy proxy = new Proxy();
// proxy.setHost("localhost");
// proxy.setActive(active);
// proxy.setNonProxyHosts("*");
// proxy.setUsername(proxyUser);
// proxy.setPassword(proxyPassword);
// proxy.setId(id);
// proxy.setProtocol("http");
// return proxy;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyId.java
// public interface KeyId {
//
// String getHashPath();
//
// PGPPublicKey getKeyFromRing(PGPPublicKeyRing publicKeyRing);
//
// PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection) throws PGPException;
//
// /**
// * Representation of a keyId with long as key.
// */
// @EqualsAndHashCode
// class KeyIdLong implements KeyId {
//
// private final Long keyId;
//
// KeyIdLong(Long keyId) {
// this.keyId = keyId;
// }
//
// @Override
// public String getHashPath() {
// return String.format("%02X/%02X/%016X.asc", (byte) (keyId >> 56), (byte) (keyId >> 48 & 0xff), keyId);
// }
//
// @Override
// public PGPPublicKey getKeyFromRing(PGPPublicKeyRing publicKeyRing) {
// return publicKeyRing.getPublicKey(keyId);
// }
//
// @Override
// public PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection)
// throws PGPException {
// return pgpRingCollection.getPublicKeyRing(keyId);
// }
//
// @Override
// @JsonValue
// public String toString() {
// return String.format("0x%016X", keyId);
// }
// }
//
// /**
// * Representation of a keyId with fingerprint as key.
// */
// @EqualsAndHashCode
// class KeyIdFingerprint implements KeyId {
//
// private final byte[] fingerprint;
//
// KeyIdFingerprint(byte[] fingerprint) {
// this.fingerprint = fingerprint;
// }
//
// @Override
// public String getHashPath() {
// StringBuilder ret = new StringBuilder();
// ret.append(String.format("%02X/", fingerprint[0]));
// ret.append(String.format("%02X/", fingerprint[1]));
// for (byte b: fingerprint) {
// ret.append(String.format("%02X", b));
// }
// ret.append(".asc");
// return ret.toString();
// }
//
// @Override
// public PGPPublicKey getKeyFromRing(PGPPublicKeyRing publicKeyRing) {
// return publicKeyRing.getPublicKey(fingerprint);
// }
//
// @Override
// public PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection)
// throws PGPException {
// return pgpRingCollection.getPublicKeyRing(fingerprint);
// }
//
// @Override
// @JsonValue
// public String toString() {
// return fingerprintToString(fingerprint);
// }
//
// }
//
// static KeyId from(byte[] fingerprint) {
// return new KeyIdFingerprint(fingerprint);
// }
//
// static KeyId from(Long keyId) {
// return new KeyIdLong(keyId);
// }
// }
| import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.simplify4u.plugins.utils.ProxyUtil.makeMavenProxy;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.settings.Proxy;
import org.apache.maven.settings.Settings;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.pgp.KeyId;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keyserver;
@Listeners(MockitoTestNGListener.class)
public class PGPKeysServerClientTest {
@Mock
Settings settings;
@Mock
MavenSession mavenSession;
@Mock
HttpClientBuilder clientBuilder;
@DataProvider(name = "proxy")
public static Object[][] emptyProxy() {
return new Object[][]{ | // Path: src/test/java/org/simplify4u/plugins/utils/ProxyUtil.java
// public static Proxy makeMavenProxy(String proxyUser, String proxyPassword, String id, boolean active) {
// Proxy proxy = new Proxy();
// proxy.setHost("localhost");
// proxy.setActive(active);
// proxy.setNonProxyHosts("*");
// proxy.setUsername(proxyUser);
// proxy.setPassword(proxyPassword);
// proxy.setId(id);
// proxy.setProtocol("http");
// return proxy;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyId.java
// public interface KeyId {
//
// String getHashPath();
//
// PGPPublicKey getKeyFromRing(PGPPublicKeyRing publicKeyRing);
//
// PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection) throws PGPException;
//
// /**
// * Representation of a keyId with long as key.
// */
// @EqualsAndHashCode
// class KeyIdLong implements KeyId {
//
// private final Long keyId;
//
// KeyIdLong(Long keyId) {
// this.keyId = keyId;
// }
//
// @Override
// public String getHashPath() {
// return String.format("%02X/%02X/%016X.asc", (byte) (keyId >> 56), (byte) (keyId >> 48 & 0xff), keyId);
// }
//
// @Override
// public PGPPublicKey getKeyFromRing(PGPPublicKeyRing publicKeyRing) {
// return publicKeyRing.getPublicKey(keyId);
// }
//
// @Override
// public PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection)
// throws PGPException {
// return pgpRingCollection.getPublicKeyRing(keyId);
// }
//
// @Override
// @JsonValue
// public String toString() {
// return String.format("0x%016X", keyId);
// }
// }
//
// /**
// * Representation of a keyId with fingerprint as key.
// */
// @EqualsAndHashCode
// class KeyIdFingerprint implements KeyId {
//
// private final byte[] fingerprint;
//
// KeyIdFingerprint(byte[] fingerprint) {
// this.fingerprint = fingerprint;
// }
//
// @Override
// public String getHashPath() {
// StringBuilder ret = new StringBuilder();
// ret.append(String.format("%02X/", fingerprint[0]));
// ret.append(String.format("%02X/", fingerprint[1]));
// for (byte b: fingerprint) {
// ret.append(String.format("%02X", b));
// }
// ret.append(".asc");
// return ret.toString();
// }
//
// @Override
// public PGPPublicKey getKeyFromRing(PGPPublicKeyRing publicKeyRing) {
// return publicKeyRing.getPublicKey(fingerprint);
// }
//
// @Override
// public PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection)
// throws PGPException {
// return pgpRingCollection.getPublicKeyRing(fingerprint);
// }
//
// @Override
// @JsonValue
// public String toString() {
// return fingerprintToString(fingerprint);
// }
//
// }
//
// static KeyId from(byte[] fingerprint) {
// return new KeyIdFingerprint(fingerprint);
// }
//
// static KeyId from(Long keyId) {
// return new KeyIdLong(keyId);
// }
// }
// Path: src/test/java/org/simplify4u/plugins/keyserver/PGPKeysServerClientTest.java
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.simplify4u.plugins.utils.ProxyUtil.makeMavenProxy;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.settings.Proxy;
import org.apache.maven.settings.Settings;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.pgp.KeyId;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keyserver;
@Listeners(MockitoTestNGListener.class)
public class PGPKeysServerClientTest {
@Mock
Settings settings;
@Mock
MavenSession mavenSession;
@Mock
HttpClientBuilder clientBuilder;
@DataProvider(name = "proxy")
public static Object[][] emptyProxy() {
return new Object[][]{ | {makeMavenProxy("", "")}, |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/keyserver/PGPKeysServerClientTest.java | // Path: src/test/java/org/simplify4u/plugins/utils/ProxyUtil.java
// public static Proxy makeMavenProxy(String proxyUser, String proxyPassword, String id, boolean active) {
// Proxy proxy = new Proxy();
// proxy.setHost("localhost");
// proxy.setActive(active);
// proxy.setNonProxyHosts("*");
// proxy.setUsername(proxyUser);
// proxy.setPassword(proxyPassword);
// proxy.setId(id);
// proxy.setProtocol("http");
// return proxy;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyId.java
// public interface KeyId {
//
// String getHashPath();
//
// PGPPublicKey getKeyFromRing(PGPPublicKeyRing publicKeyRing);
//
// PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection) throws PGPException;
//
// /**
// * Representation of a keyId with long as key.
// */
// @EqualsAndHashCode
// class KeyIdLong implements KeyId {
//
// private final Long keyId;
//
// KeyIdLong(Long keyId) {
// this.keyId = keyId;
// }
//
// @Override
// public String getHashPath() {
// return String.format("%02X/%02X/%016X.asc", (byte) (keyId >> 56), (byte) (keyId >> 48 & 0xff), keyId);
// }
//
// @Override
// public PGPPublicKey getKeyFromRing(PGPPublicKeyRing publicKeyRing) {
// return publicKeyRing.getPublicKey(keyId);
// }
//
// @Override
// public PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection)
// throws PGPException {
// return pgpRingCollection.getPublicKeyRing(keyId);
// }
//
// @Override
// @JsonValue
// public String toString() {
// return String.format("0x%016X", keyId);
// }
// }
//
// /**
// * Representation of a keyId with fingerprint as key.
// */
// @EqualsAndHashCode
// class KeyIdFingerprint implements KeyId {
//
// private final byte[] fingerprint;
//
// KeyIdFingerprint(byte[] fingerprint) {
// this.fingerprint = fingerprint;
// }
//
// @Override
// public String getHashPath() {
// StringBuilder ret = new StringBuilder();
// ret.append(String.format("%02X/", fingerprint[0]));
// ret.append(String.format("%02X/", fingerprint[1]));
// for (byte b: fingerprint) {
// ret.append(String.format("%02X", b));
// }
// ret.append(".asc");
// return ret.toString();
// }
//
// @Override
// public PGPPublicKey getKeyFromRing(PGPPublicKeyRing publicKeyRing) {
// return publicKeyRing.getPublicKey(fingerprint);
// }
//
// @Override
// public PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection)
// throws PGPException {
// return pgpRingCollection.getPublicKeyRing(fingerprint);
// }
//
// @Override
// @JsonValue
// public String toString() {
// return fingerprintToString(fingerprint);
// }
//
// }
//
// static KeyId from(byte[] fingerprint) {
// return new KeyIdFingerprint(fingerprint);
// }
//
// static KeyId from(Long keyId) {
// return new KeyIdLong(keyId);
// }
// }
| import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.simplify4u.plugins.utils.ProxyUtil.makeMavenProxy;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.settings.Proxy;
import org.apache.maven.settings.Settings;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.pgp.KeyId;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test; | }
private void runProxyConfig(Proxy proxy) {
when(mavenSession.getSettings()).thenReturn(settings);
when(settings.getActiveProxy()).thenReturn(proxy);
KeyServerClientSettings clientSettings = KeyServerClientSettings.builder()
.mavenSession(mavenSession)
.build();
PGPKeysServerClient pgpKeysServerClient = new PGPKeysServerClient(null, clientSettings, () -> clientBuilder);
pgpKeysServerClient.buildClient(null);
verify(clientBuilder).build();
}
@Test
public void offLineModeShouldThrowIOException() throws URISyntaxException {
URI uri = new URI("https://localhost/");
when(mavenSession.isOffline()).thenReturn(true);
KeyServerClientSettings clientSettings = KeyServerClientSettings.builder()
.mavenSession(mavenSession)
.build();
PGPKeysServerClient pgpKeysServerClient = new PGPKeysServerClient(uri, clientSettings);
| // Path: src/test/java/org/simplify4u/plugins/utils/ProxyUtil.java
// public static Proxy makeMavenProxy(String proxyUser, String proxyPassword, String id, boolean active) {
// Proxy proxy = new Proxy();
// proxy.setHost("localhost");
// proxy.setActive(active);
// proxy.setNonProxyHosts("*");
// proxy.setUsername(proxyUser);
// proxy.setPassword(proxyPassword);
// proxy.setId(id);
// proxy.setProtocol("http");
// return proxy;
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyId.java
// public interface KeyId {
//
// String getHashPath();
//
// PGPPublicKey getKeyFromRing(PGPPublicKeyRing publicKeyRing);
//
// PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection) throws PGPException;
//
// /**
// * Representation of a keyId with long as key.
// */
// @EqualsAndHashCode
// class KeyIdLong implements KeyId {
//
// private final Long keyId;
//
// KeyIdLong(Long keyId) {
// this.keyId = keyId;
// }
//
// @Override
// public String getHashPath() {
// return String.format("%02X/%02X/%016X.asc", (byte) (keyId >> 56), (byte) (keyId >> 48 & 0xff), keyId);
// }
//
// @Override
// public PGPPublicKey getKeyFromRing(PGPPublicKeyRing publicKeyRing) {
// return publicKeyRing.getPublicKey(keyId);
// }
//
// @Override
// public PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection)
// throws PGPException {
// return pgpRingCollection.getPublicKeyRing(keyId);
// }
//
// @Override
// @JsonValue
// public String toString() {
// return String.format("0x%016X", keyId);
// }
// }
//
// /**
// * Representation of a keyId with fingerprint as key.
// */
// @EqualsAndHashCode
// class KeyIdFingerprint implements KeyId {
//
// private final byte[] fingerprint;
//
// KeyIdFingerprint(byte[] fingerprint) {
// this.fingerprint = fingerprint;
// }
//
// @Override
// public String getHashPath() {
// StringBuilder ret = new StringBuilder();
// ret.append(String.format("%02X/", fingerprint[0]));
// ret.append(String.format("%02X/", fingerprint[1]));
// for (byte b: fingerprint) {
// ret.append(String.format("%02X", b));
// }
// ret.append(".asc");
// return ret.toString();
// }
//
// @Override
// public PGPPublicKey getKeyFromRing(PGPPublicKeyRing publicKeyRing) {
// return publicKeyRing.getPublicKey(fingerprint);
// }
//
// @Override
// public PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection)
// throws PGPException {
// return pgpRingCollection.getPublicKeyRing(fingerprint);
// }
//
// @Override
// @JsonValue
// public String toString() {
// return fingerprintToString(fingerprint);
// }
//
// }
//
// static KeyId from(byte[] fingerprint) {
// return new KeyIdFingerprint(fingerprint);
// }
//
// static KeyId from(Long keyId) {
// return new KeyIdLong(keyId);
// }
// }
// Path: src/test/java/org/simplify4u/plugins/keyserver/PGPKeysServerClientTest.java
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.simplify4u.plugins.utils.ProxyUtil.makeMavenProxy;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.settings.Proxy;
import org.apache.maven.settings.Settings;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.pgp.KeyId;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
}
private void runProxyConfig(Proxy proxy) {
when(mavenSession.getSettings()).thenReturn(settings);
when(settings.getActiveProxy()).thenReturn(proxy);
KeyServerClientSettings clientSettings = KeyServerClientSettings.builder()
.mavenSession(mavenSession)
.build();
PGPKeysServerClient pgpKeysServerClient = new PGPKeysServerClient(null, clientSettings, () -> clientBuilder);
pgpKeysServerClient.buildClient(null);
verify(clientBuilder).build();
}
@Test
public void offLineModeShouldThrowIOException() throws URISyntaxException {
URI uri = new URI("https://localhost/");
when(mavenSession.isOffline()).thenReturn(true);
KeyServerClientSettings clientSettings = KeyServerClientSettings.builder()
.mavenSession(mavenSession)
.build();
PGPKeysServerClient pgpKeysServerClient = new PGPKeysServerClient(uri, clientSettings);
| assertThatThrownBy(() -> pgpKeysServerClient.copyKeyToOutputStream(KeyId.from(0x0123456789ABCDEFL), null, null)) |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java | // Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// @UtilityClass
// public class HexUtils {
//
// /**
// * Convert byte array of fingerprint to string of hex
// * @param bytes fingerprint
// * @return fingerprint as string
// */
// public static String fingerprintToString(byte[] bytes) {
// StringBuilder ret = new StringBuilder();
// ret.append("0x");
// for (byte b : bytes) {
// ret.append(String.format("%02X", b));
// }
// return ret.toString();
// }
//
// /**
// * Convert fingerprint in string format to byte array.
// * @param key fingerprint as string
// * @return fingerprint as byte array
// */
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
// }
| import com.fasterxml.jackson.annotation.JsonValue;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import org.simplify4u.plugins.utils.HexUtils; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.pgp;
/**
* Represent a key fingerprint.
*/
@Value
@RequiredArgsConstructor
public class KeyFingerprint {
byte[] fingerprint;
/**
* Construct a key fingerprint from string representation.
* @param strFingerprint a key fingerprint as string
*/
public KeyFingerprint(String strFingerprint) { | // Path: src/main/java/org/simplify4u/plugins/utils/HexUtils.java
// @UtilityClass
// public class HexUtils {
//
// /**
// * Convert byte array of fingerprint to string of hex
// * @param bytes fingerprint
// * @return fingerprint as string
// */
// public static String fingerprintToString(byte[] bytes) {
// StringBuilder ret = new StringBuilder();
// ret.append("0x");
// for (byte b : bytes) {
// ret.append(String.format("%02X", b));
// }
// return ret.toString();
// }
//
// /**
// * Convert fingerprint in string format to byte array.
// * @param key fingerprint as string
// * @return fingerprint as byte array
// */
// public static byte[] stringToFingerprint(String key) {
// byte[] bytes;
//
// try {
// bytes = Hex.decode(key.substring(2));
// } catch (DecoderException e) {
// throw new IllegalArgumentException("Malformed keyID hex string " + key, e);
// }
//
// if (bytes.length < 8 || bytes.length > 20) {
// throw new IllegalArgumentException(
// String.format("Key length for = %s is %d bits, should be between 64 and 160 bits",
// key, bytes.length * 8));
// }
//
// return bytes;
// }
// }
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyFingerprint.java
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import org.simplify4u.plugins.utils.HexUtils;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.pgp;
/**
* Represent a key fingerprint.
*/
@Value
@RequiredArgsConstructor
public class KeyFingerprint {
byte[] fingerprint;
/**
* Construct a key fingerprint from string representation.
* @param strFingerprint a key fingerprint as string
*/
public KeyFingerprint(String strFingerprint) { | fingerprint = HexUtils.stringToFingerprint(strFingerprint); |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/pgp/PublicKeyUtilsTest.java | // Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeyInfo aKeyInfo(String fingerprint) {
// return KeyInfo.builder().fingerprint(new KeyFingerprint(fingerprint)).build();
// }
| import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.simplify4u.plugins.TestUtils.aKeyInfo;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; | .build();
assertThat(keyInfo.getMaster()).isNotNull();
assertThat(PublicKeyUtils.fingerprintForMaster(keyInfo))
.isEqualTo("0x58E79B6ABC762159DC0B1591164BD2247B936711");
}
@Test
public void userIdsWithSubKey() {
PGPPublicKey key = SUB_KEY_ID.getKeyFromRing(publicKeyRing);
assertThat(key.isMasterKey()).isFalse();
assertThat(PublicKeyUtils.getUserIDs(key, publicKeyRing))
.containsOnly("Marc Philipp (JUnit Development, 2014) <[email protected]>");
}
@Test
public void userIdsWithMasterKey() {
PGPPublicKey key = publicKeyRing.getPublicKey(MASTER_KEY_ID);
assertThat(key.isMasterKey()).isTrue();
assertThat(PublicKeyUtils.getUserIDs(key, publicKeyRing))
.containsOnly("Marc Philipp (JUnit Development, 2014) <[email protected]>");
}
@Test
public void keyIdDescriptionForMasterKey() {
| // Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeyInfo aKeyInfo(String fingerprint) {
// return KeyInfo.builder().fingerprint(new KeyFingerprint(fingerprint)).build();
// }
// Path: src/test/java/org/simplify4u/plugins/pgp/PublicKeyUtilsTest.java
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.simplify4u.plugins.TestUtils.aKeyInfo;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
.build();
assertThat(keyInfo.getMaster()).isNotNull();
assertThat(PublicKeyUtils.fingerprintForMaster(keyInfo))
.isEqualTo("0x58E79B6ABC762159DC0B1591164BD2247B936711");
}
@Test
public void userIdsWithSubKey() {
PGPPublicKey key = SUB_KEY_ID.getKeyFromRing(publicKeyRing);
assertThat(key.isMasterKey()).isFalse();
assertThat(PublicKeyUtils.getUserIDs(key, publicKeyRing))
.containsOnly("Marc Philipp (JUnit Development, 2014) <[email protected]>");
}
@Test
public void userIdsWithMasterKey() {
PGPPublicKey key = publicKeyRing.getPublicKey(MASTER_KEY_ID);
assertThat(key.isMasterKey()).isTrue();
assertThat(PublicKeyUtils.getUserIDs(key, publicKeyRing))
.containsOnly("Marc Philipp (JUnit Development, 2014) <[email protected]>");
}
@Test
public void keyIdDescriptionForMasterKey() {
| KeyInfo keyInfo = aKeyInfo("0x1234567890123456789012345678901234567890"); |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/keysmap/KeyItemFingerprintTest.java | // Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeyInfo aKeyInfo(String fingerprint) {
// return KeyInfo.builder().fingerprint(new KeyFingerprint(fingerprint)).build();
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.simplify4u.plugins.TestUtils.aKeyInfo;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.Test; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
public class KeyItemFingerprintTest {
private static final String FINGERPRINT_1 = "0x9ABC DEF0 1234 5678 9ABC DEF0 1234 5678 9ABC DEF0";
private static final String FINGERPRINT_2 = "0x9ABC DEF0 1234 5678 9ABC DEF0 1234 5678 9ABC 0000";
@Test
void twoInstanceForTheSameKeyShouldBeEqual() {
KeyItemFingerprint keyItemFingerprint1 = new KeyItemFingerprint(FINGERPRINT_1);
KeyItemFingerprint keyItemFingerprint2 = new KeyItemFingerprint(FINGERPRINT_1);
assertThat(keyItemFingerprint1)
.isNotSameAs(keyItemFingerprint2)
.isEqualTo(keyItemFingerprint2)
.hasSameHashCodeAs(keyItemFingerprint2);
}
@Test
void twoInstanceForTheDifferentKeyShouldNotBeEqual() {
KeyItemFingerprint keyItemFingerprint1 = new KeyItemFingerprint(FINGERPRINT_1);
KeyItemFingerprint keyItemFingerprint2 = new KeyItemFingerprint(FINGERPRINT_2);
assertThat(keyItemFingerprint1)
.isNotSameAs(keyItemFingerprint2)
.isNotEqualTo(keyItemFingerprint2)
.doesNotHaveSameHashCodeAs(keyItemFingerprint2);
}
@Test
void matchForMasterKey() {
KeyItemFingerprint keyItemFingerprint = new KeyItemFingerprint(FINGERPRINT_1);
| // Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeyInfo aKeyInfo(String fingerprint) {
// return KeyInfo.builder().fingerprint(new KeyFingerprint(fingerprint)).build();
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
// Path: src/test/java/org/simplify4u/plugins/keysmap/KeyItemFingerprintTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.simplify4u.plugins.TestUtils.aKeyInfo;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.Test;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
public class KeyItemFingerprintTest {
private static final String FINGERPRINT_1 = "0x9ABC DEF0 1234 5678 9ABC DEF0 1234 5678 9ABC DEF0";
private static final String FINGERPRINT_2 = "0x9ABC DEF0 1234 5678 9ABC DEF0 1234 5678 9ABC 0000";
@Test
void twoInstanceForTheSameKeyShouldBeEqual() {
KeyItemFingerprint keyItemFingerprint1 = new KeyItemFingerprint(FINGERPRINT_1);
KeyItemFingerprint keyItemFingerprint2 = new KeyItemFingerprint(FINGERPRINT_1);
assertThat(keyItemFingerprint1)
.isNotSameAs(keyItemFingerprint2)
.isEqualTo(keyItemFingerprint2)
.hasSameHashCodeAs(keyItemFingerprint2);
}
@Test
void twoInstanceForTheDifferentKeyShouldNotBeEqual() {
KeyItemFingerprint keyItemFingerprint1 = new KeyItemFingerprint(FINGERPRINT_1);
KeyItemFingerprint keyItemFingerprint2 = new KeyItemFingerprint(FINGERPRINT_2);
assertThat(keyItemFingerprint1)
.isNotSameAs(keyItemFingerprint2)
.isNotEqualTo(keyItemFingerprint2)
.doesNotHaveSameHashCodeAs(keyItemFingerprint2);
}
@Test
void matchForMasterKey() {
KeyItemFingerprint keyItemFingerprint = new KeyItemFingerprint(FINGERPRINT_1);
| KeyInfo keyInfo = aKeyInfo(FINGERPRINT_1); |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/keysmap/KeyItemFingerprintTest.java | // Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeyInfo aKeyInfo(String fingerprint) {
// return KeyInfo.builder().fingerprint(new KeyFingerprint(fingerprint)).build();
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.simplify4u.plugins.TestUtils.aKeyInfo;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.Test; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
public class KeyItemFingerprintTest {
private static final String FINGERPRINT_1 = "0x9ABC DEF0 1234 5678 9ABC DEF0 1234 5678 9ABC DEF0";
private static final String FINGERPRINT_2 = "0x9ABC DEF0 1234 5678 9ABC DEF0 1234 5678 9ABC 0000";
@Test
void twoInstanceForTheSameKeyShouldBeEqual() {
KeyItemFingerprint keyItemFingerprint1 = new KeyItemFingerprint(FINGERPRINT_1);
KeyItemFingerprint keyItemFingerprint2 = new KeyItemFingerprint(FINGERPRINT_1);
assertThat(keyItemFingerprint1)
.isNotSameAs(keyItemFingerprint2)
.isEqualTo(keyItemFingerprint2)
.hasSameHashCodeAs(keyItemFingerprint2);
}
@Test
void twoInstanceForTheDifferentKeyShouldNotBeEqual() {
KeyItemFingerprint keyItemFingerprint1 = new KeyItemFingerprint(FINGERPRINT_1);
KeyItemFingerprint keyItemFingerprint2 = new KeyItemFingerprint(FINGERPRINT_2);
assertThat(keyItemFingerprint1)
.isNotSameAs(keyItemFingerprint2)
.isNotEqualTo(keyItemFingerprint2)
.doesNotHaveSameHashCodeAs(keyItemFingerprint2);
}
@Test
void matchForMasterKey() {
KeyItemFingerprint keyItemFingerprint = new KeyItemFingerprint(FINGERPRINT_1);
| // Path: src/test/java/org/simplify4u/plugins/TestUtils.java
// public static KeyInfo aKeyInfo(String fingerprint) {
// return KeyInfo.builder().fingerprint(new KeyFingerprint(fingerprint)).build();
// }
//
// Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
// Path: src/test/java/org/simplify4u/plugins/keysmap/KeyItemFingerprintTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.simplify4u.plugins.TestUtils.aKeyInfo;
import org.simplify4u.plugins.pgp.KeyInfo;
import org.testng.annotations.Test;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
public class KeyItemFingerprintTest {
private static final String FINGERPRINT_1 = "0x9ABC DEF0 1234 5678 9ABC DEF0 1234 5678 9ABC DEF0";
private static final String FINGERPRINT_2 = "0x9ABC DEF0 1234 5678 9ABC DEF0 1234 5678 9ABC 0000";
@Test
void twoInstanceForTheSameKeyShouldBeEqual() {
KeyItemFingerprint keyItemFingerprint1 = new KeyItemFingerprint(FINGERPRINT_1);
KeyItemFingerprint keyItemFingerprint2 = new KeyItemFingerprint(FINGERPRINT_1);
assertThat(keyItemFingerprint1)
.isNotSameAs(keyItemFingerprint2)
.isEqualTo(keyItemFingerprint2)
.hasSameHashCodeAs(keyItemFingerprint2);
}
@Test
void twoInstanceForTheDifferentKeyShouldNotBeEqual() {
KeyItemFingerprint keyItemFingerprint1 = new KeyItemFingerprint(FINGERPRINT_1);
KeyItemFingerprint keyItemFingerprint2 = new KeyItemFingerprint(FINGERPRINT_2);
assertThat(keyItemFingerprint1)
.isNotSameAs(keyItemFingerprint2)
.isNotEqualTo(keyItemFingerprint2)
.doesNotHaveSameHashCodeAs(keyItemFingerprint2);
}
@Test
void matchForMasterKey() {
KeyItemFingerprint keyItemFingerprint = new KeyItemFingerprint(FINGERPRINT_1);
| KeyInfo keyInfo = aKeyInfo(FINGERPRINT_1); |
s4u/pgpverify-maven-plugin | src/main/java/org/simplify4u/plugins/keysmap/KeyItem.java | // Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
| import org.simplify4u.plugins.pgp.KeyInfo; | /*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* Describe single key item in keysMap.
*/
interface KeyItem {
/**
* Artifact can has no signature.
*
* @return signature status
*/
default boolean isNoSignature() {
return false;
}
/**
* Artifact can has broken signature.
*
* @return broken signature status
*/
default boolean isBrokenSignature() {
return false;
}
/**
* Key for signature can be not found on public key servers.
*
* @return key missing status
*/
default boolean isKeyMissing() {
return false;
}
/**
* Check if current key mach with given key.
*
* @param keyInfo key to test
*
* @return key matching status
*/ | // Path: src/main/java/org/simplify4u/plugins/pgp/KeyInfo.java
// @Builder
// @Value
// public class KeyInfo {
//
// @NonNull
// KeyFingerprint fingerprint;
//
// KeyFingerprint master;
//
// Collection<String> uids;
//
// int version;
// int algorithm;
//
// int bits;
//
// Date date;
// }
// Path: src/main/java/org/simplify4u/plugins/keysmap/KeyItem.java
import org.simplify4u.plugins.pgp.KeyInfo;
/*
* Copyright 2021 Slawomir Jaranowski
*
* 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 org.simplify4u.plugins.keysmap;
/**
* Describe single key item in keysMap.
*/
interface KeyItem {
/**
* Artifact can has no signature.
*
* @return signature status
*/
default boolean isNoSignature() {
return false;
}
/**
* Artifact can has broken signature.
*
* @return broken signature status
*/
default boolean isBrokenSignature() {
return false;
}
/**
* Key for signature can be not found on public key servers.
*
* @return key missing status
*/
default boolean isKeyMissing() {
return false;
}
/**
* Check if current key mach with given key.
*
* @param keyInfo key to test
*
* @return key matching status
*/ | default boolean isKeyMatch(KeyInfo keyInfo) { |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/ValidationChecksumTest.java | // Path: src/main/java/org/simplify4u/plugins/ValidationChecksum.java
// static final class Builder {
//
// private static final String FILENAME_CHECKSUM_PRIOR_VALIDATION = "pgpverify-prior-validation-checksum";
//
// private static final Logger LOG = LoggerFactory.getLogger(Builder.class);
//
// private File file;
//
// private boolean disabled;
//
// private Iterable<Artifact> artifacts;
//
// Builder() {
// }
//
// /**
// * Destination for checksum file.
// *
// * @param directory the target directory
// */
// Builder destination(File directory) {
// this.file = new File(directory, FILENAME_CHECKSUM_PRIOR_VALIDATION);
// return this;
// }
//
// /**
// * Set whether checksum calculation is disabled.
// *
// * @param disabled true if checksum is disabled, false otherwise.
// */
// Builder disabled(boolean disabled) {
// this.disabled = disabled;
// return this;
// }
//
// /**
// * Perform checksum calculation on artifacts.
// *
// * @param artifacts the artifacts as deterministically ordered collection
// */
// Builder artifacts(Iterable<Artifact> artifacts) {
// this.artifacts = requireNonNull(artifacts);
// return this;
// }
//
// /**
// * Build ValidationChecksum instance.
// *
// * @return Returns the validation checksum instance.
// */
// ValidationChecksum build() {
// if (this.artifacts == null) {
// throw new IllegalStateException("artifacts need to be provided");
// }
// return new ValidationChecksum(this.file, this.disabled ? new byte[0] : calculateChecksum());
// }
//
// private byte[] calculateChecksum() {
// final SHA256Digest digest = new SHA256Digest();
// final byte[] result = new byte[digest.getDigestSize()];
// for (final Artifact artifact : this.artifacts) {
// final byte[] id = artifact.getId().getBytes(UTF_8);
// digest.update(id, 0, id.length);
// digest.update((byte) '\0');
// }
// digest.doFinal(result, 0);
// if (LOG.isDebugEnabled()) {
// LOG.debug("Checksum of resolved artifacts: {}", ByteUtils.toHexString(result, "0x", ""));
// }
// return result;
// }
// }
| import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import org.apache.maven.artifact.Artifact;
import org.simplify4u.plugins.ValidationChecksum.Builder;
import org.testng.annotations.AfterMethod; | /*
* Copyright 2020 Danny van Heumen
*
* 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 org.simplify4u.plugins;
public class ValidationChecksumTest {
private File checksumdirectory = null;
@BeforeMethod
public void setUp() throws IOException {
this.checksumdirectory = Files.createTempDirectory("ValidationChecksumTest").toFile();
}
@AfterMethod
public void tearDown() throws IOException {
Files.walk(checksumdirectory.toPath())
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
@Test
public void testValidationChecksumBuilderNullFile() { | // Path: src/main/java/org/simplify4u/plugins/ValidationChecksum.java
// static final class Builder {
//
// private static final String FILENAME_CHECKSUM_PRIOR_VALIDATION = "pgpverify-prior-validation-checksum";
//
// private static final Logger LOG = LoggerFactory.getLogger(Builder.class);
//
// private File file;
//
// private boolean disabled;
//
// private Iterable<Artifact> artifacts;
//
// Builder() {
// }
//
// /**
// * Destination for checksum file.
// *
// * @param directory the target directory
// */
// Builder destination(File directory) {
// this.file = new File(directory, FILENAME_CHECKSUM_PRIOR_VALIDATION);
// return this;
// }
//
// /**
// * Set whether checksum calculation is disabled.
// *
// * @param disabled true if checksum is disabled, false otherwise.
// */
// Builder disabled(boolean disabled) {
// this.disabled = disabled;
// return this;
// }
//
// /**
// * Perform checksum calculation on artifacts.
// *
// * @param artifacts the artifacts as deterministically ordered collection
// */
// Builder artifacts(Iterable<Artifact> artifacts) {
// this.artifacts = requireNonNull(artifacts);
// return this;
// }
//
// /**
// * Build ValidationChecksum instance.
// *
// * @return Returns the validation checksum instance.
// */
// ValidationChecksum build() {
// if (this.artifacts == null) {
// throw new IllegalStateException("artifacts need to be provided");
// }
// return new ValidationChecksum(this.file, this.disabled ? new byte[0] : calculateChecksum());
// }
//
// private byte[] calculateChecksum() {
// final SHA256Digest digest = new SHA256Digest();
// final byte[] result = new byte[digest.getDigestSize()];
// for (final Artifact artifact : this.artifacts) {
// final byte[] id = artifact.getId().getBytes(UTF_8);
// digest.update(id, 0, id.length);
// digest.update((byte) '\0');
// }
// digest.doFinal(result, 0);
// if (LOG.isDebugEnabled()) {
// LOG.debug("Checksum of resolved artifacts: {}", ByteUtils.toHexString(result, "0x", ""));
// }
// return result;
// }
// }
// Path: src/test/java/org/simplify4u/plugins/ValidationChecksumTest.java
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import org.apache.maven.artifact.Artifact;
import org.simplify4u.plugins.ValidationChecksum.Builder;
import org.testng.annotations.AfterMethod;
/*
* Copyright 2020 Danny van Heumen
*
* 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 org.simplify4u.plugins;
public class ValidationChecksumTest {
private File checksumdirectory = null;
@BeforeMethod
public void setUp() throws IOException {
this.checksumdirectory = Files.createTempDirectory("ValidationChecksumTest").toFile();
}
@AfterMethod
public void tearDown() throws IOException {
Files.walk(checksumdirectory.toPath())
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
@Test
public void testValidationChecksumBuilderNullFile() { | new ValidationChecksum.Builder().destination(null).artifacts(emptyList()).build(); |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/ArtifactResolverTest.java | // Path: src/main/java/org/simplify4u/plugins/ArtifactResolver.java
// public static final class Configuration {
//
// final SkipFilter dependencyFilter;
// final SkipFilter pluginFilter;
// final boolean verifyPomFiles;
// final boolean verifyPlugins;
// final boolean verifyPluginDependencies;
// final boolean verifyAtypical;
//
// /**
// * Constructor.
// *
// * @param dependencyFilter filter for evaluating dependencies
// * @param pluginFilter filter for evaluating plugins
// * @param verifyPomFiles verify POM files as well
// * @param verifyPlugins verify build plugins as well
// * @param verifyPluginDependencies verify all dependencies of build plug-ins.
// * @param verifyAtypical verify dependencies in a-typical locations, such as maven-compiler-plugin's
// */
// public Configuration(SkipFilter dependencyFilter, SkipFilter pluginFilter, boolean verifyPomFiles,
// boolean verifyPlugins, boolean verifyPluginDependencies, boolean verifyAtypical) {
// this.dependencyFilter = requireNonNull(dependencyFilter);
// this.pluginFilter = requireNonNull(pluginFilter);
// this.verifyPomFiles = verifyPomFiles;
// this.verifyPlugins = verifyPlugins || verifyPluginDependencies;
// this.verifyPluginDependencies = verifyPluginDependencies;
// this.verifyAtypical = verifyAtypical;
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/skipfilters/CompositeSkipper.java
// public final class CompositeSkipper implements SkipFilter {
//
// private final Iterable<SkipFilter> filters;
//
// /**
// * Constructor to compose any number of {@link SkipFilter}s.
// *
// * @param filters the filters
// */
// public CompositeSkipper(Iterable<SkipFilter> filters) {
// this.filters = requireNonNull(filters);
// }
//
// /**
// * Constructor to compose any number of {@link SkipFilter}s.
// *
// * @param filters the filters
// */
// public CompositeSkipper(SkipFilter... filters) {
// if (stream(filters).anyMatch(Objects::isNull)) {
// throw new IllegalArgumentException("filters cannot contain null");
// }
// this.filters = asList(filters);
// }
//
// @Override
// public boolean shouldSkipArtifact(Artifact artifact) {
// requireNonNull(artifact);
// for (final SkipFilter filter : this.filters) {
// if (filter.shouldSkipArtifact(artifact)) {
// return true;
// }
// }
// return false;
// }
// }
| import java.util.Map;
import java.util.Set;
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.artifact.handler.DefaultArtifactHandler;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.repository.RepositorySystem;
import org.assertj.core.api.Condition;
import org.mockito.Mock;
import org.mockito.stubbing.Answer;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.ArtifactResolver.Configuration;
import org.simplify4u.plugins.skipfilters.CompositeSkipper;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test; | when(project.getRemoteArtifactRepositories()).thenReturn(emptyList());
resolver = new ArtifactResolver(repositorySystem, session);
}
@Test
public void testConstructArtifactResolverWithNull() {
reset(session, project);
assertThatCode(() -> new ArtifactResolver(null, null))
.isExactlyInstanceOf(NullPointerException.class);
assertThatCode(() -> new ArtifactResolver(null, session))
.isExactlyInstanceOf(NullPointerException.class);
doThrow(new NullPointerException()).when(session).getLocalRepository();
assertThatCode(() -> new ArtifactResolver(repositorySystem, session))
.isExactlyInstanceOf(NullPointerException.class);
doReturn(localRepository).when(session).getLocalRepository();
doThrow(new NullPointerException()).when(session).getCurrentProject();
assertThatCode(() -> new ArtifactResolver(repositorySystem, session))
.isExactlyInstanceOf(NullPointerException.class);
}
@Test
public void testResolveProjectArtifactsEmpty() throws MojoExecutionException {
// given | // Path: src/main/java/org/simplify4u/plugins/ArtifactResolver.java
// public static final class Configuration {
//
// final SkipFilter dependencyFilter;
// final SkipFilter pluginFilter;
// final boolean verifyPomFiles;
// final boolean verifyPlugins;
// final boolean verifyPluginDependencies;
// final boolean verifyAtypical;
//
// /**
// * Constructor.
// *
// * @param dependencyFilter filter for evaluating dependencies
// * @param pluginFilter filter for evaluating plugins
// * @param verifyPomFiles verify POM files as well
// * @param verifyPlugins verify build plugins as well
// * @param verifyPluginDependencies verify all dependencies of build plug-ins.
// * @param verifyAtypical verify dependencies in a-typical locations, such as maven-compiler-plugin's
// */
// public Configuration(SkipFilter dependencyFilter, SkipFilter pluginFilter, boolean verifyPomFiles,
// boolean verifyPlugins, boolean verifyPluginDependencies, boolean verifyAtypical) {
// this.dependencyFilter = requireNonNull(dependencyFilter);
// this.pluginFilter = requireNonNull(pluginFilter);
// this.verifyPomFiles = verifyPomFiles;
// this.verifyPlugins = verifyPlugins || verifyPluginDependencies;
// this.verifyPluginDependencies = verifyPluginDependencies;
// this.verifyAtypical = verifyAtypical;
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/skipfilters/CompositeSkipper.java
// public final class CompositeSkipper implements SkipFilter {
//
// private final Iterable<SkipFilter> filters;
//
// /**
// * Constructor to compose any number of {@link SkipFilter}s.
// *
// * @param filters the filters
// */
// public CompositeSkipper(Iterable<SkipFilter> filters) {
// this.filters = requireNonNull(filters);
// }
//
// /**
// * Constructor to compose any number of {@link SkipFilter}s.
// *
// * @param filters the filters
// */
// public CompositeSkipper(SkipFilter... filters) {
// if (stream(filters).anyMatch(Objects::isNull)) {
// throw new IllegalArgumentException("filters cannot contain null");
// }
// this.filters = asList(filters);
// }
//
// @Override
// public boolean shouldSkipArtifact(Artifact artifact) {
// requireNonNull(artifact);
// for (final SkipFilter filter : this.filters) {
// if (filter.shouldSkipArtifact(artifact)) {
// return true;
// }
// }
// return false;
// }
// }
// Path: src/test/java/org/simplify4u/plugins/ArtifactResolverTest.java
import java.util.Map;
import java.util.Set;
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.artifact.handler.DefaultArtifactHandler;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.repository.RepositorySystem;
import org.assertj.core.api.Condition;
import org.mockito.Mock;
import org.mockito.stubbing.Answer;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.ArtifactResolver.Configuration;
import org.simplify4u.plugins.skipfilters.CompositeSkipper;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
when(project.getRemoteArtifactRepositories()).thenReturn(emptyList());
resolver = new ArtifactResolver(repositorySystem, session);
}
@Test
public void testConstructArtifactResolverWithNull() {
reset(session, project);
assertThatCode(() -> new ArtifactResolver(null, null))
.isExactlyInstanceOf(NullPointerException.class);
assertThatCode(() -> new ArtifactResolver(null, session))
.isExactlyInstanceOf(NullPointerException.class);
doThrow(new NullPointerException()).when(session).getLocalRepository();
assertThatCode(() -> new ArtifactResolver(repositorySystem, session))
.isExactlyInstanceOf(NullPointerException.class);
doReturn(localRepository).when(session).getLocalRepository();
doThrow(new NullPointerException()).when(session).getCurrentProject();
assertThatCode(() -> new ArtifactResolver(repositorySystem, session))
.isExactlyInstanceOf(NullPointerException.class);
}
@Test
public void testResolveProjectArtifactsEmpty() throws MojoExecutionException {
// given | Configuration config = new Configuration(new CompositeSkipper(emptyList()), |
s4u/pgpverify-maven-plugin | src/test/java/org/simplify4u/plugins/ArtifactResolverTest.java | // Path: src/main/java/org/simplify4u/plugins/ArtifactResolver.java
// public static final class Configuration {
//
// final SkipFilter dependencyFilter;
// final SkipFilter pluginFilter;
// final boolean verifyPomFiles;
// final boolean verifyPlugins;
// final boolean verifyPluginDependencies;
// final boolean verifyAtypical;
//
// /**
// * Constructor.
// *
// * @param dependencyFilter filter for evaluating dependencies
// * @param pluginFilter filter for evaluating plugins
// * @param verifyPomFiles verify POM files as well
// * @param verifyPlugins verify build plugins as well
// * @param verifyPluginDependencies verify all dependencies of build plug-ins.
// * @param verifyAtypical verify dependencies in a-typical locations, such as maven-compiler-plugin's
// */
// public Configuration(SkipFilter dependencyFilter, SkipFilter pluginFilter, boolean verifyPomFiles,
// boolean verifyPlugins, boolean verifyPluginDependencies, boolean verifyAtypical) {
// this.dependencyFilter = requireNonNull(dependencyFilter);
// this.pluginFilter = requireNonNull(pluginFilter);
// this.verifyPomFiles = verifyPomFiles;
// this.verifyPlugins = verifyPlugins || verifyPluginDependencies;
// this.verifyPluginDependencies = verifyPluginDependencies;
// this.verifyAtypical = verifyAtypical;
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/skipfilters/CompositeSkipper.java
// public final class CompositeSkipper implements SkipFilter {
//
// private final Iterable<SkipFilter> filters;
//
// /**
// * Constructor to compose any number of {@link SkipFilter}s.
// *
// * @param filters the filters
// */
// public CompositeSkipper(Iterable<SkipFilter> filters) {
// this.filters = requireNonNull(filters);
// }
//
// /**
// * Constructor to compose any number of {@link SkipFilter}s.
// *
// * @param filters the filters
// */
// public CompositeSkipper(SkipFilter... filters) {
// if (stream(filters).anyMatch(Objects::isNull)) {
// throw new IllegalArgumentException("filters cannot contain null");
// }
// this.filters = asList(filters);
// }
//
// @Override
// public boolean shouldSkipArtifact(Artifact artifact) {
// requireNonNull(artifact);
// for (final SkipFilter filter : this.filters) {
// if (filter.shouldSkipArtifact(artifact)) {
// return true;
// }
// }
// return false;
// }
// }
| import java.util.Map;
import java.util.Set;
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.artifact.handler.DefaultArtifactHandler;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.repository.RepositorySystem;
import org.assertj.core.api.Condition;
import org.mockito.Mock;
import org.mockito.stubbing.Answer;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.ArtifactResolver.Configuration;
import org.simplify4u.plugins.skipfilters.CompositeSkipper;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test; | when(project.getRemoteArtifactRepositories()).thenReturn(emptyList());
resolver = new ArtifactResolver(repositorySystem, session);
}
@Test
public void testConstructArtifactResolverWithNull() {
reset(session, project);
assertThatCode(() -> new ArtifactResolver(null, null))
.isExactlyInstanceOf(NullPointerException.class);
assertThatCode(() -> new ArtifactResolver(null, session))
.isExactlyInstanceOf(NullPointerException.class);
doThrow(new NullPointerException()).when(session).getLocalRepository();
assertThatCode(() -> new ArtifactResolver(repositorySystem, session))
.isExactlyInstanceOf(NullPointerException.class);
doReturn(localRepository).when(session).getLocalRepository();
doThrow(new NullPointerException()).when(session).getCurrentProject();
assertThatCode(() -> new ArtifactResolver(repositorySystem, session))
.isExactlyInstanceOf(NullPointerException.class);
}
@Test
public void testResolveProjectArtifactsEmpty() throws MojoExecutionException {
// given | // Path: src/main/java/org/simplify4u/plugins/ArtifactResolver.java
// public static final class Configuration {
//
// final SkipFilter dependencyFilter;
// final SkipFilter pluginFilter;
// final boolean verifyPomFiles;
// final boolean verifyPlugins;
// final boolean verifyPluginDependencies;
// final boolean verifyAtypical;
//
// /**
// * Constructor.
// *
// * @param dependencyFilter filter for evaluating dependencies
// * @param pluginFilter filter for evaluating plugins
// * @param verifyPomFiles verify POM files as well
// * @param verifyPlugins verify build plugins as well
// * @param verifyPluginDependencies verify all dependencies of build plug-ins.
// * @param verifyAtypical verify dependencies in a-typical locations, such as maven-compiler-plugin's
// */
// public Configuration(SkipFilter dependencyFilter, SkipFilter pluginFilter, boolean verifyPomFiles,
// boolean verifyPlugins, boolean verifyPluginDependencies, boolean verifyAtypical) {
// this.dependencyFilter = requireNonNull(dependencyFilter);
// this.pluginFilter = requireNonNull(pluginFilter);
// this.verifyPomFiles = verifyPomFiles;
// this.verifyPlugins = verifyPlugins || verifyPluginDependencies;
// this.verifyPluginDependencies = verifyPluginDependencies;
// this.verifyAtypical = verifyAtypical;
// }
// }
//
// Path: src/main/java/org/simplify4u/plugins/skipfilters/CompositeSkipper.java
// public final class CompositeSkipper implements SkipFilter {
//
// private final Iterable<SkipFilter> filters;
//
// /**
// * Constructor to compose any number of {@link SkipFilter}s.
// *
// * @param filters the filters
// */
// public CompositeSkipper(Iterable<SkipFilter> filters) {
// this.filters = requireNonNull(filters);
// }
//
// /**
// * Constructor to compose any number of {@link SkipFilter}s.
// *
// * @param filters the filters
// */
// public CompositeSkipper(SkipFilter... filters) {
// if (stream(filters).anyMatch(Objects::isNull)) {
// throw new IllegalArgumentException("filters cannot contain null");
// }
// this.filters = asList(filters);
// }
//
// @Override
// public boolean shouldSkipArtifact(Artifact artifact) {
// requireNonNull(artifact);
// for (final SkipFilter filter : this.filters) {
// if (filter.shouldSkipArtifact(artifact)) {
// return true;
// }
// }
// return false;
// }
// }
// Path: src/test/java/org/simplify4u/plugins/ArtifactResolverTest.java
import java.util.Map;
import java.util.Set;
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.artifact.handler.DefaultArtifactHandler;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.repository.RepositorySystem;
import org.assertj.core.api.Condition;
import org.mockito.Mock;
import org.mockito.stubbing.Answer;
import org.mockito.testng.MockitoTestNGListener;
import org.simplify4u.plugins.ArtifactResolver.Configuration;
import org.simplify4u.plugins.skipfilters.CompositeSkipper;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
when(project.getRemoteArtifactRepositories()).thenReturn(emptyList());
resolver = new ArtifactResolver(repositorySystem, session);
}
@Test
public void testConstructArtifactResolverWithNull() {
reset(session, project);
assertThatCode(() -> new ArtifactResolver(null, null))
.isExactlyInstanceOf(NullPointerException.class);
assertThatCode(() -> new ArtifactResolver(null, session))
.isExactlyInstanceOf(NullPointerException.class);
doThrow(new NullPointerException()).when(session).getLocalRepository();
assertThatCode(() -> new ArtifactResolver(repositorySystem, session))
.isExactlyInstanceOf(NullPointerException.class);
doReturn(localRepository).when(session).getLocalRepository();
doThrow(new NullPointerException()).when(session).getCurrentProject();
assertThatCode(() -> new ArtifactResolver(repositorySystem, session))
.isExactlyInstanceOf(NullPointerException.class);
}
@Test
public void testResolveProjectArtifactsEmpty() throws MojoExecutionException {
// given | Configuration config = new Configuration(new CompositeSkipper(emptyList()), |
xxv/Units | src/net/sourceforge/unitsinjava/Parser.java | // Path: src/net/sourceforge/unitsinjava/Source.java
// public interface Source
// {
// boolean created();
//
// int end();
//
// char at(int p);
//
// String at(int p, int q);
//
// String where(int p);
// }
| import net.sourceforge.unitsinjava.Source; | //=========================================================================
//
// This file was generated by Mouse 1.3 at 2010-11-02 16:19:27 GMT\nfrom
// grammar 'D:\Units\ units\grammar.peg'.
//
//=========================================================================
package net.sourceforge.unitsinjava;
public class Parser extends net.sourceforge.unitsinjava.ParserBase
{
final Semantics sem;
//=======================================================================
//
// Initialization
//
//=======================================================================
//-------------------------------------------------------------------
// Constructor
//-------------------------------------------------------------------
public Parser()
{
sem = new Semantics();
sem.rule = this;
super.sem = sem;
}
//-------------------------------------------------------------------
// Run the parser
//------------------------------------------------------------------- | // Path: src/net/sourceforge/unitsinjava/Source.java
// public interface Source
// {
// boolean created();
//
// int end();
//
// char at(int p);
//
// String at(int p, int q);
//
// String where(int p);
// }
// Path: src/net/sourceforge/unitsinjava/Parser.java
import net.sourceforge.unitsinjava.Source;
//=========================================================================
//
// This file was generated by Mouse 1.3 at 2010-11-02 16:19:27 GMT\nfrom
// grammar 'D:\Units\ units\grammar.peg'.
//
//=========================================================================
package net.sourceforge.unitsinjava;
public class Parser extends net.sourceforge.unitsinjava.ParserBase
{
final Semantics sem;
//=======================================================================
//
// Initialization
//
//=======================================================================
//-------------------------------------------------------------------
// Constructor
//-------------------------------------------------------------------
public Parser()
{
sem = new Semantics();
sem.rule = this;
super.sem = sem;
}
//-------------------------------------------------------------------
// Run the parser
//------------------------------------------------------------------- | public boolean parse(Source src) |
xxv/Units | src/net/sourceforge/unitsinjava/ParserBase.java | // Path: src/net/sourceforge/unitsinjava/Source.java
// public interface Source
// {
// boolean created();
//
// int end();
//
// char at(int p);
//
// String at(int p, int q);
//
// String where(int p);
// }
| import net.sourceforge.unitsinjava.Source;
import java.util.Vector; | //=========================================================================
//
// Part of PEG parser generator Mouse.
//
// Copyright (C) 2009, 2010 by Roman R. Redziejowski (www.romanredz.se).
//
// 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.
//
//-------------------------------------------------------------------------
//
// Change log
// 090720 Created for Mouse 1.1.
// Version 1.2
// 100320 Bug fix in accept(): upgrade error info on success.
// 100320 Bug fix in rejectNot(): backtrack before registering failure.
// Version 1.3
// 100429 Bug fix in errMerge(Phrase): assignment to errText replaced
// by clear + addAll (assignment produced alias resulting in
// explosion of errText in memo version).
//
//=========================================================================
package net.sourceforge.unitsinjava;
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
//
// ParserBase
//
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
public class ParserBase implements net.sourceforge.unitsinjava.CurrentRule
{
//-------------------------------------------------------------------
// Input
//------------------------------------------------------------------- | // Path: src/net/sourceforge/unitsinjava/Source.java
// public interface Source
// {
// boolean created();
//
// int end();
//
// char at(int p);
//
// String at(int p, int q);
//
// String where(int p);
// }
// Path: src/net/sourceforge/unitsinjava/ParserBase.java
import net.sourceforge.unitsinjava.Source;
import java.util.Vector;
//=========================================================================
//
// Part of PEG parser generator Mouse.
//
// Copyright (C) 2009, 2010 by Roman R. Redziejowski (www.romanredz.se).
//
// 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.
//
//-------------------------------------------------------------------------
//
// Change log
// 090720 Created for Mouse 1.1.
// Version 1.2
// 100320 Bug fix in accept(): upgrade error info on success.
// 100320 Bug fix in rejectNot(): backtrack before registering failure.
// Version 1.3
// 100429 Bug fix in errMerge(Phrase): assignment to errText replaced
// by clear + addAll (assignment produced alias resulting in
// explosion of errText in memo version).
//
//=========================================================================
package net.sourceforge.unitsinjava;
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
//
// ParserBase
//
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
public class ParserBase implements net.sourceforge.unitsinjava.CurrentRule
{
//-------------------------------------------------------------------
// Input
//------------------------------------------------------------------- | Source source; // Source of text to parse |
interedition/collatex | collatex-core/src/test/java/eu/interedition/collatex/dekker/BeckettTest.java | // Path: collatex-core/src/main/java/eu/interedition/collatex/matching/Matches.java
// public class Matches {
//
// public final Map<Token, List<VariantGraph.Vertex>> allMatches;
// public final Set<Token> unmatchedInWitness;
// public final Set<Token> ambiguousInWitness;
// public final Set<Token> uniqueInWitness;
//
// public static Matches between(final Iterable<VariantGraph.Vertex> vertices, final Iterable<Token> witnessTokens, Comparator<Token> comparator) {
//
// final Map<Token, List<VariantGraph.Vertex>> allMatches = new HashMap<>();
//
// StreamUtil.stream(vertices).forEach(vertex ->
// vertex.tokens().stream().findFirst().ifPresent(baseToken ->
// StreamUtil.stream(witnessTokens)
// .filter(witnessToken -> comparator.compare(baseToken, witnessToken) == 0)
// .forEach(matchingToken -> allMatches.computeIfAbsent(matchingToken, t -> new ArrayList<>()).add(vertex))));
//
// final Set<Token> unmatchedInWitness = StreamUtil.stream(witnessTokens)
// .filter(t -> !allMatches.containsKey(t))
// .collect(Collectors.toCollection(LinkedHashSet::new));
//
// final Set<VariantGraph.Vertex> ambiguousInBase = allMatches.values().stream()
// .flatMap(List::stream)
// .collect(Collectors.toMap(Function.identity(), v -> 1, (a, b) -> a + b))
// .entrySet()
// .stream()
// .filter(v -> v.getValue() > 1)
// .map(Map.Entry::getKey)
// .collect(Collectors.toCollection(LinkedHashSet::new));
//
// // (have to check: base -> witness, and witness -> base)
// final Set<Token> ambiguousInWitness = Stream.concat(
// StreamUtil.stream(witnessTokens)
// .filter(t -> allMatches.getOrDefault(t, Collections.emptyList()).size() > 1),
//
// allMatches.entrySet().stream()
// .filter(match -> match.getValue().stream().anyMatch(ambiguousInBase::contains))
// .map(Map.Entry::getKey)
// ).collect(Collectors.toCollection(LinkedHashSet::new));
//
// // sure tokens
// // have to check unsure tokens because of (base -> witness && witness -> base)
// final Set<Token> uniqueInWitness = StreamUtil.stream(witnessTokens)
// .filter(t -> allMatches.getOrDefault(t, Collections.emptyList()).size() == 1 && !ambiguousInWitness.contains(t))
// .collect(Collectors.toCollection(LinkedHashSet::new));
//
// return new Matches(allMatches, unmatchedInWitness, ambiguousInWitness, uniqueInWitness);
// }
//
// private Matches(Map<Token, List<VariantGraph.Vertex>> allMatches, Set<Token> unmatchedInWitness, Set<Token> ambiguousInWitness, Set<Token> uniqueInWitness) {
// this.allMatches = Collections.unmodifiableMap(allMatches);
// this.unmatchedInWitness = Collections.unmodifiableSet(unmatchedInWitness);
// this.ambiguousInWitness = Collections.unmodifiableSet(ambiguousInWitness);
// this.uniqueInWitness = Collections.unmodifiableSet(uniqueInWitness);
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import eu.interedition.collatex.*;
import eu.interedition.collatex.matching.EqualityTokenComparator;
import eu.interedition.collatex.matching.Matches;
import eu.interedition.collatex.simple.SimpleToken;
import eu.interedition.collatex.simple.SimpleWitness;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import static eu.interedition.collatex.dekker.Match.PHRASE_MATCH_TO_TOKENS; | /*
* Copyright (c) 2015 The Interedition Development Group.
*
* This file is part of CollateX.
*
* CollateX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CollateX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CollateX. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.interedition.collatex.dekker;
public class BeckettTest extends AbstractTest {
/**
* The ranking of vertices in the transposition detector should only
* rank matched vertices!!!
*/
@Test
public void testBeckettStrangeTransposition() {
SimpleWitness[] w = createWitnesses("People with things, people without things, things without people, what does it matter. I'm confident I can soon scatter them.", "People with things, people without things, things without people, what does it matter, it will not take me long to scatter them.", "People with things, people without things, things without people, what does it matter, I flatter myself it will not take me long to scatter them, whenever I choose, to the winds.");
final VariantGraph graph = new VariantGraph();
InspectableCollationAlgorithm algo = (InspectableCollationAlgorithm) CollationAlgorithmFactory.dekker(new EqualityTokenComparator());
algo.collate(graph, w);
// List<List<Match>> phraseMatches = algo.getPhraseMatches();
// for (List<Match> phraseMatch: phraseMatches) {
// System.out.println(SimpleToken.toString(PHRASE_MATCH_TO_TOKENS.apply(phraseMatch)));
// }
assertEquals(0, algo.getTranspositions().size());
}
@Test
public void dirkVincent() {
final SimpleWitness[] w = createWitnesses(//
"Its soft light neither daylight nor moonlight nor starlight nor any light he could remember from the days & nights when day followed night & vice versa.",//
"Its soft changeless light unlike any light he could remember from the days and nights when day followed hard on night and vice versa.");
final VariantGraph graph = collate(w[0]); | // Path: collatex-core/src/main/java/eu/interedition/collatex/matching/Matches.java
// public class Matches {
//
// public final Map<Token, List<VariantGraph.Vertex>> allMatches;
// public final Set<Token> unmatchedInWitness;
// public final Set<Token> ambiguousInWitness;
// public final Set<Token> uniqueInWitness;
//
// public static Matches between(final Iterable<VariantGraph.Vertex> vertices, final Iterable<Token> witnessTokens, Comparator<Token> comparator) {
//
// final Map<Token, List<VariantGraph.Vertex>> allMatches = new HashMap<>();
//
// StreamUtil.stream(vertices).forEach(vertex ->
// vertex.tokens().stream().findFirst().ifPresent(baseToken ->
// StreamUtil.stream(witnessTokens)
// .filter(witnessToken -> comparator.compare(baseToken, witnessToken) == 0)
// .forEach(matchingToken -> allMatches.computeIfAbsent(matchingToken, t -> new ArrayList<>()).add(vertex))));
//
// final Set<Token> unmatchedInWitness = StreamUtil.stream(witnessTokens)
// .filter(t -> !allMatches.containsKey(t))
// .collect(Collectors.toCollection(LinkedHashSet::new));
//
// final Set<VariantGraph.Vertex> ambiguousInBase = allMatches.values().stream()
// .flatMap(List::stream)
// .collect(Collectors.toMap(Function.identity(), v -> 1, (a, b) -> a + b))
// .entrySet()
// .stream()
// .filter(v -> v.getValue() > 1)
// .map(Map.Entry::getKey)
// .collect(Collectors.toCollection(LinkedHashSet::new));
//
// // (have to check: base -> witness, and witness -> base)
// final Set<Token> ambiguousInWitness = Stream.concat(
// StreamUtil.stream(witnessTokens)
// .filter(t -> allMatches.getOrDefault(t, Collections.emptyList()).size() > 1),
//
// allMatches.entrySet().stream()
// .filter(match -> match.getValue().stream().anyMatch(ambiguousInBase::contains))
// .map(Map.Entry::getKey)
// ).collect(Collectors.toCollection(LinkedHashSet::new));
//
// // sure tokens
// // have to check unsure tokens because of (base -> witness && witness -> base)
// final Set<Token> uniqueInWitness = StreamUtil.stream(witnessTokens)
// .filter(t -> allMatches.getOrDefault(t, Collections.emptyList()).size() == 1 && !ambiguousInWitness.contains(t))
// .collect(Collectors.toCollection(LinkedHashSet::new));
//
// return new Matches(allMatches, unmatchedInWitness, ambiguousInWitness, uniqueInWitness);
// }
//
// private Matches(Map<Token, List<VariantGraph.Vertex>> allMatches, Set<Token> unmatchedInWitness, Set<Token> ambiguousInWitness, Set<Token> uniqueInWitness) {
// this.allMatches = Collections.unmodifiableMap(allMatches);
// this.unmatchedInWitness = Collections.unmodifiableSet(unmatchedInWitness);
// this.ambiguousInWitness = Collections.unmodifiableSet(ambiguousInWitness);
// this.uniqueInWitness = Collections.unmodifiableSet(uniqueInWitness);
// }
//
// }
// Path: collatex-core/src/test/java/eu/interedition/collatex/dekker/BeckettTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import eu.interedition.collatex.*;
import eu.interedition.collatex.matching.EqualityTokenComparator;
import eu.interedition.collatex.matching.Matches;
import eu.interedition.collatex.simple.SimpleToken;
import eu.interedition.collatex.simple.SimpleWitness;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import static eu.interedition.collatex.dekker.Match.PHRASE_MATCH_TO_TOKENS;
/*
* Copyright (c) 2015 The Interedition Development Group.
*
* This file is part of CollateX.
*
* CollateX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CollateX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CollateX. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.interedition.collatex.dekker;
public class BeckettTest extends AbstractTest {
/**
* The ranking of vertices in the transposition detector should only
* rank matched vertices!!!
*/
@Test
public void testBeckettStrangeTransposition() {
SimpleWitness[] w = createWitnesses("People with things, people without things, things without people, what does it matter. I'm confident I can soon scatter them.", "People with things, people without things, things without people, what does it matter, it will not take me long to scatter them.", "People with things, people without things, things without people, what does it matter, I flatter myself it will not take me long to scatter them, whenever I choose, to the winds.");
final VariantGraph graph = new VariantGraph();
InspectableCollationAlgorithm algo = (InspectableCollationAlgorithm) CollationAlgorithmFactory.dekker(new EqualityTokenComparator());
algo.collate(graph, w);
// List<List<Match>> phraseMatches = algo.getPhraseMatches();
// for (List<Match> phraseMatch: phraseMatches) {
// System.out.println(SimpleToken.toString(PHRASE_MATCH_TO_TOKENS.apply(phraseMatch)));
// }
assertEquals(0, algo.getTranspositions().size());
}
@Test
public void dirkVincent() {
final SimpleWitness[] w = createWitnesses(//
"Its soft light neither daylight nor moonlight nor starlight nor any light he could remember from the days & nights when day followed night & vice versa.",//
"Its soft changeless light unlike any light he could remember from the days and nights when day followed hard on night and vice versa.");
final VariantGraph graph = collate(w[0]); | final Map<Token, List<VariantGraph.Vertex>> matches = Matches.between(graph.vertices(), w[1], new EqualityTokenComparator()).allMatches; |
interedition/collatex | collatex-core/src/test/java/eu/interedition/collatex/dekker/legacy/MatchTableLinkerTest.java | // Path: collatex-core/src/main/java/eu/interedition/collatex/matching/StrictEqualityTokenComparator.java
// public class StrictEqualityTokenComparator implements Comparator<Token> {
//
// @Override
// public int compare(Token base, Token witness) {
// final String baseContent = ((SimpleToken) base).getContent();
// final String witnessContent = ((SimpleToken) witness).getContent();
// return baseContent.compareTo(witnessContent);
// }
//
// }
| import java.util.logging.Level;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import eu.interedition.collatex.*;
import eu.interedition.collatex.dekker.DekkerAlgorithm;
import eu.interedition.collatex.dekker.Match;
import eu.interedition.collatex.dekker.PhraseMatchDetector;
import eu.interedition.collatex.matching.EqualityTokenComparator;
import eu.interedition.collatex.matching.StrictEqualityTokenComparator;
import eu.interedition.collatex.simple.SimpleWitness;
import org.junit.Test;
import javax.xml.stream.XMLStreamException;
import java.util.*; | assertTrue(tokensAsString.contains("C:4:'voer'"));
assertTrue(tokensAsString.contains("C:5:'een'"));
assertTrue(tokensAsString.contains("C:7:'grote'"));
assertTrue(tokensAsString.contains("C:8:'stomer'"));
}
// String newLine = System.getProperty("line.separator");
@Test
public void test1() {
SimpleWitness[] sw = createWitnesses("A B C A B", "A B C A B");
VariantGraph vg = collate(sw[0]);
MatchTableLinker linker = new MatchTableLinker();
Map<Token, VariantGraph.Vertex> linkedTokens = linker.link(vg, sw[1], new EqualityTokenComparator());
Set<Token> tokens = linkedTokens.keySet();
Set<String> tokensAsString = new LinkedHashSet<>();
for (Token token : tokens) {
tokensAsString.add(token.toString());
}
assertTrue(tokensAsString.contains("B:0:'a'"));
assertTrue(tokensAsString.contains("B:1:'b'"));
assertTrue(tokensAsString.contains("B:2:'c'"));
assertTrue(tokensAsString.contains("B:3:'a'"));
assertTrue(tokensAsString.contains("B:4:'b'"));
}
@Test
public void testOverDeAtlantischeOceaan() {
int outlierTranspositionsSizeLimit = 1; | // Path: collatex-core/src/main/java/eu/interedition/collatex/matching/StrictEqualityTokenComparator.java
// public class StrictEqualityTokenComparator implements Comparator<Token> {
//
// @Override
// public int compare(Token base, Token witness) {
// final String baseContent = ((SimpleToken) base).getContent();
// final String witnessContent = ((SimpleToken) witness).getContent();
// return baseContent.compareTo(witnessContent);
// }
//
// }
// Path: collatex-core/src/test/java/eu/interedition/collatex/dekker/legacy/MatchTableLinkerTest.java
import java.util.logging.Level;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import eu.interedition.collatex.*;
import eu.interedition.collatex.dekker.DekkerAlgorithm;
import eu.interedition.collatex.dekker.Match;
import eu.interedition.collatex.dekker.PhraseMatchDetector;
import eu.interedition.collatex.matching.EqualityTokenComparator;
import eu.interedition.collatex.matching.StrictEqualityTokenComparator;
import eu.interedition.collatex.simple.SimpleWitness;
import org.junit.Test;
import javax.xml.stream.XMLStreamException;
import java.util.*;
assertTrue(tokensAsString.contains("C:4:'voer'"));
assertTrue(tokensAsString.contains("C:5:'een'"));
assertTrue(tokensAsString.contains("C:7:'grote'"));
assertTrue(tokensAsString.contains("C:8:'stomer'"));
}
// String newLine = System.getProperty("line.separator");
@Test
public void test1() {
SimpleWitness[] sw = createWitnesses("A B C A B", "A B C A B");
VariantGraph vg = collate(sw[0]);
MatchTableLinker linker = new MatchTableLinker();
Map<Token, VariantGraph.Vertex> linkedTokens = linker.link(vg, sw[1], new EqualityTokenComparator());
Set<Token> tokens = linkedTokens.keySet();
Set<String> tokensAsString = new LinkedHashSet<>();
for (Token token : tokens) {
tokensAsString.add(token.toString());
}
assertTrue(tokensAsString.contains("B:0:'a'"));
assertTrue(tokensAsString.contains("B:1:'b'"));
assertTrue(tokensAsString.contains("B:2:'c'"));
assertTrue(tokensAsString.contains("B:3:'a'"));
assertTrue(tokensAsString.contains("B:4:'b'"));
}
@Test
public void testOverDeAtlantischeOceaan() {
int outlierTranspositionsSizeLimit = 1; | collationAlgorithm = new DekkerAlgorithm(new StrictEqualityTokenComparator()); |
PhantomThief/more-lambdas-java | core-jdk9/src/test/java/com/github/phantomthief/util/MoreReflectionTest.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreReflection.java
// @Nullable
// public static StackTraceElement getCallerPlace() {
// return getCallerPlace(MoreReflection.class);
// }
| import static com.github.phantomthief.util.MoreReflection.getCallerPlace;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test; | package com.github.phantomthief.util;
/**
* @author w.vela
* Created on 2018-06-13.
*/
class MoreReflectionTest {
@Test
void testCaller() {
StackTraceElement callerPlace = MyTest.test3();
assertNotNull(callerPlace);
assertEquals("MoreReflectionTest.java", callerPlace.getFileName());
callerPlace = MyTest2.test41();
assertNotNull(callerPlace);
assertEquals("MoreReflectionTest.java", callerPlace.getFileName());
}
static class MyTest {
@Deprecated
static void test() { | // Path: core/src/main/java/com/github/phantomthief/util/MoreReflection.java
// @Nullable
// public static StackTraceElement getCallerPlace() {
// return getCallerPlace(MoreReflection.class);
// }
// Path: core-jdk9/src/test/java/com/github/phantomthief/util/MoreReflectionTest.java
import static com.github.phantomthief.util.MoreReflection.getCallerPlace;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
package com.github.phantomthief.util;
/**
* @author w.vela
* Created on 2018-06-13.
*/
class MoreReflectionTest {
@Test
void testCaller() {
StackTraceElement callerPlace = MyTest.test3();
assertNotNull(callerPlace);
assertEquals("MoreReflectionTest.java", callerPlace.getFileName());
callerPlace = MyTest2.test41();
assertNotNull(callerPlace);
assertEquals("MoreReflectionTest.java", callerPlace.getFileName());
}
static class MyTest {
@Deprecated
static void test() { | System.err.println(getCallerPlace()); |
PhantomThief/more-lambdas-java | core/src/main/java/com/github/phantomthief/concurrent/TimeoutListenableFuture.java | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableRunnable.java
// @FunctionalInterface
// public interface ThrowableRunnable<X extends Throwable> {
//
// void run() throws X;
// }
| import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import com.github.phantomthief.util.ThrowableConsumer;
import com.github.phantomthief.util.ThrowableRunnable;
import com.google.common.util.concurrent.ForwardingListenableFuture;
import com.google.common.util.concurrent.ListenableFuture; | package com.github.phantomthief.concurrent;
/**
* @author w.vela
* Created on 16/5/31.
*/
public class TimeoutListenableFuture<V> extends ForwardingListenableFuture<V> {
private static final Logger logger = getLogger(TimeoutListenableFuture.class);
private final ListenableFuture<V> delegate; | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableRunnable.java
// @FunctionalInterface
// public interface ThrowableRunnable<X extends Throwable> {
//
// void run() throws X;
// }
// Path: core/src/main/java/com/github/phantomthief/concurrent/TimeoutListenableFuture.java
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import com.github.phantomthief.util.ThrowableConsumer;
import com.github.phantomthief.util.ThrowableRunnable;
import com.google.common.util.concurrent.ForwardingListenableFuture;
import com.google.common.util.concurrent.ListenableFuture;
package com.github.phantomthief.concurrent;
/**
* @author w.vela
* Created on 16/5/31.
*/
public class TimeoutListenableFuture<V> extends ForwardingListenableFuture<V> {
private static final Logger logger = getLogger(TimeoutListenableFuture.class);
private final ListenableFuture<V> delegate; | private final List<ThrowableConsumer<TimeoutException, Exception>> timeoutListeners = new ArrayList<>(); |
PhantomThief/more-lambdas-java | core/src/main/java/com/github/phantomthief/concurrent/TimeoutListenableFuture.java | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableRunnable.java
// @FunctionalInterface
// public interface ThrowableRunnable<X extends Throwable> {
//
// void run() throws X;
// }
| import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import com.github.phantomthief.util.ThrowableConsumer;
import com.github.phantomthief.util.ThrowableRunnable;
import com.google.common.util.concurrent.ForwardingListenableFuture;
import com.google.common.util.concurrent.ListenableFuture; | package com.github.phantomthief.concurrent;
/**
* @author w.vela
* Created on 16/5/31.
*/
public class TimeoutListenableFuture<V> extends ForwardingListenableFuture<V> {
private static final Logger logger = getLogger(TimeoutListenableFuture.class);
private final ListenableFuture<V> delegate;
private final List<ThrowableConsumer<TimeoutException, Exception>> timeoutListeners = new ArrayList<>();
/**
* better use {@link #timeoutListenableFuture(ListenableFuture)}
*/
public TimeoutListenableFuture(ListenableFuture<V> delegate) {
this.delegate = delegate;
}
public static <V> TimeoutListenableFuture<V>
timeoutListenableFuture(ListenableFuture<V> delegate) {
if (delegate instanceof TimeoutListenableFuture) {
return (TimeoutListenableFuture<V>) delegate;
} else {
return new TimeoutListenableFuture<>(delegate);
}
}
@Override
protected ListenableFuture<V> delegate() {
return delegate;
}
public TimeoutListenableFuture<V> | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableRunnable.java
// @FunctionalInterface
// public interface ThrowableRunnable<X extends Throwable> {
//
// void run() throws X;
// }
// Path: core/src/main/java/com/github/phantomthief/concurrent/TimeoutListenableFuture.java
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import com.github.phantomthief.util.ThrowableConsumer;
import com.github.phantomthief.util.ThrowableRunnable;
import com.google.common.util.concurrent.ForwardingListenableFuture;
import com.google.common.util.concurrent.ListenableFuture;
package com.github.phantomthief.concurrent;
/**
* @author w.vela
* Created on 16/5/31.
*/
public class TimeoutListenableFuture<V> extends ForwardingListenableFuture<V> {
private static final Logger logger = getLogger(TimeoutListenableFuture.class);
private final ListenableFuture<V> delegate;
private final List<ThrowableConsumer<TimeoutException, Exception>> timeoutListeners = new ArrayList<>();
/**
* better use {@link #timeoutListenableFuture(ListenableFuture)}
*/
public TimeoutListenableFuture(ListenableFuture<V> delegate) {
this.delegate = delegate;
}
public static <V> TimeoutListenableFuture<V>
timeoutListenableFuture(ListenableFuture<V> delegate) {
if (delegate instanceof TimeoutListenableFuture) {
return (TimeoutListenableFuture<V>) delegate;
} else {
return new TimeoutListenableFuture<>(delegate);
}
}
@Override
protected ListenableFuture<V> delegate() {
return delegate;
}
public TimeoutListenableFuture<V> | addTimeoutListener(@Nonnull ThrowableRunnable<Exception> listener) { |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/pool/impl/KeyAffinityTest.java | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableFunction.java
// @FunctionalInterface
// public interface ThrowableFunction<T, R, X extends Throwable> {
//
// static <T, X extends Throwable> ThrowableFunction<T, T, X> identity() {
// return t -> t;
// }
//
// R apply(T t) throws X;
//
// default <V> ThrowableFunction<V, R, X>
// compose(ThrowableFunction<? super V, ? extends T, X> before) {
// requireNonNull(before);
// return (V v) -> apply(before.apply(v));
// }
//
// default <V> ThrowableFunction<T, V, X>
// andThen(ThrowableFunction<? super R, ? extends V, X> after) {
// requireNonNull(after);
// return (T t) -> after.apply(apply(t));
// }
// }
| import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.MoreExecutors.shutdownAndAwaitTermination;
import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import javax.annotation.Nonnull;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.github.phantomthief.util.ThrowableConsumer;
import com.github.phantomthief.util.ThrowableFunction; | ExecutorService executorService = newFixedThreadPool(50);
Map<Integer, String> firstMapping = new ConcurrentHashMap<>();
for (int i = 0; i < 20; i++) {
int j = i;
executorService.execute(() -> {
run(keyAffinity, j, v -> {
firstMapping.put(j, v);
sleepUninterruptibly(10, SECONDS);
});
});
}
sleepUninterruptibly(1, SECONDS);
for (int i = 0; i < 1000; i++) {
executorService.execute(() -> {
int key = ThreadLocalRandom.current().nextInt(20);
run(keyAffinity, key, v -> {
String firstV = firstMapping.get(key);
assertEquals(firstV, v);
});
});
}
shutdownAndAwaitTermination(executorService, 1, DAYS);
}
@AfterEach
void tearDown() throws Exception {
keyAffinity.close();
}
private static <T, X extends Throwable, K, V> T supply(LazyKeyAffinity<K, V> keyAffinity, K key, | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableFunction.java
// @FunctionalInterface
// public interface ThrowableFunction<T, R, X extends Throwable> {
//
// static <T, X extends Throwable> ThrowableFunction<T, T, X> identity() {
// return t -> t;
// }
//
// R apply(T t) throws X;
//
// default <V> ThrowableFunction<V, R, X>
// compose(ThrowableFunction<? super V, ? extends T, X> before) {
// requireNonNull(before);
// return (V v) -> apply(before.apply(v));
// }
//
// default <V> ThrowableFunction<T, V, X>
// andThen(ThrowableFunction<? super R, ? extends V, X> after) {
// requireNonNull(after);
// return (T t) -> after.apply(apply(t));
// }
// }
// Path: core/src/test/java/com/github/phantomthief/pool/impl/KeyAffinityTest.java
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.MoreExecutors.shutdownAndAwaitTermination;
import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import javax.annotation.Nonnull;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.github.phantomthief.util.ThrowableConsumer;
import com.github.phantomthief.util.ThrowableFunction;
ExecutorService executorService = newFixedThreadPool(50);
Map<Integer, String> firstMapping = new ConcurrentHashMap<>();
for (int i = 0; i < 20; i++) {
int j = i;
executorService.execute(() -> {
run(keyAffinity, j, v -> {
firstMapping.put(j, v);
sleepUninterruptibly(10, SECONDS);
});
});
}
sleepUninterruptibly(1, SECONDS);
for (int i = 0; i < 1000; i++) {
executorService.execute(() -> {
int key = ThreadLocalRandom.current().nextInt(20);
run(keyAffinity, key, v -> {
String firstV = firstMapping.get(key);
assertEquals(firstV, v);
});
});
}
shutdownAndAwaitTermination(executorService, 1, DAYS);
}
@AfterEach
void tearDown() throws Exception {
keyAffinity.close();
}
private static <T, X extends Throwable, K, V> T supply(LazyKeyAffinity<K, V> keyAffinity, K key, | @Nonnull ThrowableFunction<V, T, X> func) throws X { |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/pool/impl/KeyAffinityTest.java | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableFunction.java
// @FunctionalInterface
// public interface ThrowableFunction<T, R, X extends Throwable> {
//
// static <T, X extends Throwable> ThrowableFunction<T, T, X> identity() {
// return t -> t;
// }
//
// R apply(T t) throws X;
//
// default <V> ThrowableFunction<V, R, X>
// compose(ThrowableFunction<? super V, ? extends T, X> before) {
// requireNonNull(before);
// return (V v) -> apply(before.apply(v));
// }
//
// default <V> ThrowableFunction<T, V, X>
// andThen(ThrowableFunction<? super R, ? extends V, X> after) {
// requireNonNull(after);
// return (T t) -> after.apply(apply(t));
// }
// }
| import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.MoreExecutors.shutdownAndAwaitTermination;
import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import javax.annotation.Nonnull;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.github.phantomthief.util.ThrowableConsumer;
import com.github.phantomthief.util.ThrowableFunction; | sleepUninterruptibly(1, SECONDS);
for (int i = 0; i < 1000; i++) {
executorService.execute(() -> {
int key = ThreadLocalRandom.current().nextInt(20);
run(keyAffinity, key, v -> {
String firstV = firstMapping.get(key);
assertEquals(firstV, v);
});
});
}
shutdownAndAwaitTermination(executorService, 1, DAYS);
}
@AfterEach
void tearDown() throws Exception {
keyAffinity.close();
}
private static <T, X extends Throwable, K, V> T supply(LazyKeyAffinity<K, V> keyAffinity, K key,
@Nonnull ThrowableFunction<V, T, X> func) throws X {
checkNotNull(func);
V one = keyAffinity.select(key);
try {
return func.apply(one);
} finally {
keyAffinity.finishCall(key);
}
}
private static <X extends Throwable, K, V> void run(LazyKeyAffinity<K, V> keyAffinity, K key, | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableFunction.java
// @FunctionalInterface
// public interface ThrowableFunction<T, R, X extends Throwable> {
//
// static <T, X extends Throwable> ThrowableFunction<T, T, X> identity() {
// return t -> t;
// }
//
// R apply(T t) throws X;
//
// default <V> ThrowableFunction<V, R, X>
// compose(ThrowableFunction<? super V, ? extends T, X> before) {
// requireNonNull(before);
// return (V v) -> apply(before.apply(v));
// }
//
// default <V> ThrowableFunction<T, V, X>
// andThen(ThrowableFunction<? super R, ? extends V, X> after) {
// requireNonNull(after);
// return (T t) -> after.apply(apply(t));
// }
// }
// Path: core/src/test/java/com/github/phantomthief/pool/impl/KeyAffinityTest.java
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.MoreExecutors.shutdownAndAwaitTermination;
import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import javax.annotation.Nonnull;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.github.phantomthief.util.ThrowableConsumer;
import com.github.phantomthief.util.ThrowableFunction;
sleepUninterruptibly(1, SECONDS);
for (int i = 0; i < 1000; i++) {
executorService.execute(() -> {
int key = ThreadLocalRandom.current().nextInt(20);
run(keyAffinity, key, v -> {
String firstV = firstMapping.get(key);
assertEquals(firstV, v);
});
});
}
shutdownAndAwaitTermination(executorService, 1, DAYS);
}
@AfterEach
void tearDown() throws Exception {
keyAffinity.close();
}
private static <T, X extends Throwable, K, V> T supply(LazyKeyAffinity<K, V> keyAffinity, K key,
@Nonnull ThrowableFunction<V, T, X> func) throws X {
checkNotNull(func);
V one = keyAffinity.select(key);
try {
return func.apply(one);
} finally {
keyAffinity.finishCall(key);
}
}
private static <X extends Throwable, K, V> void run(LazyKeyAffinity<K, V> keyAffinity, K key, | @Nonnull ThrowableConsumer<V, X> func) throws X { |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/util/ThrowableUtilsTest.java | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableUtils.java
// public static void changeThrowableMessage(Throwable throwable, Function<String, String> messageChangeFunc) {
// changeThrowableMessage(throwable, messageChangeFunc.apply(throwable.getMessage()));
// }
| import static com.github.phantomthief.util.ThrowableUtils.changeThrowableMessage;
import static com.google.common.base.Preconditions.checkArgument;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package com.github.phantomthief.util;
/**
* @author w.vela
* Created on 2019-06-18.
*/
class ThrowableUtilsTest {
private static final Logger logger = LoggerFactory.getLogger(ThrowableUtilsTest.class);
@Test
void test() {
try {
checkArgument(false, "myTest");
} catch (IllegalArgumentException e) { | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableUtils.java
// public static void changeThrowableMessage(Throwable throwable, Function<String, String> messageChangeFunc) {
// changeThrowableMessage(throwable, messageChangeFunc.apply(throwable.getMessage()));
// }
// Path: core/src/test/java/com/github/phantomthief/util/ThrowableUtilsTest.java
import static com.github.phantomthief.util.ThrowableUtils.changeThrowableMessage;
import static com.google.common.base.Preconditions.checkArgument;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package com.github.phantomthief.util;
/**
* @author w.vela
* Created on 2019-06-18.
*/
class ThrowableUtilsTest {
private static final Logger logger = LoggerFactory.getLogger(ThrowableUtilsTest.class);
@Test
void test() {
try {
checkArgument(false, "myTest");
} catch (IllegalArgumentException e) { | changeThrowableMessage(e, it -> it + "!!!"); |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/concurrent/MoreFuturesDynamicTest.java | // Path: core/src/main/java/com/github/phantomthief/concurrent/MoreFutures.java
// public static Future<?> scheduleWithDynamicDelay(@Nonnull ScheduledExecutorService executor,
// @Nullable Duration initDelay, @Nonnull Scheduled task) {
// checkNotNull(executor);
// checkNotNull(task);
// AtomicBoolean canceled = new AtomicBoolean(false);
// AbstractFuture<?> future = new AbstractFuture<Object>() {
//
// @Override
// public boolean cancel(boolean mayInterruptIfRunning) {
// canceled.set(true);
// return super.cancel(mayInterruptIfRunning);
// }
// };
// executor.schedule(new ScheduledTaskImpl(executor, task, canceled),
// initDelay == null ? 0 : initDelay.toMillis(), MILLISECONDS);
// return future;
// }
| import static com.github.phantomthief.concurrent.MoreFutures.scheduleWithDynamicDelay;
import static com.google.common.util.concurrent.MoreExecutors.shutdownAndAwaitTermination;
import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
import static java.time.Duration.ofSeconds;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package com.github.phantomthief.concurrent;
/**
* @author w.vela
* Created on 2019-11-26.
*/
class MoreFuturesDynamicTest {
private static final Logger logger = LoggerFactory.getLogger(MoreFuturesDynamicTest.class);
@Test
void test() {
ScheduledExecutorService scheduled = newSingleThreadScheduledExecutor();
int[] i = {1};
int[] run = {0}; | // Path: core/src/main/java/com/github/phantomthief/concurrent/MoreFutures.java
// public static Future<?> scheduleWithDynamicDelay(@Nonnull ScheduledExecutorService executor,
// @Nullable Duration initDelay, @Nonnull Scheduled task) {
// checkNotNull(executor);
// checkNotNull(task);
// AtomicBoolean canceled = new AtomicBoolean(false);
// AbstractFuture<?> future = new AbstractFuture<Object>() {
//
// @Override
// public boolean cancel(boolean mayInterruptIfRunning) {
// canceled.set(true);
// return super.cancel(mayInterruptIfRunning);
// }
// };
// executor.schedule(new ScheduledTaskImpl(executor, task, canceled),
// initDelay == null ? 0 : initDelay.toMillis(), MILLISECONDS);
// return future;
// }
// Path: core/src/test/java/com/github/phantomthief/concurrent/MoreFuturesDynamicTest.java
import static com.github.phantomthief.concurrent.MoreFutures.scheduleWithDynamicDelay;
import static com.google.common.util.concurrent.MoreExecutors.shutdownAndAwaitTermination;
import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
import static java.time.Duration.ofSeconds;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package com.github.phantomthief.concurrent;
/**
* @author w.vela
* Created on 2019-11-26.
*/
class MoreFuturesDynamicTest {
private static final Logger logger = LoggerFactory.getLogger(MoreFuturesDynamicTest.class);
@Test
void test() {
ScheduledExecutorService scheduled = newSingleThreadScheduledExecutor();
int[] i = {1};
int[] run = {0}; | Future<?> future = scheduleWithDynamicDelay(scheduled, () -> { |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/util/MorePreconditionsTest.java | // Path: core/src/main/java/com/github/phantomthief/util/MorePreconditions.java
// public static <X extends Throwable> void checkOrThrow(boolean expression, Supplier<X> exception) throws X {
// if (!expression) {
// throw exception.get();
// }
// }
| import static com.github.phantomthief.util.MorePreconditions.checkOrThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import org.junit.jupiter.api.Test; | package com.github.phantomthief.util;
/**
* @author w.vela
* Created on 2020-02-26.
*/
class MorePreconditionsTest {
@Test
void test() throws IOException { | // Path: core/src/main/java/com/github/phantomthief/util/MorePreconditions.java
// public static <X extends Throwable> void checkOrThrow(boolean expression, Supplier<X> exception) throws X {
// if (!expression) {
// throw exception.get();
// }
// }
// Path: core/src/test/java/com/github/phantomthief/util/MorePreconditionsTest.java
import static com.github.phantomthief.util.MorePreconditions.checkOrThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import org.junit.jupiter.api.Test;
package com.github.phantomthief.util;
/**
* @author w.vela
* Created on 2020-02-26.
*/
class MorePreconditionsTest {
@Test
void test() throws IOException { | checkOrThrow(true, IOException::new, "test"); |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/test/MoreStreamsTest.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreStreams.java
// public class MoreStreams {
//
// /**
// * 工具类,禁止实例化成对象
// */
// private MoreStreams() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * 创建一个类型为long的Stream,返回从开始到结束一个闭区间内的整数
// *
// * @param from 起始值(含)
// * @param to 终止值(含)
// * @return 生成的{@link LongStream}
// */
// public static LongStream longRangeClosed(long from, long to) {
// if (from <= to) {
// return LongStream.rangeClosed(from, to);
// } else {
// return LongStream.rangeClosed(to, from).map(i -> to - i + from);
// }
// }
//
// /**
// * 创建一个类型为int的Stream,返回从开始到结束一个闭区间内的整数
// *
// * @param from 起始值(含)
// * @param to 终止值(含)
// * @return 生成的{@link IntStream}
// */
// public static IntStream intRangeClosed(int from, int to) {
// if (from <= to) {
// return rangeClosed(from, to);
// } else {
// return rangeClosed(to, from).map(i -> to - i + from);
// }
// }
//
// /**
// * 将一个迭代器转换为一个Stream
// *
// * @param iterator 输入的迭代器对象,不能为空
// * @param <T> 输入值的类型泛型
// * @return 生成的{@link Stream}
// */
// public static <T> Stream<T> toStream(Iterator<T> iterator) {
// checkNotNull(iterator);
// return stream(spliteratorUnknownSize(iterator, (NONNULL | IMMUTABLE | ORDERED)), false);
// }
//
// /**
// * 将一个可迭代对象转换为一个Stream
// *
// * @param iterable 输入的可迭代对象,不能为空
// * @param <T> 输入值的类型泛型
// * @return 生成的{@link Stream}
// */
// public static <T> Stream<T> toStream(Iterable<T> iterable) {
// checkNotNull(iterable);
// if (iterable instanceof Collection) {
// // failfast
// try {
// Collection<T> collection = (Collection<T>) iterable;
// return stream(spliterator(collection, 0), false);
// } catch (Throwable e) {
// // do nothing
// }
// }
// return stream(spliteratorUnknownSize(iterable.iterator(), (NONNULL | IMMUTABLE | ORDERED)),
// false);
// }
//
// /**
// * 将一个Stream按一定的大小进行批次分组,返回一个按组的新的Stream
// *
// * @param stream 输入值的Stream
// * @param size 分组的大小
// * @param <T> 输入值的类型泛型
// * @return 生成的{@link Stream}
// */
// public static <T> Stream<List<T>> partition(Stream<T> stream, int size) {
// Iterable<List<T>> iterable = () -> Iterators.partition(stream.iterator(), size);
// return StreamSupport.stream(iterable.spliterator(), false);
// }
// }
| import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.github.phantomthief.util.MoreStreams; | package com.github.phantomthief.test;
/**
* @author w.vela
*/
class MoreStreamsTest {
@Test
void testRange() { | // Path: core/src/main/java/com/github/phantomthief/util/MoreStreams.java
// public class MoreStreams {
//
// /**
// * 工具类,禁止实例化成对象
// */
// private MoreStreams() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * 创建一个类型为long的Stream,返回从开始到结束一个闭区间内的整数
// *
// * @param from 起始值(含)
// * @param to 终止值(含)
// * @return 生成的{@link LongStream}
// */
// public static LongStream longRangeClosed(long from, long to) {
// if (from <= to) {
// return LongStream.rangeClosed(from, to);
// } else {
// return LongStream.rangeClosed(to, from).map(i -> to - i + from);
// }
// }
//
// /**
// * 创建一个类型为int的Stream,返回从开始到结束一个闭区间内的整数
// *
// * @param from 起始值(含)
// * @param to 终止值(含)
// * @return 生成的{@link IntStream}
// */
// public static IntStream intRangeClosed(int from, int to) {
// if (from <= to) {
// return rangeClosed(from, to);
// } else {
// return rangeClosed(to, from).map(i -> to - i + from);
// }
// }
//
// /**
// * 将一个迭代器转换为一个Stream
// *
// * @param iterator 输入的迭代器对象,不能为空
// * @param <T> 输入值的类型泛型
// * @return 生成的{@link Stream}
// */
// public static <T> Stream<T> toStream(Iterator<T> iterator) {
// checkNotNull(iterator);
// return stream(spliteratorUnknownSize(iterator, (NONNULL | IMMUTABLE | ORDERED)), false);
// }
//
// /**
// * 将一个可迭代对象转换为一个Stream
// *
// * @param iterable 输入的可迭代对象,不能为空
// * @param <T> 输入值的类型泛型
// * @return 生成的{@link Stream}
// */
// public static <T> Stream<T> toStream(Iterable<T> iterable) {
// checkNotNull(iterable);
// if (iterable instanceof Collection) {
// // failfast
// try {
// Collection<T> collection = (Collection<T>) iterable;
// return stream(spliterator(collection, 0), false);
// } catch (Throwable e) {
// // do nothing
// }
// }
// return stream(spliteratorUnknownSize(iterable.iterator(), (NONNULL | IMMUTABLE | ORDERED)),
// false);
// }
//
// /**
// * 将一个Stream按一定的大小进行批次分组,返回一个按组的新的Stream
// *
// * @param stream 输入值的Stream
// * @param size 分组的大小
// * @param <T> 输入值的类型泛型
// * @return 生成的{@link Stream}
// */
// public static <T> Stream<List<T>> partition(Stream<T> stream, int size) {
// Iterable<List<T>> iterable = () -> Iterators.partition(stream.iterator(), size);
// return StreamSupport.stream(iterable.spliterator(), false);
// }
// }
// Path: core/src/test/java/com/github/phantomthief/test/MoreStreamsTest.java
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.github.phantomthief.util.MoreStreams;
package com.github.phantomthief.test;
/**
* @author w.vela
*/
class MoreStreamsTest {
@Test
void testRange() { | MoreStreams.longRangeClosed(10, 15).forEach(System.out::println); |
PhantomThief/more-lambdas-java | core/src/main/java/com/github/phantomthief/concurrent/MoreFutures.java | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableFunction.java
// @FunctionalInterface
// public interface ThrowableFunction<T, R, X extends Throwable> {
//
// static <T, X extends Throwable> ThrowableFunction<T, T, X> identity() {
// return t -> t;
// }
//
// R apply(T t) throws X;
//
// default <V> ThrowableFunction<V, R, X>
// compose(ThrowableFunction<? super V, ? extends T, X> before) {
// requireNonNull(before);
// return (V v) -> apply(before.apply(v));
// }
//
// default <V> ThrowableFunction<T, V, X>
// andThen(ThrowableFunction<? super R, ? extends V, X> after) {
// requireNonNull(after);
// return (T t) -> after.apply(apply(t));
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableRunnable.java
// @FunctionalInterface
// public interface ThrowableRunnable<X extends Throwable> {
//
// void run() throws X;
// }
| import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import static java.lang.System.nanoTime;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import java.time.Duration;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.phantomthief.util.ThrowableConsumer;
import com.github.phantomthief.util.ThrowableFunction;
import com.github.phantomthief.util.ThrowableRunnable;
import com.google.common.util.concurrent.AbstractFuture;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.common.util.concurrent.UncheckedTimeoutException; | * // don't try/catch the exception it throws.
* Map<Future<User>, User> success = tryWait(list, 1, SECONDS);
* }</pre>
*
* @param futures 要获取值的多个{@link Future}
* @param timeout 超时时间
* @param unit 超时时间单位
* @throws TryWaitFutureUncheckedException 当并非所有的{@link Future}都成功返回时,将会抛出此异常,
* 可以通过此异常获取成功、异常、超时、取消的各个{@link Future}
*/
@Nonnull
public static <F extends Future<V>, V> Map<F, V> tryWait(@Nonnull Iterable<F> futures, @Nonnegative long timeout,
@Nonnull TimeUnit unit) throws TryWaitFutureUncheckedException {
checkNotNull(futures);
checkArgument(timeout > 0);
checkNotNull(unit);
return tryWait(futures, timeout, unit, it -> it, TryWaitFutureUncheckedException::new);
}
/**
* 同时获取并返回一批{@link Future}的操作结果值
*
* @param keys 要获取值的Key,作为输入值,通过asyncFunc参数传入的函数转换为Future对象
* @param duration 获取值的超时时间
* @param asyncFunc 异步转换函数,将输入的每一个Key值转换为{@link Future}
* @throws TryWaitUncheckedException if not all calls are successful.
* @see #tryWait(Iterable, long, TimeUnit, ThrowableFunction)
*/
@Nonnull
public static <K, V, X extends Throwable> Map<K, V> tryWait(@Nonnull Iterable<K> keys, | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableFunction.java
// @FunctionalInterface
// public interface ThrowableFunction<T, R, X extends Throwable> {
//
// static <T, X extends Throwable> ThrowableFunction<T, T, X> identity() {
// return t -> t;
// }
//
// R apply(T t) throws X;
//
// default <V> ThrowableFunction<V, R, X>
// compose(ThrowableFunction<? super V, ? extends T, X> before) {
// requireNonNull(before);
// return (V v) -> apply(before.apply(v));
// }
//
// default <V> ThrowableFunction<T, V, X>
// andThen(ThrowableFunction<? super R, ? extends V, X> after) {
// requireNonNull(after);
// return (T t) -> after.apply(apply(t));
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableRunnable.java
// @FunctionalInterface
// public interface ThrowableRunnable<X extends Throwable> {
//
// void run() throws X;
// }
// Path: core/src/main/java/com/github/phantomthief/concurrent/MoreFutures.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import static java.lang.System.nanoTime;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import java.time.Duration;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.phantomthief.util.ThrowableConsumer;
import com.github.phantomthief.util.ThrowableFunction;
import com.github.phantomthief.util.ThrowableRunnable;
import com.google.common.util.concurrent.AbstractFuture;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.common.util.concurrent.UncheckedTimeoutException;
* // don't try/catch the exception it throws.
* Map<Future<User>, User> success = tryWait(list, 1, SECONDS);
* }</pre>
*
* @param futures 要获取值的多个{@link Future}
* @param timeout 超时时间
* @param unit 超时时间单位
* @throws TryWaitFutureUncheckedException 当并非所有的{@link Future}都成功返回时,将会抛出此异常,
* 可以通过此异常获取成功、异常、超时、取消的各个{@link Future}
*/
@Nonnull
public static <F extends Future<V>, V> Map<F, V> tryWait(@Nonnull Iterable<F> futures, @Nonnegative long timeout,
@Nonnull TimeUnit unit) throws TryWaitFutureUncheckedException {
checkNotNull(futures);
checkArgument(timeout > 0);
checkNotNull(unit);
return tryWait(futures, timeout, unit, it -> it, TryWaitFutureUncheckedException::new);
}
/**
* 同时获取并返回一批{@link Future}的操作结果值
*
* @param keys 要获取值的Key,作为输入值,通过asyncFunc参数传入的函数转换为Future对象
* @param duration 获取值的超时时间
* @param asyncFunc 异步转换函数,将输入的每一个Key值转换为{@link Future}
* @throws TryWaitUncheckedException if not all calls are successful.
* @see #tryWait(Iterable, long, TimeUnit, ThrowableFunction)
*/
@Nonnull
public static <K, V, X extends Throwable> Map<K, V> tryWait(@Nonnull Iterable<K> keys, | @Nonnull Duration duration, @Nonnull ThrowableFunction<K, Future<V>, X> asyncFunc) |
PhantomThief/more-lambdas-java | core/src/main/java/com/github/phantomthief/concurrent/MoreFutures.java | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableFunction.java
// @FunctionalInterface
// public interface ThrowableFunction<T, R, X extends Throwable> {
//
// static <T, X extends Throwable> ThrowableFunction<T, T, X> identity() {
// return t -> t;
// }
//
// R apply(T t) throws X;
//
// default <V> ThrowableFunction<V, R, X>
// compose(ThrowableFunction<? super V, ? extends T, X> before) {
// requireNonNull(before);
// return (V v) -> apply(before.apply(v));
// }
//
// default <V> ThrowableFunction<T, V, X>
// andThen(ThrowableFunction<? super R, ? extends V, X> after) {
// requireNonNull(after);
// return (T t) -> after.apply(apply(t));
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableRunnable.java
// @FunctionalInterface
// public interface ThrowableRunnable<X extends Throwable> {
//
// void run() throws X;
// }
| import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import static java.lang.System.nanoTime;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import java.time.Duration;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.phantomthief.util.ThrowableConsumer;
import com.github.phantomthief.util.ThrowableFunction;
import com.github.phantomthief.util.ThrowableRunnable;
import com.google.common.util.concurrent.AbstractFuture;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.common.util.concurrent.UncheckedTimeoutException; | */
public static Future<?> scheduleWithDynamicDelay(@Nonnull ScheduledExecutorService executor,
@Nullable Duration initDelay, @Nonnull Scheduled task) {
checkNotNull(executor);
checkNotNull(task);
AtomicBoolean canceled = new AtomicBoolean(false);
AbstractFuture<?> future = new AbstractFuture<Object>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
canceled.set(true);
return super.cancel(mayInterruptIfRunning);
}
};
executor.schedule(new ScheduledTaskImpl(executor, task, canceled),
initDelay == null ? 0 : initDelay.toMillis(), MILLISECONDS);
return future;
}
/**
* 执行一个计划任务,按照上一次计划任务返回的等待时间,来运行下一次任务
*
* @param executor 任务执行器,当任务执行器停止时,所有任务将停止运行
* @param initialDelay 首次执行的延迟时间
* @param delay 任务延迟提供器,用来设置任务执行之后下一次的执行间隔时间
* @param task 执行的任务,在任务中抛出的异常会终止任务的运行,需谨慎处理
* @return 执行任务的Future,可以用来取消任务
*/
public static Future<?> scheduleWithDynamicDelay(@Nonnull ScheduledExecutorService executor,
@Nonnull Duration initialDelay, @Nonnull Supplier<Duration> delay, | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableFunction.java
// @FunctionalInterface
// public interface ThrowableFunction<T, R, X extends Throwable> {
//
// static <T, X extends Throwable> ThrowableFunction<T, T, X> identity() {
// return t -> t;
// }
//
// R apply(T t) throws X;
//
// default <V> ThrowableFunction<V, R, X>
// compose(ThrowableFunction<? super V, ? extends T, X> before) {
// requireNonNull(before);
// return (V v) -> apply(before.apply(v));
// }
//
// default <V> ThrowableFunction<T, V, X>
// andThen(ThrowableFunction<? super R, ? extends V, X> after) {
// requireNonNull(after);
// return (T t) -> after.apply(apply(t));
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableRunnable.java
// @FunctionalInterface
// public interface ThrowableRunnable<X extends Throwable> {
//
// void run() throws X;
// }
// Path: core/src/main/java/com/github/phantomthief/concurrent/MoreFutures.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import static java.lang.System.nanoTime;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import java.time.Duration;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.phantomthief.util.ThrowableConsumer;
import com.github.phantomthief.util.ThrowableFunction;
import com.github.phantomthief.util.ThrowableRunnable;
import com.google.common.util.concurrent.AbstractFuture;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.common.util.concurrent.UncheckedTimeoutException;
*/
public static Future<?> scheduleWithDynamicDelay(@Nonnull ScheduledExecutorService executor,
@Nullable Duration initDelay, @Nonnull Scheduled task) {
checkNotNull(executor);
checkNotNull(task);
AtomicBoolean canceled = new AtomicBoolean(false);
AbstractFuture<?> future = new AbstractFuture<Object>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
canceled.set(true);
return super.cancel(mayInterruptIfRunning);
}
};
executor.schedule(new ScheduledTaskImpl(executor, task, canceled),
initDelay == null ? 0 : initDelay.toMillis(), MILLISECONDS);
return future;
}
/**
* 执行一个计划任务,按照上一次计划任务返回的等待时间,来运行下一次任务
*
* @param executor 任务执行器,当任务执行器停止时,所有任务将停止运行
* @param initialDelay 首次执行的延迟时间
* @param delay 任务延迟提供器,用来设置任务执行之后下一次的执行间隔时间
* @param task 执行的任务,在任务中抛出的异常会终止任务的运行,需谨慎处理
* @return 执行任务的Future,可以用来取消任务
*/
public static Future<?> scheduleWithDynamicDelay(@Nonnull ScheduledExecutorService executor,
@Nonnull Duration initialDelay, @Nonnull Supplier<Duration> delay, | @Nonnull ThrowableRunnable<Throwable> task) { |
PhantomThief/more-lambdas-java | core/src/main/java/com/github/phantomthief/concurrent/MoreFutures.java | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableFunction.java
// @FunctionalInterface
// public interface ThrowableFunction<T, R, X extends Throwable> {
//
// static <T, X extends Throwable> ThrowableFunction<T, T, X> identity() {
// return t -> t;
// }
//
// R apply(T t) throws X;
//
// default <V> ThrowableFunction<V, R, X>
// compose(ThrowableFunction<? super V, ? extends T, X> before) {
// requireNonNull(before);
// return (V v) -> apply(before.apply(v));
// }
//
// default <V> ThrowableFunction<T, V, X>
// andThen(ThrowableFunction<? super R, ? extends V, X> after) {
// requireNonNull(after);
// return (T t) -> after.apply(apply(t));
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableRunnable.java
// @FunctionalInterface
// public interface ThrowableRunnable<X extends Throwable> {
//
// void run() throws X;
// }
| import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import static java.lang.System.nanoTime;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import java.time.Duration;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.phantomthief.util.ThrowableConsumer;
import com.github.phantomthief.util.ThrowableFunction;
import com.github.phantomthief.util.ThrowableRunnable;
import com.google.common.util.concurrent.AbstractFuture;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.common.util.concurrent.UncheckedTimeoutException; | }
return delay.get();
});
}
/**
* 用于替换 {@link Futures#transform(ListenableFuture, com.google.common.base.Function, Executor)}
* <p>
* 主要提供两个额外的功能:
* 1. API使用jdk8
* 2. 提供了 {@link TimeoutListenableFuture} 的支持(保持Listener不会丢)
*
* @param input 输入的Future
* @param function 用于从输入的Future转换为输出Future结果类型的转换函数
* @param executor 转换函数执行的Executor
* @return 返回转换后的Future对象
*/
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
Function<? super I, ? extends O> function, Executor executor) {
@SuppressWarnings("Guava")
com.google.common.base.Function<? super I, ? extends O> realFunc;
if (function instanceof com.google.common.base.Function) {
//noinspection unchecked
realFunc = (com.google.common.base.Function) function;
} else {
realFunc = function::apply;
}
ListenableFuture<O> result = Futures.transform(input, realFunc, executor);
if (input instanceof TimeoutListenableFuture) {
TimeoutListenableFuture<O> newResult = new TimeoutListenableFuture<>(result); | // Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableFunction.java
// @FunctionalInterface
// public interface ThrowableFunction<T, R, X extends Throwable> {
//
// static <T, X extends Throwable> ThrowableFunction<T, T, X> identity() {
// return t -> t;
// }
//
// R apply(T t) throws X;
//
// default <V> ThrowableFunction<V, R, X>
// compose(ThrowableFunction<? super V, ? extends T, X> before) {
// requireNonNull(before);
// return (V v) -> apply(before.apply(v));
// }
//
// default <V> ThrowableFunction<T, V, X>
// andThen(ThrowableFunction<? super R, ? extends V, X> after) {
// requireNonNull(after);
// return (T t) -> after.apply(apply(t));
// }
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableRunnable.java
// @FunctionalInterface
// public interface ThrowableRunnable<X extends Throwable> {
//
// void run() throws X;
// }
// Path: core/src/main/java/com/github/phantomthief/concurrent/MoreFutures.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import static java.lang.System.nanoTime;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import java.time.Duration;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.phantomthief.util.ThrowableConsumer;
import com.github.phantomthief.util.ThrowableFunction;
import com.github.phantomthief.util.ThrowableRunnable;
import com.google.common.util.concurrent.AbstractFuture;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.common.util.concurrent.UncheckedTimeoutException;
}
return delay.get();
});
}
/**
* 用于替换 {@link Futures#transform(ListenableFuture, com.google.common.base.Function, Executor)}
* <p>
* 主要提供两个额外的功能:
* 1. API使用jdk8
* 2. 提供了 {@link TimeoutListenableFuture} 的支持(保持Listener不会丢)
*
* @param input 输入的Future
* @param function 用于从输入的Future转换为输出Future结果类型的转换函数
* @param executor 转换函数执行的Executor
* @return 返回转换后的Future对象
*/
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
Function<? super I, ? extends O> function, Executor executor) {
@SuppressWarnings("Guava")
com.google.common.base.Function<? super I, ? extends O> realFunc;
if (function instanceof com.google.common.base.Function) {
//noinspection unchecked
realFunc = (com.google.common.base.Function) function;
} else {
realFunc = function::apply;
}
ListenableFuture<O> result = Futures.transform(input, realFunc, executor);
if (input instanceof TimeoutListenableFuture) {
TimeoutListenableFuture<O> newResult = new TimeoutListenableFuture<>(result); | for (ThrowableConsumer<TimeoutException, Exception> timeoutListener : ((TimeoutListenableFuture<I>) input) |
PhantomThief/more-lambdas-java | core/src/main/java/com/github/phantomthief/pool/impl/DynamicCapacityLinkedBlockingQueue.java | // Path: core/src/main/java/com/github/phantomthief/util/SimpleRateLimiter.java
// @ThreadSafe
// public class SimpleRateLimiter {
//
// private final LongAdder skip = new LongAdder();
//
// /**
// * 多少ns允许一次请求
// */
// private long allowTimesPerNanos;
// private volatile long lastAcquiredNanos;
//
// private SimpleRateLimiter(long allowTimesPerNanos) {
// checkState(allowTimesPerNanos > 0);
// this.allowTimesPerNanos = allowTimesPerNanos;
// }
//
// /**
// * 创建一个{@link SimpleRateLimiter}对象,限制每次的时间间隔
// *
// * @param periodPerTimes 时间间隔
// * @return {@link SimpleRateLimiter}对象
// */
// public static SimpleRateLimiter createByPeriod(Duration periodPerTimes) {
// return new SimpleRateLimiter(checkNotNull(periodPerTimes).toNanos());
// }
//
// /**
// * 创建一个{@link SimpleRateLimiter}对象,限制每秒允许的请求次数
// *
// * @param permitsPerSecond 请求次数
// * @return {@link SimpleRateLimiter}对象
// */
// public static SimpleRateLimiter create(double permitsPerSecond) {
// checkState(permitsPerSecond > 0);
// long allowTimesPerNanos = (long) (SECONDS.toNanos(1) / permitsPerSecond);
// return new SimpleRateLimiter(allowTimesPerNanos);
// }
//
// /**
// * 设置当前{@link SimpleRateLimiter}对象每秒允许的请求次数
// *
// * @param permitsPerSecond 每秒请求次数
// */
// public void setRate(double permitsPerSecond) {
// checkState(permitsPerSecond > 0);
// long thisPeriod = (long) (SECONDS.toNanos(1) / permitsPerSecond);
// checkState(thisPeriod > 0);
// this.allowTimesPerNanos = thisPeriod;
// }
//
// /**
// * 设置当前{@link SimpleRateLimiter}对象每次请求的间隔时间
// *
// * @param periodPerTimes 间隔时间
// */
// public void setPeriod(Duration periodPerTimes) {
// long thisPeriod = checkNotNull(periodPerTimes).toNanos();
// checkState(thisPeriod > 0);
// this.allowTimesPerNanos = thisPeriod;
// }
//
// long getAllowTimesPerNanos() {
// return allowTimesPerNanos;
// }
//
// /**
// * 判断本次请求是否获得准许处理请求
// *
// * @return 是否获得准许
// */
// public boolean tryAcquire() {
// long nanoTime = System.nanoTime();
// if (nanoTime >= lastAcquiredNanos + allowTimesPerNanos || lastAcquiredNanos == 0) {
// synchronized (this) {
// if (nanoTime >= lastAcquiredNanos + allowTimesPerNanos || lastAcquiredNanos == 0) {
// lastAcquiredNanos = nanoTime;
// return true;
// }
// }
// }
// skip.increment();
// return false;
// }
//
// /**
// * 计算到上次执行本操作前,共计多少个没有获取到准许,计算完成后重新计数
// *
// * @return 累计跳过的请求数
// */
// public long getSkipCountAndClear() {
// return skip.sumThenReset();
// }
// }
| import java.util.Collection;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.IntSupplier;
import java.util.function.Predicate;
import com.github.phantomthief.util.SimpleRateLimiter; | package com.github.phantomthief.pool.impl;
/**
* 备注,本类主要是用于给
* {@link com.github.phantomthief.pool.KeyAffinityExecutor#newSerializingExecutor(IntSupplier, IntSupplier, String)}
* 提供支持的,并不推荐大家直接使用,未来也可能会随时调整实现和行为
*
* @author w.vela
* Created on 2020-08-19.
*/
public class DynamicCapacityLinkedBlockingQueue<E> implements BlockingQueue<E> {
private final CapacitySettableLinkedBlockingQueue<E> queue;
private final IntSupplier capacity; | // Path: core/src/main/java/com/github/phantomthief/util/SimpleRateLimiter.java
// @ThreadSafe
// public class SimpleRateLimiter {
//
// private final LongAdder skip = new LongAdder();
//
// /**
// * 多少ns允许一次请求
// */
// private long allowTimesPerNanos;
// private volatile long lastAcquiredNanos;
//
// private SimpleRateLimiter(long allowTimesPerNanos) {
// checkState(allowTimesPerNanos > 0);
// this.allowTimesPerNanos = allowTimesPerNanos;
// }
//
// /**
// * 创建一个{@link SimpleRateLimiter}对象,限制每次的时间间隔
// *
// * @param periodPerTimes 时间间隔
// * @return {@link SimpleRateLimiter}对象
// */
// public static SimpleRateLimiter createByPeriod(Duration periodPerTimes) {
// return new SimpleRateLimiter(checkNotNull(periodPerTimes).toNanos());
// }
//
// /**
// * 创建一个{@link SimpleRateLimiter}对象,限制每秒允许的请求次数
// *
// * @param permitsPerSecond 请求次数
// * @return {@link SimpleRateLimiter}对象
// */
// public static SimpleRateLimiter create(double permitsPerSecond) {
// checkState(permitsPerSecond > 0);
// long allowTimesPerNanos = (long) (SECONDS.toNanos(1) / permitsPerSecond);
// return new SimpleRateLimiter(allowTimesPerNanos);
// }
//
// /**
// * 设置当前{@link SimpleRateLimiter}对象每秒允许的请求次数
// *
// * @param permitsPerSecond 每秒请求次数
// */
// public void setRate(double permitsPerSecond) {
// checkState(permitsPerSecond > 0);
// long thisPeriod = (long) (SECONDS.toNanos(1) / permitsPerSecond);
// checkState(thisPeriod > 0);
// this.allowTimesPerNanos = thisPeriod;
// }
//
// /**
// * 设置当前{@link SimpleRateLimiter}对象每次请求的间隔时间
// *
// * @param periodPerTimes 间隔时间
// */
// public void setPeriod(Duration periodPerTimes) {
// long thisPeriod = checkNotNull(periodPerTimes).toNanos();
// checkState(thisPeriod > 0);
// this.allowTimesPerNanos = thisPeriod;
// }
//
// long getAllowTimesPerNanos() {
// return allowTimesPerNanos;
// }
//
// /**
// * 判断本次请求是否获得准许处理请求
// *
// * @return 是否获得准许
// */
// public boolean tryAcquire() {
// long nanoTime = System.nanoTime();
// if (nanoTime >= lastAcquiredNanos + allowTimesPerNanos || lastAcquiredNanos == 0) {
// synchronized (this) {
// if (nanoTime >= lastAcquiredNanos + allowTimesPerNanos || lastAcquiredNanos == 0) {
// lastAcquiredNanos = nanoTime;
// return true;
// }
// }
// }
// skip.increment();
// return false;
// }
//
// /**
// * 计算到上次执行本操作前,共计多少个没有获取到准许,计算完成后重新计数
// *
// * @return 累计跳过的请求数
// */
// public long getSkipCountAndClear() {
// return skip.sumThenReset();
// }
// }
// Path: core/src/main/java/com/github/phantomthief/pool/impl/DynamicCapacityLinkedBlockingQueue.java
import java.util.Collection;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.IntSupplier;
import java.util.function.Predicate;
import com.github.phantomthief.util.SimpleRateLimiter;
package com.github.phantomthief.pool.impl;
/**
* 备注,本类主要是用于给
* {@link com.github.phantomthief.pool.KeyAffinityExecutor#newSerializingExecutor(IntSupplier, IntSupplier, String)}
* 提供支持的,并不推荐大家直接使用,未来也可能会随时调整实现和行为
*
* @author w.vela
* Created on 2020-08-19.
*/
public class DynamicCapacityLinkedBlockingQueue<E> implements BlockingQueue<E> {
private final CapacitySettableLinkedBlockingQueue<E> queue;
private final IntSupplier capacity; | private final SimpleRateLimiter rateLimiter; |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/test/MoreRunnablesTest.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreRunnables.java
// public final class MoreRunnables {
//
// /**
// * 将给定的{@link Runnable}包装为只执行一次的对象,通常可以用来做首次运行时初始化的工作
// *
// * @param runnable 传入的{@link Runnable}
// * @return 经过包装,只运行一次的{@link Runnable}
// */
// public static Runnable runOnce(Runnable runnable) {
// return new Runnable() {
//
// private final Supplier<Void> supplier = MoreSuppliers.lazy(() -> {
// runnable.run();
// return null;
// });
//
// @Override
// public void run() {
// supplier.get();
// }
// };
// }
// }
| import com.github.phantomthief.util.MoreRunnables;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Test; | package com.github.phantomthief.test;
/**
* @author w.vela
* Created on 16/3/14.
*/
class MoreRunnablesTest {
@Test
void test() {
AtomicBoolean runned = new AtomicBoolean(false); | // Path: core/src/main/java/com/github/phantomthief/util/MoreRunnables.java
// public final class MoreRunnables {
//
// /**
// * 将给定的{@link Runnable}包装为只执行一次的对象,通常可以用来做首次运行时初始化的工作
// *
// * @param runnable 传入的{@link Runnable}
// * @return 经过包装,只运行一次的{@link Runnable}
// */
// public static Runnable runOnce(Runnable runnable) {
// return new Runnable() {
//
// private final Supplier<Void> supplier = MoreSuppliers.lazy(() -> {
// runnable.run();
// return null;
// });
//
// @Override
// public void run() {
// supplier.get();
// }
// };
// }
// }
// Path: core/src/test/java/com/github/phantomthief/test/MoreRunnablesTest.java
import com.github.phantomthief.util.MoreRunnables;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Test;
package com.github.phantomthief.test;
/**
* @author w.vela
* Created on 16/3/14.
*/
class MoreRunnablesTest {
@Test
void test() {
AtomicBoolean runned = new AtomicBoolean(false); | Runnable runOnce = MoreRunnables.runOnce(() -> { |
PhantomThief/more-lambdas-java | core-jdk9/src/test/java/com/github/phantomthief/util/JdkProviderTest.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreReflection.java
// @Nullable
// public static StackTraceElement getCallerPlace() {
// return getCallerPlace(MoreReflection.class);
// }
| import static com.github.phantomthief.util.MoreReflection.getCallerPlace;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Test; | callerPlace = MyTest2.test911();
assertNotNull(callerPlace);
assertEquals("JdkProviderTest.java", callerPlace.getFileName());
}
@Test
void testReflection8() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method test41 = MyTest2.class.getDeclaredMethod("test811");
test41.setAccessible(true);
StackTraceElement callerPlace = (StackTraceElement) test41.invoke(null);
assertNotNull(callerPlace);
assertEquals("JdkProviderTest.java", callerPlace.getFileName());
}
@Test
void testReflection9() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method test41 = MyTest2.class.getDeclaredMethod("test911");
test41.setAccessible(true);
StackTraceElement callerPlace = (StackTraceElement) test41.invoke(null);
assertNotNull(callerPlace);
assertEquals("JdkProviderTest.java", callerPlace.getFileName());
}
static class MyTest {
private static StackTraceProviderJdk9 jdk9 = new StackTraceProviderJdk9();
private static StackTraceProviderJdk8 jdk8 = new StackTraceProviderJdk8();
@Deprecated
static void test() { | // Path: core/src/main/java/com/github/phantomthief/util/MoreReflection.java
// @Nullable
// public static StackTraceElement getCallerPlace() {
// return getCallerPlace(MoreReflection.class);
// }
// Path: core-jdk9/src/test/java/com/github/phantomthief/util/JdkProviderTest.java
import static com.github.phantomthief.util.MoreReflection.getCallerPlace;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Test;
callerPlace = MyTest2.test911();
assertNotNull(callerPlace);
assertEquals("JdkProviderTest.java", callerPlace.getFileName());
}
@Test
void testReflection8() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method test41 = MyTest2.class.getDeclaredMethod("test811");
test41.setAccessible(true);
StackTraceElement callerPlace = (StackTraceElement) test41.invoke(null);
assertNotNull(callerPlace);
assertEquals("JdkProviderTest.java", callerPlace.getFileName());
}
@Test
void testReflection9() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method test41 = MyTest2.class.getDeclaredMethod("test911");
test41.setAccessible(true);
StackTraceElement callerPlace = (StackTraceElement) test41.invoke(null);
assertNotNull(callerPlace);
assertEquals("JdkProviderTest.java", callerPlace.getFileName());
}
static class MyTest {
private static StackTraceProviderJdk9 jdk9 = new StackTraceProviderJdk9();
private static StackTraceProviderJdk8 jdk8 = new StackTraceProviderJdk8();
@Deprecated
static void test() { | System.err.println(getCallerPlace()); |
PhantomThief/more-lambdas-java | core/src/main/java/com/github/phantomthief/util/RateLogger.java | // Path: core/src/main/java/com/github/phantomthief/tuple/Tuple.java
// public static <A, B> TwoTuple<A, B> tuple(final A a, final B b) {
// return new TwoTuple<>(a, b);
// }
//
// Path: core/src/main/java/com/github/phantomthief/tuple/ThreeTuple.java
// public class ThreeTuple<A, B, C> extends TwoTuple<A, B> {
//
// public final C third;
//
// /**
// * use {@link Tuple#tuple(Object, Object, Object)} instead
// */
// @Deprecated
// public ThreeTuple(final A a, final B b, final C c) {
// super(a, b);
// third = c;
// }
//
// public C getThird() {
// return third;
// }
//
// @Override
// public String toString() {
// return "(" + first + ", " + second + ", " + third + ")";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = super.hashCode();
// result = prime * result + (third == null ? 0 : third.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (!super.equals(obj)) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final ThreeTuple<?, ?, ?> other = (ThreeTuple<?, ?, ?>) obj;
// if (third == null) {
// if (other.third != null) {
// return false;
// }
// } else if (!third.equals(other.third)) {
// return false;
// }
// return true;
// }
//
// }
| import static com.github.phantomthief.tuple.Tuple.tuple;
import static org.slf4j.spi.LocationAwareLogger.DEBUG_INT;
import static org.slf4j.spi.LocationAwareLogger.ERROR_INT;
import static org.slf4j.spi.LocationAwareLogger.INFO_INT;
import static org.slf4j.spi.LocationAwareLogger.TRACE_INT;
import static org.slf4j.spi.LocationAwareLogger.WARN_INT;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.Nullable;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.spi.LocationAwareLogger;
import com.github.phantomthief.tuple.ThreeTuple;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache; | package com.github.phantomthief.util;
/**
* 使用 {@link SimpleRateLimiter} 来控制打 log 输出的频率,避免出现 log flood 占用过高的 CPU <p>
* 对于需要用一个 logger 打不同类型的日志,又不希望不同日志输出频率互相干扰(比如高频日志把低频日志淹没)<p>
* 可以使用 {@link #perMessageRateLogger(Logger)} 方式构建 logger,这时候,不同日志的区分方式是以 log.info(msg, args...);<p>
* 中第一个参数 msg 来区分,相同的 msg 会被认为是相同类型的日志,从而共享相同的频次限制;<p>
*
* 使用方法:
* <pre>
* {@code
*
* class MyObject {
* private static final Logger logger = LoggerFactory.getLogger(MyObject.class); // normal one
* private static final Logger rateLogger = RateLogger.rateLogger(logger); // wrap as a rate one
*
* void foo() {
* rateLogger.info("my message"); // use as normal logger.
* }
* }
* }
* </pre>
*
* @author w.vela
* Created on 2017-02-24.
*/
public class RateLogger implements Logger {
/**
* fully qualified class name, for short
*/
private static final String FQCN = RateLogger.class.getName();
private static final double DEFAULT_PERMITS_PER_SECOND = 1;
private static final int MAX_PER_FORMAT_CACHE_SIZE = 100;
// 直接使用Map来cache RateLogger。Logger的数量是有限的,LogBack也是使用了Map来Cache,所以没必要用一个支持evict的Cache。 | // Path: core/src/main/java/com/github/phantomthief/tuple/Tuple.java
// public static <A, B> TwoTuple<A, B> tuple(final A a, final B b) {
// return new TwoTuple<>(a, b);
// }
//
// Path: core/src/main/java/com/github/phantomthief/tuple/ThreeTuple.java
// public class ThreeTuple<A, B, C> extends TwoTuple<A, B> {
//
// public final C third;
//
// /**
// * use {@link Tuple#tuple(Object, Object, Object)} instead
// */
// @Deprecated
// public ThreeTuple(final A a, final B b, final C c) {
// super(a, b);
// third = c;
// }
//
// public C getThird() {
// return third;
// }
//
// @Override
// public String toString() {
// return "(" + first + ", " + second + ", " + third + ")";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = super.hashCode();
// result = prime * result + (third == null ? 0 : third.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (!super.equals(obj)) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final ThreeTuple<?, ?, ?> other = (ThreeTuple<?, ?, ?>) obj;
// if (third == null) {
// if (other.third != null) {
// return false;
// }
// } else if (!third.equals(other.third)) {
// return false;
// }
// return true;
// }
//
// }
// Path: core/src/main/java/com/github/phantomthief/util/RateLogger.java
import static com.github.phantomthief.tuple.Tuple.tuple;
import static org.slf4j.spi.LocationAwareLogger.DEBUG_INT;
import static org.slf4j.spi.LocationAwareLogger.ERROR_INT;
import static org.slf4j.spi.LocationAwareLogger.INFO_INT;
import static org.slf4j.spi.LocationAwareLogger.TRACE_INT;
import static org.slf4j.spi.LocationAwareLogger.WARN_INT;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.Nullable;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.spi.LocationAwareLogger;
import com.github.phantomthief.tuple.ThreeTuple;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
package com.github.phantomthief.util;
/**
* 使用 {@link SimpleRateLimiter} 来控制打 log 输出的频率,避免出现 log flood 占用过高的 CPU <p>
* 对于需要用一个 logger 打不同类型的日志,又不希望不同日志输出频率互相干扰(比如高频日志把低频日志淹没)<p>
* 可以使用 {@link #perMessageRateLogger(Logger)} 方式构建 logger,这时候,不同日志的区分方式是以 log.info(msg, args...);<p>
* 中第一个参数 msg 来区分,相同的 msg 会被认为是相同类型的日志,从而共享相同的频次限制;<p>
*
* 使用方法:
* <pre>
* {@code
*
* class MyObject {
* private static final Logger logger = LoggerFactory.getLogger(MyObject.class); // normal one
* private static final Logger rateLogger = RateLogger.rateLogger(logger); // wrap as a rate one
*
* void foo() {
* rateLogger.info("my message"); // use as normal logger.
* }
* }
* }
* </pre>
*
* @author w.vela
* Created on 2017-02-24.
*/
public class RateLogger implements Logger {
/**
* fully qualified class name, for short
*/
private static final String FQCN = RateLogger.class.getName();
private static final double DEFAULT_PERMITS_PER_SECOND = 1;
private static final int MAX_PER_FORMAT_CACHE_SIZE = 100;
// 直接使用Map来cache RateLogger。Logger的数量是有限的,LogBack也是使用了Map来Cache,所以没必要用一个支持evict的Cache。 | private static final ConcurrentMap<ThreeTuple<String, Double, Boolean>, RateLogger> CACHE = new ConcurrentHashMap<>(); |
PhantomThief/more-lambdas-java | core/src/main/java/com/github/phantomthief/util/RateLogger.java | // Path: core/src/main/java/com/github/phantomthief/tuple/Tuple.java
// public static <A, B> TwoTuple<A, B> tuple(final A a, final B b) {
// return new TwoTuple<>(a, b);
// }
//
// Path: core/src/main/java/com/github/phantomthief/tuple/ThreeTuple.java
// public class ThreeTuple<A, B, C> extends TwoTuple<A, B> {
//
// public final C third;
//
// /**
// * use {@link Tuple#tuple(Object, Object, Object)} instead
// */
// @Deprecated
// public ThreeTuple(final A a, final B b, final C c) {
// super(a, b);
// third = c;
// }
//
// public C getThird() {
// return third;
// }
//
// @Override
// public String toString() {
// return "(" + first + ", " + second + ", " + third + ")";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = super.hashCode();
// result = prime * result + (third == null ? 0 : third.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (!super.equals(obj)) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final ThreeTuple<?, ?, ?> other = (ThreeTuple<?, ?, ?>) obj;
// if (third == null) {
// if (other.third != null) {
// return false;
// }
// } else if (!third.equals(other.third)) {
// return false;
// }
// return true;
// }
//
// }
| import static com.github.phantomthief.tuple.Tuple.tuple;
import static org.slf4j.spi.LocationAwareLogger.DEBUG_INT;
import static org.slf4j.spi.LocationAwareLogger.ERROR_INT;
import static org.slf4j.spi.LocationAwareLogger.INFO_INT;
import static org.slf4j.spi.LocationAwareLogger.TRACE_INT;
import static org.slf4j.spi.LocationAwareLogger.WARN_INT;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.Nullable;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.spi.LocationAwareLogger;
import com.github.phantomthief.tuple.ThreeTuple;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache; |
/**
* 工厂方法
*
* @param logger 要封装的logger实例
* @param permitsPer 打log的每秒允许个数,例如传入0.2,就意味着五秒打一条log
*/
public static RateLogger rateLogger(Logger logger, double permitsPer) {
return rateLogger(logger, permitsPer, false);
}
/**
* 工厂方法,和 {@link #rateLogger} 的区别是,会按照不同的 msg 分别采样计算
*
* @param logger 要封装的logger实例
* @param permitsPer 打log的每秒允许个数,例如传入0.2,就意味着五秒打一条log
*/
public static RateLogger perMessageRateLogger(Logger logger, double permitsPer) {
return rateLogger(logger, permitsPer, true);
}
/**
* 工厂方法
*
* @param logger 要封装的logger实例
* @param permitsPer 打log的每秒允许个数,例如传入0.2,就意味着五秒打一条log
* @param perFormatString 如果为 {@code true},则按照每个 formatString 为单位而不是整个 logger 为单位执行采样
*/
private static RateLogger rateLogger(Logger logger, double permitsPer, boolean perFormatString) {
String name = logger.getName(); | // Path: core/src/main/java/com/github/phantomthief/tuple/Tuple.java
// public static <A, B> TwoTuple<A, B> tuple(final A a, final B b) {
// return new TwoTuple<>(a, b);
// }
//
// Path: core/src/main/java/com/github/phantomthief/tuple/ThreeTuple.java
// public class ThreeTuple<A, B, C> extends TwoTuple<A, B> {
//
// public final C third;
//
// /**
// * use {@link Tuple#tuple(Object, Object, Object)} instead
// */
// @Deprecated
// public ThreeTuple(final A a, final B b, final C c) {
// super(a, b);
// third = c;
// }
//
// public C getThird() {
// return third;
// }
//
// @Override
// public String toString() {
// return "(" + first + ", " + second + ", " + third + ")";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = super.hashCode();
// result = prime * result + (third == null ? 0 : third.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (!super.equals(obj)) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final ThreeTuple<?, ?, ?> other = (ThreeTuple<?, ?, ?>) obj;
// if (third == null) {
// if (other.third != null) {
// return false;
// }
// } else if (!third.equals(other.third)) {
// return false;
// }
// return true;
// }
//
// }
// Path: core/src/main/java/com/github/phantomthief/util/RateLogger.java
import static com.github.phantomthief.tuple.Tuple.tuple;
import static org.slf4j.spi.LocationAwareLogger.DEBUG_INT;
import static org.slf4j.spi.LocationAwareLogger.ERROR_INT;
import static org.slf4j.spi.LocationAwareLogger.INFO_INT;
import static org.slf4j.spi.LocationAwareLogger.TRACE_INT;
import static org.slf4j.spi.LocationAwareLogger.WARN_INT;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.Nullable;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.spi.LocationAwareLogger;
import com.github.phantomthief.tuple.ThreeTuple;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
/**
* 工厂方法
*
* @param logger 要封装的logger实例
* @param permitsPer 打log的每秒允许个数,例如传入0.2,就意味着五秒打一条log
*/
public static RateLogger rateLogger(Logger logger, double permitsPer) {
return rateLogger(logger, permitsPer, false);
}
/**
* 工厂方法,和 {@link #rateLogger} 的区别是,会按照不同的 msg 分别采样计算
*
* @param logger 要封装的logger实例
* @param permitsPer 打log的每秒允许个数,例如传入0.2,就意味着五秒打一条log
*/
public static RateLogger perMessageRateLogger(Logger logger, double permitsPer) {
return rateLogger(logger, permitsPer, true);
}
/**
* 工厂方法
*
* @param logger 要封装的logger实例
* @param permitsPer 打log的每秒允许个数,例如传入0.2,就意味着五秒打一条log
* @param perFormatString 如果为 {@code true},则按照每个 formatString 为单位而不是整个 logger 为单位执行采样
*/
private static RateLogger rateLogger(Logger logger, double permitsPer, boolean perFormatString) {
String name = logger.getName(); | ThreeTuple<String, Double, Boolean> key = tuple(name, permitsPer, perFormatString); |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/test/ToStringHelperTest.java | // Path: core/src/main/java/com/github/phantomthief/util/ToStringHelper.java
// public class ToStringHelper {
//
// public static <T> T wrapToString(Class<T> interfaceType, T obj,
// Function<T, String> toStringSupplier) {
// return newProxy(interfaceType, (proxy, method, args) -> {
// if (method.getName().equals("toString")) {
// return toStringSupplier.apply(obj);
// } else {
// return method.invoke(obj, args);
// }
// });
// }
// }
| import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.junit.jupiter.api.Test;
import com.github.phantomthief.util.ToStringHelper; | package com.github.phantomthief.test;
/**
* @author w.vela
* Created on 16/5/7.
*/
class ToStringHelperTest {
@Test
void test() {
List<Integer> list = Arrays.asList(1, 2, 3);
String ori = list.toString(); | // Path: core/src/main/java/com/github/phantomthief/util/ToStringHelper.java
// public class ToStringHelper {
//
// public static <T> T wrapToString(Class<T> interfaceType, T obj,
// Function<T, String> toStringSupplier) {
// return newProxy(interfaceType, (proxy, method, args) -> {
// if (method.getName().equals("toString")) {
// return toStringSupplier.apply(obj);
// } else {
// return method.invoke(obj, args);
// }
// });
// }
// }
// Path: core/src/test/java/com/github/phantomthief/test/ToStringHelperTest.java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.junit.jupiter.api.Test;
import com.github.phantomthief.util.ToStringHelper;
package com.github.phantomthief.test;
/**
* @author w.vela
* Created on 16/5/7.
*/
class ToStringHelperTest {
@Test
void test() {
List<Integer> list = Arrays.asList(1, 2, 3);
String ori = list.toString(); | List<Integer> list2 = ToStringHelper.wrapToString(List.class, list, i -> i + "!!!!"); |
PhantomThief/more-lambdas-java | core/src/main/java/com/github/phantomthief/pool/impl/KeyAffinityBuilder.java | // Path: core/src/main/java/com/github/phantomthief/pool/KeyAffinityExecutorUtils.java
// public static final int RANDOM_THRESHOLD = 20;
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
| import static com.github.phantomthief.pool.KeyAffinityExecutorUtils.RANDOM_THRESHOLD;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.function.BooleanSupplier;
import java.util.function.IntPredicate;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.NotThreadSafe;
import com.github.phantomthief.util.ThrowableConsumer;
import com.google.common.annotations.VisibleForTesting; | package com.github.phantomthief.pool.impl;
/**
* @author w.vela
* Created on 2018-02-09.
*/
@NotThreadSafe
class KeyAffinityBuilder<V> {
private Supplier<V> factory;
private IntSupplier count; | // Path: core/src/main/java/com/github/phantomthief/pool/KeyAffinityExecutorUtils.java
// public static final int RANDOM_THRESHOLD = 20;
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
// Path: core/src/main/java/com/github/phantomthief/pool/impl/KeyAffinityBuilder.java
import static com.github.phantomthief.pool.KeyAffinityExecutorUtils.RANDOM_THRESHOLD;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.function.BooleanSupplier;
import java.util.function.IntPredicate;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.NotThreadSafe;
import com.github.phantomthief.util.ThrowableConsumer;
import com.google.common.annotations.VisibleForTesting;
package com.github.phantomthief.pool.impl;
/**
* @author w.vela
* Created on 2018-02-09.
*/
@NotThreadSafe
class KeyAffinityBuilder<V> {
private Supplier<V> factory;
private IntSupplier count; | private ThrowableConsumer<V, Exception> depose; |
PhantomThief/more-lambdas-java | core/src/main/java/com/github/phantomthief/pool/impl/KeyAffinityBuilder.java | // Path: core/src/main/java/com/github/phantomthief/pool/KeyAffinityExecutorUtils.java
// public static final int RANDOM_THRESHOLD = 20;
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
| import static com.github.phantomthief.pool.KeyAffinityExecutorUtils.RANDOM_THRESHOLD;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.function.BooleanSupplier;
import java.util.function.IntPredicate;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.NotThreadSafe;
import com.github.phantomthief.util.ThrowableConsumer;
import com.google.common.annotations.VisibleForTesting; | package com.github.phantomthief.pool.impl;
/**
* @author w.vela
* Created on 2018-02-09.
*/
@NotThreadSafe
class KeyAffinityBuilder<V> {
private Supplier<V> factory;
private IntSupplier count;
private ThrowableConsumer<V, Exception> depose;
private IntPredicate usingRandom;
private BooleanSupplier counterChecker;
public <K> LazyKeyAffinity<K, V> build() {
ensure();
return new LazyKeyAffinity<>(this::buildInner);
}
<K> KeyAffinityImpl<K, V> buildInner() {
return new KeyAffinityImpl<>(factory, count, depose, usingRandom, counterChecker);
}
void ensure() {
if (count == null || count.getAsInt() <= 0) {
throw new IllegalArgumentException("no count found.");
}
if (counterChecker == null) {
counterChecker = () -> true;
}
if (depose == null) {
depose = it -> { };
}
if (usingRandom == null) { | // Path: core/src/main/java/com/github/phantomthief/pool/KeyAffinityExecutorUtils.java
// public static final int RANDOM_THRESHOLD = 20;
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
// Path: core/src/main/java/com/github/phantomthief/pool/impl/KeyAffinityBuilder.java
import static com.github.phantomthief.pool.KeyAffinityExecutorUtils.RANDOM_THRESHOLD;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.function.BooleanSupplier;
import java.util.function.IntPredicate;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.NotThreadSafe;
import com.github.phantomthief.util.ThrowableConsumer;
import com.google.common.annotations.VisibleForTesting;
package com.github.phantomthief.pool.impl;
/**
* @author w.vela
* Created on 2018-02-09.
*/
@NotThreadSafe
class KeyAffinityBuilder<V> {
private Supplier<V> factory;
private IntSupplier count;
private ThrowableConsumer<V, Exception> depose;
private IntPredicate usingRandom;
private BooleanSupplier counterChecker;
public <K> LazyKeyAffinity<K, V> build() {
ensure();
return new LazyKeyAffinity<>(this::buildInner);
}
<K> KeyAffinityImpl<K, V> buildInner() {
return new KeyAffinityImpl<>(factory, count, depose, usingRandom, counterChecker);
}
void ensure() {
if (count == null || count.getAsInt() <= 0) {
throw new IllegalArgumentException("no count found.");
}
if (counterChecker == null) {
counterChecker = () -> true;
}
if (depose == null) {
depose = it -> { };
}
if (usingRandom == null) { | usingRandom = it -> it > RANDOM_THRESHOLD; |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/util/MoreReflectionTest.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreReflection.java
// @Nullable
// public static StackTraceElement getCallerPlace() {
// return getCallerPlace(MoreReflection.class);
// }
| import static com.github.phantomthief.util.MoreReflection.getCallerPlace;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test; | package com.github.phantomthief.util;
/**
* @author w.vela
* Created on 2018-06-13.
*/
class MoreReflectionTest {
@Test
void test() {
MyTest.test();
MyTest.test2();
}
@Test
void testKotlinCaller() {
KotlinCaller.test1();
}
@Test
void testCaller() {
StackTraceElement callerPlace = MyTest.test3();
assertNotNull(callerPlace);
assertEquals("MoreReflectionTest.java", callerPlace.getFileName());
callerPlace = MyTest2.test41();
assertNotNull(callerPlace);
assertEquals("MoreReflectionTest.java", callerPlace.getFileName());
}
static class MyTest {
@Deprecated
static void test() { | // Path: core/src/main/java/com/github/phantomthief/util/MoreReflection.java
// @Nullable
// public static StackTraceElement getCallerPlace() {
// return getCallerPlace(MoreReflection.class);
// }
// Path: core/src/test/java/com/github/phantomthief/util/MoreReflectionTest.java
import static com.github.phantomthief.util.MoreReflection.getCallerPlace;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
package com.github.phantomthief.util;
/**
* @author w.vela
* Created on 2018-06-13.
*/
class MoreReflectionTest {
@Test
void test() {
MyTest.test();
MyTest.test2();
}
@Test
void testKotlinCaller() {
KotlinCaller.test1();
}
@Test
void testCaller() {
StackTraceElement callerPlace = MyTest.test3();
assertNotNull(callerPlace);
assertEquals("MoreReflectionTest.java", callerPlace.getFileName());
callerPlace = MyTest2.test41();
assertNotNull(callerPlace);
assertEquals("MoreReflectionTest.java", callerPlace.getFileName());
}
static class MyTest {
@Deprecated
static void test() { | System.err.println(getCallerPlace()); |
PhantomThief/more-lambdas-java | core/src/main/java/com/github/phantomthief/util/MoreIterables.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreStreams.java
// public static <T> Stream<T> toStream(Iterator<T> iterator) {
// checkNotNull(iterator);
// return stream(spliteratorUnknownSize(iterator, (NONNULL | IMMUTABLE | ORDERED)), false);
// }
| import static com.github.phantomthief.util.MoreStreams.toStream;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Iterables.partition;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import com.google.common.collect.Range; | package com.github.phantomthief.util;
/**
* MoreIterables增强工具集合
* <p>迭代器快捷工具,用于快速获取批次数列</p>
*
* @author w.vela
*/
public final class MoreIterables {
/**
* 工具类,禁止实例化成对象
*/
private MoreIterables() {
throw new UnsupportedOperationException();
}
/**
* 取得一个闭区间的long类型的数列,并按批次的大小进行分组,返回一个{@link Stream}
*
* @param from 起始值(含)
* @param to 终止值(含)
* @param batch 分组批次大小
* @return 分组序列Stream
*/
public static Stream<List<Long>> batchClosedRangeStream(long from, long to, int batch) { | // Path: core/src/main/java/com/github/phantomthief/util/MoreStreams.java
// public static <T> Stream<T> toStream(Iterator<T> iterator) {
// checkNotNull(iterator);
// return stream(spliteratorUnknownSize(iterator, (NONNULL | IMMUTABLE | ORDERED)), false);
// }
// Path: core/src/main/java/com/github/phantomthief/util/MoreIterables.java
import static com.github.phantomthief.util.MoreStreams.toStream;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Iterables.partition;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import com.google.common.collect.Range;
package com.github.phantomthief.util;
/**
* MoreIterables增强工具集合
* <p>迭代器快捷工具,用于快速获取批次数列</p>
*
* @author w.vela
*/
public final class MoreIterables {
/**
* 工具类,禁止实例化成对象
*/
private MoreIterables() {
throw new UnsupportedOperationException();
}
/**
* 取得一个闭区间的long类型的数列,并按批次的大小进行分组,返回一个{@link Stream}
*
* @param from 起始值(含)
* @param to 终止值(含)
* @param batch 分组批次大小
* @return 分组序列Stream
*/
public static Stream<List<Long>> batchClosedRangeStream(long from, long to, int batch) { | return toStream(batchClosedRange(from, to, batch)); |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/pool/impl/DynamicCapacityLinkedBlockingQueueTest.java | // Path: core/src/main/java/com/github/phantomthief/pool/impl/DynamicCapacityLinkedBlockingQueue.java
// public static <T> BlockingQueue<T> lazyDynamicCapacityLinkedBlockingQueue(IntSupplier capacity) {
// return new LazyBlockingQueue<>(() -> new DynamicCapacityLinkedBlockingQueue<>(capacity));
// }
| import static com.github.phantomthief.pool.impl.DynamicCapacityLinkedBlockingQueue.lazyDynamicCapacityLinkedBlockingQueue;
import static com.google.common.util.concurrent.SimpleTimeLimiter.create;
import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.TimeLimiter; | package com.github.phantomthief.pool.impl;
/**
* @author w.vela
* Created on 2020-08-20.
*/
class DynamicCapacityLinkedBlockingQueueTest {
private static final Logger logger = LoggerFactory.getLogger(DynamicCapacityLinkedBlockingQueueTest.class);
@Test
void test() throws InterruptedException {
int[] count = {0};
boolean[] access = {false}; | // Path: core/src/main/java/com/github/phantomthief/pool/impl/DynamicCapacityLinkedBlockingQueue.java
// public static <T> BlockingQueue<T> lazyDynamicCapacityLinkedBlockingQueue(IntSupplier capacity) {
// return new LazyBlockingQueue<>(() -> new DynamicCapacityLinkedBlockingQueue<>(capacity));
// }
// Path: core/src/test/java/com/github/phantomthief/pool/impl/DynamicCapacityLinkedBlockingQueueTest.java
import static com.github.phantomthief.pool.impl.DynamicCapacityLinkedBlockingQueue.lazyDynamicCapacityLinkedBlockingQueue;
import static com.google.common.util.concurrent.SimpleTimeLimiter.create;
import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.TimeLimiter;
package com.github.phantomthief.pool.impl;
/**
* @author w.vela
* Created on 2020-08-20.
*/
class DynamicCapacityLinkedBlockingQueueTest {
private static final Logger logger = LoggerFactory.getLogger(DynamicCapacityLinkedBlockingQueueTest.class);
@Test
void test() throws InterruptedException {
int[] count = {0};
boolean[] access = {false}; | BlockingQueue<Object> queue = lazyDynamicCapacityLinkedBlockingQueue(() -> { |
PhantomThief/more-lambdas-java | core-jdk8-test/src/test/java/com/github/phantomthief/util/MoreReflectionJdk8CompatibilityTest.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreReflection.java
// static StackTraceProvider getStackTraceProvider() {
// return STACK_TRACE_PROVIDER;
// }
| import static com.github.phantomthief.util.MoreReflection.getStackTraceProvider;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test; | package com.github.phantomthief.util;
/**
* @author w.vela
* Created on 2019-08-01.
*/
class MoreReflectionJdk8CompatibilityTest {
/**
* 需要使用 JDK8 来测试
*/
@Disabled
@Test
void test() { | // Path: core/src/main/java/com/github/phantomthief/util/MoreReflection.java
// static StackTraceProvider getStackTraceProvider() {
// return STACK_TRACE_PROVIDER;
// }
// Path: core-jdk8-test/src/test/java/com/github/phantomthief/util/MoreReflectionJdk8CompatibilityTest.java
import static com.github.phantomthief.util.MoreReflection.getStackTraceProvider;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
package com.github.phantomthief.util;
/**
* @author w.vela
* Created on 2019-08-01.
*/
class MoreReflectionJdk8CompatibilityTest {
/**
* 需要使用 JDK8 来测试
*/
@Disabled
@Test
void test() { | StackTraceProvider stackTraceProvider = getStackTraceProvider(); |
PhantomThief/more-lambdas-java | core-jdk9/src/test/java/com/github/phantomthief/util/CallerTrackBenchmark.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreReflection.java
// @Nullable
// public static StackTraceElement getCallerPlace() {
// return getCallerPlace(MoreReflection.class);
// }
| import static com.github.phantomthief.util.MoreReflection.getCallerPlace;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup; | package com.github.phantomthief.util;
/**
* 性能指标:
*
* Benchmark Mode Cnt Score Error Units
* CallerTrackBenchmark.testJdk8 thrpt 5 158153.109 ± 59700.454 ops/s
* CallerTrackBenchmark.testJdk9 thrpt 5 373640.233 ± 178347.303 ops/s
*
* @author w.vela
* Created on 2019-08-01.
*/
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 1, time = 2)
@Measurement(iterations = 5, time = 1)
@Threads(8)
@Fork(1)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
public class CallerTrackBenchmark {
@Benchmark
public static void testJdk8() {
StackTraceElement callerPlace = MyTest.test3();
callerPlace = MyTest2.test41();
}
@Benchmark
public static void testJdk9() {
StackTraceElement callerPlace = MyTest.test39();
callerPlace = MyTest2.test42();
}
static class MyTest {
private static StackTraceProviderJdk9 jdk9 = new StackTraceProviderJdk9();
private static StackTraceProviderJdk8 jdk8 = new StackTraceProviderJdk8();
@Deprecated
static void test() { | // Path: core/src/main/java/com/github/phantomthief/util/MoreReflection.java
// @Nullable
// public static StackTraceElement getCallerPlace() {
// return getCallerPlace(MoreReflection.class);
// }
// Path: core-jdk9/src/test/java/com/github/phantomthief/util/CallerTrackBenchmark.java
import static com.github.phantomthief.util.MoreReflection.getCallerPlace;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
package com.github.phantomthief.util;
/**
* 性能指标:
*
* Benchmark Mode Cnt Score Error Units
* CallerTrackBenchmark.testJdk8 thrpt 5 158153.109 ± 59700.454 ops/s
* CallerTrackBenchmark.testJdk9 thrpt 5 373640.233 ± 178347.303 ops/s
*
* @author w.vela
* Created on 2019-08-01.
*/
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 1, time = 2)
@Measurement(iterations = 5, time = 1)
@Threads(8)
@Fork(1)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
public class CallerTrackBenchmark {
@Benchmark
public static void testJdk8() {
StackTraceElement callerPlace = MyTest.test3();
callerPlace = MyTest2.test41();
}
@Benchmark
public static void testJdk9() {
StackTraceElement callerPlace = MyTest.test39();
callerPlace = MyTest2.test42();
}
static class MyTest {
private static StackTraceProviderJdk9 jdk9 = new StackTraceProviderJdk9();
private static StackTraceProviderJdk8 jdk8 = new StackTraceProviderJdk8();
@Deprecated
static void test() { | System.err.println(getCallerPlace()); |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/util/MoreCollectorsTest.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreCollectors.java
// public static <T, K> Collector<T, ?, Map<K, List<T>>> groupingByAllowNullKey(
// Function<? super T, ? extends K> classifier) {
// return groupingByAllowNullKey(classifier, toList());
// }
| import static com.github.phantomthief.util.MoreCollectors.groupingByAllowNullKey;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test; | package com.github.phantomthief.util;
/**
* MoreCollectorsTest
* <p>
* Write the code. Change the world.
*
* @author trang
* @date 2019-07-31
*/
class MoreCollectorsTest {
/**
* toMap() 本身支持 null key,但不支持 null value
*/
@Test
void toMapTest() {
Map<Integer, TestEnum1> map =
Stream.of(TestEnum1.values()).collect(toMap(TestEnum1::getValue, identity()));
assertEquals(4, map.size());
assertNotNull(map.get(null));
}
@Test
void groupingByTest() {
assertThrows(NullPointerException.class,
() -> Stream.of(TestEnum2.values()).collect(groupingBy(TestEnum2::getValue)));
}
@Test
void groupingByAllowNullKeyTest() {
Map<Integer, List<TestEnum2>> map = | // Path: core/src/main/java/com/github/phantomthief/util/MoreCollectors.java
// public static <T, K> Collector<T, ?, Map<K, List<T>>> groupingByAllowNullKey(
// Function<? super T, ? extends K> classifier) {
// return groupingByAllowNullKey(classifier, toList());
// }
// Path: core/src/test/java/com/github/phantomthief/util/MoreCollectorsTest.java
import static com.github.phantomthief.util.MoreCollectors.groupingByAllowNullKey;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
package com.github.phantomthief.util;
/**
* MoreCollectorsTest
* <p>
* Write the code. Change the world.
*
* @author trang
* @date 2019-07-31
*/
class MoreCollectorsTest {
/**
* toMap() 本身支持 null key,但不支持 null value
*/
@Test
void toMapTest() {
Map<Integer, TestEnum1> map =
Stream.of(TestEnum1.values()).collect(toMap(TestEnum1::getValue, identity()));
assertEquals(4, map.size());
assertNotNull(map.get(null));
}
@Test
void groupingByTest() {
assertThrows(NullPointerException.class,
() -> Stream.of(TestEnum2.values()).collect(groupingBy(TestEnum2::getValue)));
}
@Test
void groupingByAllowNullKeyTest() {
Map<Integer, List<TestEnum2>> map = | Stream.of(TestEnum2.values()).collect(groupingByAllowNullKey(TestEnum2::getValue)); |
PhantomThief/more-lambdas-java | core/src/main/java/com/github/phantomthief/pool/impl/KeyAffinityImpl.java | // Path: core/src/main/java/com/github/phantomthief/pool/KeyAffinity.java
// @Deprecated
// public interface KeyAffinity<K, V> extends AutoCloseable, Iterable<V> {
//
// boolean inited();
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
| import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterators.transform;
import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
import static java.util.Comparator.comparingInt;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BooleanSupplier;
import java.util.function.IntPredicate;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.phantomthief.pool.KeyAffinity;
import com.github.phantomthief.util.ThrowableConsumer;
import com.google.common.annotations.VisibleForTesting; | package com.github.phantomthief.pool.impl;
/**
* @author w.vela
* Created on 2018-02-08.
*/
class KeyAffinityImpl<K, V> implements KeyAffinity<K, V> {
private static final Logger logger = LoggerFactory.getLogger(KeyAffinityImpl.class);
private static long sleepBeforeClose = SECONDS.toMillis(5);
private final IntSupplier count;
private final List<ValueRef> all; | // Path: core/src/main/java/com/github/phantomthief/pool/KeyAffinity.java
// @Deprecated
// public interface KeyAffinity<K, V> extends AutoCloseable, Iterable<V> {
//
// boolean inited();
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/ThrowableConsumer.java
// @FunctionalInterface
// public interface ThrowableConsumer<T, X extends Throwable> {
//
// void accept(T t) throws X;
//
// default ThrowableConsumer<T, X> andThen(ThrowableConsumer<? super T, X> after) {
// requireNonNull(after);
// return t -> {
// accept(t);
// after.accept(t);
// };
// }
// }
// Path: core/src/main/java/com/github/phantomthief/pool/impl/KeyAffinityImpl.java
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterators.transform;
import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
import static java.util.Comparator.comparingInt;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BooleanSupplier;
import java.util.function.IntPredicate;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.phantomthief.pool.KeyAffinity;
import com.github.phantomthief.util.ThrowableConsumer;
import com.google.common.annotations.VisibleForTesting;
package com.github.phantomthief.pool.impl;
/**
* @author w.vela
* Created on 2018-02-08.
*/
class KeyAffinityImpl<K, V> implements KeyAffinity<K, V> {
private static final Logger logger = LoggerFactory.getLogger(KeyAffinityImpl.class);
private static long sleepBeforeClose = SECONDS.toMillis(5);
private final IntSupplier count;
private final List<ValueRef> all; | private final ThrowableConsumer<V, Exception> deposeFunc; |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/test/MoreFunctionsTest.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R catching(Callable<R> callable) {
// return catching(callable, e -> logger.error(FAIL_SAFE_MARK, e));
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Consumer<Entry<K, V>> consumerKv(BiConsumer<K, V> func) {
// return entry -> func.accept(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Predicate<Entry<K, V>> filterKv(BiPredicate<K, V> func) {
// return entry -> func.test(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V, T> Function<Entry<K, V>, T> mapKv(BiFunction<K, V, T> func) {
// return entry -> func.apply(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runParallel(ForkJoinPool pool,
// ThrowableRunnable<X> func) throws X {
// supplyParallel(pool, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runWithThreadName(
// @Nonnull Function<String, String> name, @Nonnull ThrowableRunnable<X> func) throws X {
// supplyWithThreadName(name, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R throwing(Callable<R> callable) {
// return catching(callable, throwable -> {
// throwIfUnchecked(throwable);
// throw new RuntimeException(throwable);
// });
// }
| import static com.github.phantomthief.util.MoreFunctions.catching;
import static com.github.phantomthief.util.MoreFunctions.consumerKv;
import static com.github.phantomthief.util.MoreFunctions.filterKv;
import static com.github.phantomthief.util.MoreFunctions.mapKv;
import static com.github.phantomthief.util.MoreFunctions.runParallel;
import static com.github.phantomthief.util.MoreFunctions.runWithThreadName;
import static com.github.phantomthief.util.MoreFunctions.throwing;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap; | package com.github.phantomthief.test;
/**
* @author w.vela
*/
class MoreFunctionsTest {
@Test
void testTrying() { | // Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R catching(Callable<R> callable) {
// return catching(callable, e -> logger.error(FAIL_SAFE_MARK, e));
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Consumer<Entry<K, V>> consumerKv(BiConsumer<K, V> func) {
// return entry -> func.accept(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Predicate<Entry<K, V>> filterKv(BiPredicate<K, V> func) {
// return entry -> func.test(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V, T> Function<Entry<K, V>, T> mapKv(BiFunction<K, V, T> func) {
// return entry -> func.apply(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runParallel(ForkJoinPool pool,
// ThrowableRunnable<X> func) throws X {
// supplyParallel(pool, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runWithThreadName(
// @Nonnull Function<String, String> name, @Nonnull ThrowableRunnable<X> func) throws X {
// supplyWithThreadName(name, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R throwing(Callable<R> callable) {
// return catching(callable, throwable -> {
// throwIfUnchecked(throwable);
// throw new RuntimeException(throwable);
// });
// }
// Path: core/src/test/java/com/github/phantomthief/test/MoreFunctionsTest.java
import static com.github.phantomthief.util.MoreFunctions.catching;
import static com.github.phantomthief.util.MoreFunctions.consumerKv;
import static com.github.phantomthief.util.MoreFunctions.filterKv;
import static com.github.phantomthief.util.MoreFunctions.mapKv;
import static com.github.phantomthief.util.MoreFunctions.runParallel;
import static com.github.phantomthief.util.MoreFunctions.runWithThreadName;
import static com.github.phantomthief.util.MoreFunctions.throwing;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
package com.github.phantomthief.test;
/**
* @author w.vela
*/
class MoreFunctionsTest {
@Test
void testTrying() { | assertNull(catching(i -> function(i, Exception::new), 1)); |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/test/MoreFunctionsTest.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R catching(Callable<R> callable) {
// return catching(callable, e -> logger.error(FAIL_SAFE_MARK, e));
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Consumer<Entry<K, V>> consumerKv(BiConsumer<K, V> func) {
// return entry -> func.accept(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Predicate<Entry<K, V>> filterKv(BiPredicate<K, V> func) {
// return entry -> func.test(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V, T> Function<Entry<K, V>, T> mapKv(BiFunction<K, V, T> func) {
// return entry -> func.apply(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runParallel(ForkJoinPool pool,
// ThrowableRunnable<X> func) throws X {
// supplyParallel(pool, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runWithThreadName(
// @Nonnull Function<String, String> name, @Nonnull ThrowableRunnable<X> func) throws X {
// supplyWithThreadName(name, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R throwing(Callable<R> callable) {
// return catching(callable, throwable -> {
// throwIfUnchecked(throwable);
// throw new RuntimeException(throwable);
// });
// }
| import static com.github.phantomthief.util.MoreFunctions.catching;
import static com.github.phantomthief.util.MoreFunctions.consumerKv;
import static com.github.phantomthief.util.MoreFunctions.filterKv;
import static com.github.phantomthief.util.MoreFunctions.mapKv;
import static com.github.phantomthief.util.MoreFunctions.runParallel;
import static com.github.phantomthief.util.MoreFunctions.runWithThreadName;
import static com.github.phantomthief.util.MoreFunctions.throwing;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap; | package com.github.phantomthief.test;
/**
* @author w.vela
*/
class MoreFunctionsTest {
@Test
void testTrying() {
assertNull(catching(i -> function(i, Exception::new), 1));
assertNull(catching(i -> function(i, IllegalArgumentException::new), 1));
assertEquals("1", catching(i -> function(i, null), 1));
}
@Test
void testThrowing() { | // Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R catching(Callable<R> callable) {
// return catching(callable, e -> logger.error(FAIL_SAFE_MARK, e));
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Consumer<Entry<K, V>> consumerKv(BiConsumer<K, V> func) {
// return entry -> func.accept(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Predicate<Entry<K, V>> filterKv(BiPredicate<K, V> func) {
// return entry -> func.test(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V, T> Function<Entry<K, V>, T> mapKv(BiFunction<K, V, T> func) {
// return entry -> func.apply(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runParallel(ForkJoinPool pool,
// ThrowableRunnable<X> func) throws X {
// supplyParallel(pool, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runWithThreadName(
// @Nonnull Function<String, String> name, @Nonnull ThrowableRunnable<X> func) throws X {
// supplyWithThreadName(name, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R throwing(Callable<R> callable) {
// return catching(callable, throwable -> {
// throwIfUnchecked(throwable);
// throw new RuntimeException(throwable);
// });
// }
// Path: core/src/test/java/com/github/phantomthief/test/MoreFunctionsTest.java
import static com.github.phantomthief.util.MoreFunctions.catching;
import static com.github.phantomthief.util.MoreFunctions.consumerKv;
import static com.github.phantomthief.util.MoreFunctions.filterKv;
import static com.github.phantomthief.util.MoreFunctions.mapKv;
import static com.github.phantomthief.util.MoreFunctions.runParallel;
import static com.github.phantomthief.util.MoreFunctions.runWithThreadName;
import static com.github.phantomthief.util.MoreFunctions.throwing;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
package com.github.phantomthief.test;
/**
* @author w.vela
*/
class MoreFunctionsTest {
@Test
void testTrying() {
assertNull(catching(i -> function(i, Exception::new), 1));
assertNull(catching(i -> function(i, IllegalArgumentException::new), 1));
assertEquals("1", catching(i -> function(i, null), 1));
}
@Test
void testThrowing() { | assertThrows(IllegalArgumentException.class, () -> throwing(() -> { |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/test/MoreFunctionsTest.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R catching(Callable<R> callable) {
// return catching(callable, e -> logger.error(FAIL_SAFE_MARK, e));
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Consumer<Entry<K, V>> consumerKv(BiConsumer<K, V> func) {
// return entry -> func.accept(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Predicate<Entry<K, V>> filterKv(BiPredicate<K, V> func) {
// return entry -> func.test(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V, T> Function<Entry<K, V>, T> mapKv(BiFunction<K, V, T> func) {
// return entry -> func.apply(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runParallel(ForkJoinPool pool,
// ThrowableRunnable<X> func) throws X {
// supplyParallel(pool, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runWithThreadName(
// @Nonnull Function<String, String> name, @Nonnull ThrowableRunnable<X> func) throws X {
// supplyWithThreadName(name, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R throwing(Callable<R> callable) {
// return catching(callable, throwable -> {
// throwIfUnchecked(throwable);
// throw new RuntimeException(throwable);
// });
// }
| import static com.github.phantomthief.util.MoreFunctions.catching;
import static com.github.phantomthief.util.MoreFunctions.consumerKv;
import static com.github.phantomthief.util.MoreFunctions.filterKv;
import static com.github.phantomthief.util.MoreFunctions.mapKv;
import static com.github.phantomthief.util.MoreFunctions.runParallel;
import static com.github.phantomthief.util.MoreFunctions.runWithThreadName;
import static com.github.phantomthief.util.MoreFunctions.throwing;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap; | package com.github.phantomthief.test;
/**
* @author w.vela
*/
class MoreFunctionsTest {
@Test
void testTrying() {
assertNull(catching(i -> function(i, Exception::new), 1));
assertNull(catching(i -> function(i, IllegalArgumentException::new), 1));
assertEquals("1", catching(i -> function(i, null), 1));
}
@Test
void testThrowing() {
assertThrows(IllegalArgumentException.class, () -> throwing(() -> {
throw new IllegalArgumentException();
}));
assertTrue(assertThrows(RuntimeException.class, () -> throwing(() -> {
throw new IOException();
})).getCause() instanceof IOException);
}
private <X extends Throwable> String function(int i, Supplier<X> exception) throws X {
if (exception != null) {
X x = exception.get();
throw x;
} else {
return i + "";
}
}
@Test
void testParallel() {
List<Integer> list = Stream.iterate(1, i -> i + 1).limit(10000).collect(toList()); | // Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R catching(Callable<R> callable) {
// return catching(callable, e -> logger.error(FAIL_SAFE_MARK, e));
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Consumer<Entry<K, V>> consumerKv(BiConsumer<K, V> func) {
// return entry -> func.accept(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Predicate<Entry<K, V>> filterKv(BiPredicate<K, V> func) {
// return entry -> func.test(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V, T> Function<Entry<K, V>, T> mapKv(BiFunction<K, V, T> func) {
// return entry -> func.apply(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runParallel(ForkJoinPool pool,
// ThrowableRunnable<X> func) throws X {
// supplyParallel(pool, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runWithThreadName(
// @Nonnull Function<String, String> name, @Nonnull ThrowableRunnable<X> func) throws X {
// supplyWithThreadName(name, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R throwing(Callable<R> callable) {
// return catching(callable, throwable -> {
// throwIfUnchecked(throwable);
// throw new RuntimeException(throwable);
// });
// }
// Path: core/src/test/java/com/github/phantomthief/test/MoreFunctionsTest.java
import static com.github.phantomthief.util.MoreFunctions.catching;
import static com.github.phantomthief.util.MoreFunctions.consumerKv;
import static com.github.phantomthief.util.MoreFunctions.filterKv;
import static com.github.phantomthief.util.MoreFunctions.mapKv;
import static com.github.phantomthief.util.MoreFunctions.runParallel;
import static com.github.phantomthief.util.MoreFunctions.runWithThreadName;
import static com.github.phantomthief.util.MoreFunctions.throwing;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
package com.github.phantomthief.test;
/**
* @author w.vela
*/
class MoreFunctionsTest {
@Test
void testTrying() {
assertNull(catching(i -> function(i, Exception::new), 1));
assertNull(catching(i -> function(i, IllegalArgumentException::new), 1));
assertEquals("1", catching(i -> function(i, null), 1));
}
@Test
void testThrowing() {
assertThrows(IllegalArgumentException.class, () -> throwing(() -> {
throw new IllegalArgumentException();
}));
assertTrue(assertThrows(RuntimeException.class, () -> throwing(() -> {
throw new IOException();
})).getCause() instanceof IOException);
}
private <X extends Throwable> String function(int i, Supplier<X> exception) throws X {
if (exception != null) {
X x = exception.get();
throw x;
} else {
return i + "";
}
}
@Test
void testParallel() {
List<Integer> list = Stream.iterate(1, i -> i + 1).limit(10000).collect(toList()); | runParallel(new ForkJoinPool(10), () -> list.stream().parallel() |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/test/MoreFunctionsTest.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R catching(Callable<R> callable) {
// return catching(callable, e -> logger.error(FAIL_SAFE_MARK, e));
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Consumer<Entry<K, V>> consumerKv(BiConsumer<K, V> func) {
// return entry -> func.accept(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Predicate<Entry<K, V>> filterKv(BiPredicate<K, V> func) {
// return entry -> func.test(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V, T> Function<Entry<K, V>, T> mapKv(BiFunction<K, V, T> func) {
// return entry -> func.apply(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runParallel(ForkJoinPool pool,
// ThrowableRunnable<X> func) throws X {
// supplyParallel(pool, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runWithThreadName(
// @Nonnull Function<String, String> name, @Nonnull ThrowableRunnable<X> func) throws X {
// supplyWithThreadName(name, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R throwing(Callable<R> callable) {
// return catching(callable, throwable -> {
// throwIfUnchecked(throwable);
// throw new RuntimeException(throwable);
// });
// }
| import static com.github.phantomthief.util.MoreFunctions.catching;
import static com.github.phantomthief.util.MoreFunctions.consumerKv;
import static com.github.phantomthief.util.MoreFunctions.filterKv;
import static com.github.phantomthief.util.MoreFunctions.mapKv;
import static com.github.phantomthief.util.MoreFunctions.runParallel;
import static com.github.phantomthief.util.MoreFunctions.runWithThreadName;
import static com.github.phantomthief.util.MoreFunctions.throwing;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap; |
@Test
void testThrowing() {
assertThrows(IllegalArgumentException.class, () -> throwing(() -> {
throw new IllegalArgumentException();
}));
assertTrue(assertThrows(RuntimeException.class, () -> throwing(() -> {
throw new IOException();
})).getCause() instanceof IOException);
}
private <X extends Throwable> String function(int i, Supplier<X> exception) throws X {
if (exception != null) {
X x = exception.get();
throw x;
} else {
return i + "";
}
}
@Test
void testParallel() {
List<Integer> list = Stream.iterate(1, i -> i + 1).limit(10000).collect(toList());
runParallel(new ForkJoinPool(10), () -> list.stream().parallel()
.forEach(System.out::println));
}
@Test
void testThreadName() {
String mySuffix = "MySuffix"; | // Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R catching(Callable<R> callable) {
// return catching(callable, e -> logger.error(FAIL_SAFE_MARK, e));
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Consumer<Entry<K, V>> consumerKv(BiConsumer<K, V> func) {
// return entry -> func.accept(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Predicate<Entry<K, V>> filterKv(BiPredicate<K, V> func) {
// return entry -> func.test(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V, T> Function<Entry<K, V>, T> mapKv(BiFunction<K, V, T> func) {
// return entry -> func.apply(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runParallel(ForkJoinPool pool,
// ThrowableRunnable<X> func) throws X {
// supplyParallel(pool, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runWithThreadName(
// @Nonnull Function<String, String> name, @Nonnull ThrowableRunnable<X> func) throws X {
// supplyWithThreadName(name, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R throwing(Callable<R> callable) {
// return catching(callable, throwable -> {
// throwIfUnchecked(throwable);
// throw new RuntimeException(throwable);
// });
// }
// Path: core/src/test/java/com/github/phantomthief/test/MoreFunctionsTest.java
import static com.github.phantomthief.util.MoreFunctions.catching;
import static com.github.phantomthief.util.MoreFunctions.consumerKv;
import static com.github.phantomthief.util.MoreFunctions.filterKv;
import static com.github.phantomthief.util.MoreFunctions.mapKv;
import static com.github.phantomthief.util.MoreFunctions.runParallel;
import static com.github.phantomthief.util.MoreFunctions.runWithThreadName;
import static com.github.phantomthief.util.MoreFunctions.throwing;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
@Test
void testThrowing() {
assertThrows(IllegalArgumentException.class, () -> throwing(() -> {
throw new IllegalArgumentException();
}));
assertTrue(assertThrows(RuntimeException.class, () -> throwing(() -> {
throw new IOException();
})).getCause() instanceof IOException);
}
private <X extends Throwable> String function(int i, Supplier<X> exception) throws X {
if (exception != null) {
X x = exception.get();
throw x;
} else {
return i + "";
}
}
@Test
void testParallel() {
List<Integer> list = Stream.iterate(1, i -> i + 1).limit(10000).collect(toList());
runParallel(new ForkJoinPool(10), () -> list.stream().parallel()
.forEach(System.out::println));
}
@Test
void testThreadName() {
String mySuffix = "MySuffix"; | runWithThreadName(it -> it + mySuffix, () -> { |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/test/MoreFunctionsTest.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R catching(Callable<R> callable) {
// return catching(callable, e -> logger.error(FAIL_SAFE_MARK, e));
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Consumer<Entry<K, V>> consumerKv(BiConsumer<K, V> func) {
// return entry -> func.accept(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Predicate<Entry<K, V>> filterKv(BiPredicate<K, V> func) {
// return entry -> func.test(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V, T> Function<Entry<K, V>, T> mapKv(BiFunction<K, V, T> func) {
// return entry -> func.apply(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runParallel(ForkJoinPool pool,
// ThrowableRunnable<X> func) throws X {
// supplyParallel(pool, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runWithThreadName(
// @Nonnull Function<String, String> name, @Nonnull ThrowableRunnable<X> func) throws X {
// supplyWithThreadName(name, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R throwing(Callable<R> callable) {
// return catching(callable, throwable -> {
// throwIfUnchecked(throwable);
// throw new RuntimeException(throwable);
// });
// }
| import static com.github.phantomthief.util.MoreFunctions.catching;
import static com.github.phantomthief.util.MoreFunctions.consumerKv;
import static com.github.phantomthief.util.MoreFunctions.filterKv;
import static com.github.phantomthief.util.MoreFunctions.mapKv;
import static com.github.phantomthief.util.MoreFunctions.runParallel;
import static com.github.phantomthief.util.MoreFunctions.runWithThreadName;
import static com.github.phantomthief.util.MoreFunctions.throwing;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap; | }
private <X extends Throwable> String function(int i, Supplier<X> exception) throws X {
if (exception != null) {
X x = exception.get();
throw x;
} else {
return i + "";
}
}
@Test
void testParallel() {
List<Integer> list = Stream.iterate(1, i -> i + 1).limit(10000).collect(toList());
runParallel(new ForkJoinPool(10), () -> list.stream().parallel()
.forEach(System.out::println));
}
@Test
void testThreadName() {
String mySuffix = "MySuffix";
runWithThreadName(it -> it + mySuffix, () -> {
assertTrue(Thread.currentThread().getName().endsWith(mySuffix));
});
}
@Test
void testKv() {
Map<String, Integer> map = ImmutableMap.of("test", 1, "a1", 2);
map.entrySet().stream() | // Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R catching(Callable<R> callable) {
// return catching(callable, e -> logger.error(FAIL_SAFE_MARK, e));
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Consumer<Entry<K, V>> consumerKv(BiConsumer<K, V> func) {
// return entry -> func.accept(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Predicate<Entry<K, V>> filterKv(BiPredicate<K, V> func) {
// return entry -> func.test(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V, T> Function<Entry<K, V>, T> mapKv(BiFunction<K, V, T> func) {
// return entry -> func.apply(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runParallel(ForkJoinPool pool,
// ThrowableRunnable<X> func) throws X {
// supplyParallel(pool, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runWithThreadName(
// @Nonnull Function<String, String> name, @Nonnull ThrowableRunnable<X> func) throws X {
// supplyWithThreadName(name, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R throwing(Callable<R> callable) {
// return catching(callable, throwable -> {
// throwIfUnchecked(throwable);
// throw new RuntimeException(throwable);
// });
// }
// Path: core/src/test/java/com/github/phantomthief/test/MoreFunctionsTest.java
import static com.github.phantomthief.util.MoreFunctions.catching;
import static com.github.phantomthief.util.MoreFunctions.consumerKv;
import static com.github.phantomthief.util.MoreFunctions.filterKv;
import static com.github.phantomthief.util.MoreFunctions.mapKv;
import static com.github.phantomthief.util.MoreFunctions.runParallel;
import static com.github.phantomthief.util.MoreFunctions.runWithThreadName;
import static com.github.phantomthief.util.MoreFunctions.throwing;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
}
private <X extends Throwable> String function(int i, Supplier<X> exception) throws X {
if (exception != null) {
X x = exception.get();
throw x;
} else {
return i + "";
}
}
@Test
void testParallel() {
List<Integer> list = Stream.iterate(1, i -> i + 1).limit(10000).collect(toList());
runParallel(new ForkJoinPool(10), () -> list.stream().parallel()
.forEach(System.out::println));
}
@Test
void testThreadName() {
String mySuffix = "MySuffix";
runWithThreadName(it -> it + mySuffix, () -> {
assertTrue(Thread.currentThread().getName().endsWith(mySuffix));
});
}
@Test
void testKv() {
Map<String, Integer> map = ImmutableMap.of("test", 1, "a1", 2);
map.entrySet().stream() | .filter(filterKv((k, v) -> true)) |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/test/MoreFunctionsTest.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R catching(Callable<R> callable) {
// return catching(callable, e -> logger.error(FAIL_SAFE_MARK, e));
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Consumer<Entry<K, V>> consumerKv(BiConsumer<K, V> func) {
// return entry -> func.accept(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Predicate<Entry<K, V>> filterKv(BiPredicate<K, V> func) {
// return entry -> func.test(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V, T> Function<Entry<K, V>, T> mapKv(BiFunction<K, V, T> func) {
// return entry -> func.apply(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runParallel(ForkJoinPool pool,
// ThrowableRunnable<X> func) throws X {
// supplyParallel(pool, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runWithThreadName(
// @Nonnull Function<String, String> name, @Nonnull ThrowableRunnable<X> func) throws X {
// supplyWithThreadName(name, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R throwing(Callable<R> callable) {
// return catching(callable, throwable -> {
// throwIfUnchecked(throwable);
// throw new RuntimeException(throwable);
// });
// }
| import static com.github.phantomthief.util.MoreFunctions.catching;
import static com.github.phantomthief.util.MoreFunctions.consumerKv;
import static com.github.phantomthief.util.MoreFunctions.filterKv;
import static com.github.phantomthief.util.MoreFunctions.mapKv;
import static com.github.phantomthief.util.MoreFunctions.runParallel;
import static com.github.phantomthief.util.MoreFunctions.runWithThreadName;
import static com.github.phantomthief.util.MoreFunctions.throwing;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap; |
private <X extends Throwable> String function(int i, Supplier<X> exception) throws X {
if (exception != null) {
X x = exception.get();
throw x;
} else {
return i + "";
}
}
@Test
void testParallel() {
List<Integer> list = Stream.iterate(1, i -> i + 1).limit(10000).collect(toList());
runParallel(new ForkJoinPool(10), () -> list.stream().parallel()
.forEach(System.out::println));
}
@Test
void testThreadName() {
String mySuffix = "MySuffix";
runWithThreadName(it -> it + mySuffix, () -> {
assertTrue(Thread.currentThread().getName().endsWith(mySuffix));
});
}
@Test
void testKv() {
Map<String, Integer> map = ImmutableMap.of("test", 1, "a1", 2);
map.entrySet().stream()
.filter(filterKv((k, v) -> true)) | // Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R catching(Callable<R> callable) {
// return catching(callable, e -> logger.error(FAIL_SAFE_MARK, e));
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Consumer<Entry<K, V>> consumerKv(BiConsumer<K, V> func) {
// return entry -> func.accept(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Predicate<Entry<K, V>> filterKv(BiPredicate<K, V> func) {
// return entry -> func.test(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V, T> Function<Entry<K, V>, T> mapKv(BiFunction<K, V, T> func) {
// return entry -> func.apply(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runParallel(ForkJoinPool pool,
// ThrowableRunnable<X> func) throws X {
// supplyParallel(pool, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runWithThreadName(
// @Nonnull Function<String, String> name, @Nonnull ThrowableRunnable<X> func) throws X {
// supplyWithThreadName(name, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R throwing(Callable<R> callable) {
// return catching(callable, throwable -> {
// throwIfUnchecked(throwable);
// throw new RuntimeException(throwable);
// });
// }
// Path: core/src/test/java/com/github/phantomthief/test/MoreFunctionsTest.java
import static com.github.phantomthief.util.MoreFunctions.catching;
import static com.github.phantomthief.util.MoreFunctions.consumerKv;
import static com.github.phantomthief.util.MoreFunctions.filterKv;
import static com.github.phantomthief.util.MoreFunctions.mapKv;
import static com.github.phantomthief.util.MoreFunctions.runParallel;
import static com.github.phantomthief.util.MoreFunctions.runWithThreadName;
import static com.github.phantomthief.util.MoreFunctions.throwing;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
private <X extends Throwable> String function(int i, Supplier<X> exception) throws X {
if (exception != null) {
X x = exception.get();
throw x;
} else {
return i + "";
}
}
@Test
void testParallel() {
List<Integer> list = Stream.iterate(1, i -> i + 1).limit(10000).collect(toList());
runParallel(new ForkJoinPool(10), () -> list.stream().parallel()
.forEach(System.out::println));
}
@Test
void testThreadName() {
String mySuffix = "MySuffix";
runWithThreadName(it -> it + mySuffix, () -> {
assertTrue(Thread.currentThread().getName().endsWith(mySuffix));
});
}
@Test
void testKv() {
Map<String, Integer> map = ImmutableMap.of("test", 1, "a1", 2);
map.entrySet().stream()
.filter(filterKv((k, v) -> true)) | .forEach(consumerKv((k, v) -> System.out.println(k + "==>" + v))); |
PhantomThief/more-lambdas-java | core/src/test/java/com/github/phantomthief/test/MoreFunctionsTest.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R catching(Callable<R> callable) {
// return catching(callable, e -> logger.error(FAIL_SAFE_MARK, e));
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Consumer<Entry<K, V>> consumerKv(BiConsumer<K, V> func) {
// return entry -> func.accept(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Predicate<Entry<K, V>> filterKv(BiPredicate<K, V> func) {
// return entry -> func.test(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V, T> Function<Entry<K, V>, T> mapKv(BiFunction<K, V, T> func) {
// return entry -> func.apply(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runParallel(ForkJoinPool pool,
// ThrowableRunnable<X> func) throws X {
// supplyParallel(pool, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runWithThreadName(
// @Nonnull Function<String, String> name, @Nonnull ThrowableRunnable<X> func) throws X {
// supplyWithThreadName(name, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R throwing(Callable<R> callable) {
// return catching(callable, throwable -> {
// throwIfUnchecked(throwable);
// throw new RuntimeException(throwable);
// });
// }
| import static com.github.phantomthief.util.MoreFunctions.catching;
import static com.github.phantomthief.util.MoreFunctions.consumerKv;
import static com.github.phantomthief.util.MoreFunctions.filterKv;
import static com.github.phantomthief.util.MoreFunctions.mapKv;
import static com.github.phantomthief.util.MoreFunctions.runParallel;
import static com.github.phantomthief.util.MoreFunctions.runWithThreadName;
import static com.github.phantomthief.util.MoreFunctions.throwing;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap; | if (exception != null) {
X x = exception.get();
throw x;
} else {
return i + "";
}
}
@Test
void testParallel() {
List<Integer> list = Stream.iterate(1, i -> i + 1).limit(10000).collect(toList());
runParallel(new ForkJoinPool(10), () -> list.stream().parallel()
.forEach(System.out::println));
}
@Test
void testThreadName() {
String mySuffix = "MySuffix";
runWithThreadName(it -> it + mySuffix, () -> {
assertTrue(Thread.currentThread().getName().endsWith(mySuffix));
});
}
@Test
void testKv() {
Map<String, Integer> map = ImmutableMap.of("test", 1, "a1", 2);
map.entrySet().stream()
.filter(filterKv((k, v) -> true))
.forEach(consumerKv((k, v) -> System.out.println(k + "==>" + v)));
map.entrySet().stream() | // Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R catching(Callable<R> callable) {
// return catching(callable, e -> logger.error(FAIL_SAFE_MARK, e));
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Consumer<Entry<K, V>> consumerKv(BiConsumer<K, V> func) {
// return entry -> func.accept(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V> Predicate<Entry<K, V>> filterKv(BiPredicate<K, V> func) {
// return entry -> func.test(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <K, V, T> Function<Entry<K, V>, T> mapKv(BiFunction<K, V, T> func) {
// return entry -> func.apply(entry.getKey(), entry.getValue());
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runParallel(ForkJoinPool pool,
// ThrowableRunnable<X> func) throws X {
// supplyParallel(pool, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <X extends Throwable> void runWithThreadName(
// @Nonnull Function<String, String> name, @Nonnull ThrowableRunnable<X> func) throws X {
// supplyWithThreadName(name, () -> {
// func.run();
// return null;
// });
// }
//
// Path: core/src/main/java/com/github/phantomthief/util/MoreFunctions.java
// public static <R> R throwing(Callable<R> callable) {
// return catching(callable, throwable -> {
// throwIfUnchecked(throwable);
// throw new RuntimeException(throwable);
// });
// }
// Path: core/src/test/java/com/github/phantomthief/test/MoreFunctionsTest.java
import static com.github.phantomthief.util.MoreFunctions.catching;
import static com.github.phantomthief.util.MoreFunctions.consumerKv;
import static com.github.phantomthief.util.MoreFunctions.filterKv;
import static com.github.phantomthief.util.MoreFunctions.mapKv;
import static com.github.phantomthief.util.MoreFunctions.runParallel;
import static com.github.phantomthief.util.MoreFunctions.runWithThreadName;
import static com.github.phantomthief.util.MoreFunctions.throwing;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
if (exception != null) {
X x = exception.get();
throw x;
} else {
return i + "";
}
}
@Test
void testParallel() {
List<Integer> list = Stream.iterate(1, i -> i + 1).limit(10000).collect(toList());
runParallel(new ForkJoinPool(10), () -> list.stream().parallel()
.forEach(System.out::println));
}
@Test
void testThreadName() {
String mySuffix = "MySuffix";
runWithThreadName(it -> it + mySuffix, () -> {
assertTrue(Thread.currentThread().getName().endsWith(mySuffix));
});
}
@Test
void testKv() {
Map<String, Integer> map = ImmutableMap.of("test", 1, "a1", 2);
map.entrySet().stream()
.filter(filterKv((k, v) -> true))
.forEach(consumerKv((k, v) -> System.out.println(k + "==>" + v)));
map.entrySet().stream() | .map(mapKv((k, v) -> v)) |
PhantomThief/more-lambdas-java | core-jdk9/src/main/java/com/github/phantomthief/util/StackTraceProviderJdk9.java | // Path: core/src/main/java/com/github/phantomthief/util/StackTraceProviderJdk8.java
// static final String[] REFLECTION_PREFIXES = {"sun.reflect.", "java.lang.reflect.", "jdk.internal.reflect."};
| import static com.github.phantomthief.util.StackTraceProviderJdk8.REFLECTION_PREFIXES;
import static java.lang.StackWalker.Option.RETAIN_CLASS_REFERENCE;
import java.lang.StackWalker.StackFrame;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils; | return false;
}
if (afterSelf) {
if (deprecatedClass == null) {
deprecatedClass = declaringClass;
}
}
if (declaringClass == deprecatedClass) {
afterDeprecated = true;
return false;
}
if (ignore.test(declaringClass.getName())) {
return false;
}
return afterDeprecated;
})
.findAny()
.map(StackFrame::toStackTraceElement)
.orElse(null);
}
});
}
/**
* at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
* at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
* at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
* at java.base/java.lang.reflect.Method.invoke(Method.java:566)
*/
private boolean isReflection(String className) { | // Path: core/src/main/java/com/github/phantomthief/util/StackTraceProviderJdk8.java
// static final String[] REFLECTION_PREFIXES = {"sun.reflect.", "java.lang.reflect.", "jdk.internal.reflect."};
// Path: core-jdk9/src/main/java/com/github/phantomthief/util/StackTraceProviderJdk9.java
import static com.github.phantomthief.util.StackTraceProviderJdk8.REFLECTION_PREFIXES;
import static java.lang.StackWalker.Option.RETAIN_CLASS_REFERENCE;
import java.lang.StackWalker.StackFrame;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
return false;
}
if (afterSelf) {
if (deprecatedClass == null) {
deprecatedClass = declaringClass;
}
}
if (declaringClass == deprecatedClass) {
afterDeprecated = true;
return false;
}
if (ignore.test(declaringClass.getName())) {
return false;
}
return afterDeprecated;
})
.findAny()
.map(StackFrame::toStackTraceElement)
.orElse(null);
}
});
}
/**
* at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
* at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
* at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
* at java.base/java.lang.reflect.Method.invoke(Method.java:566)
*/
private boolean isReflection(String className) { | return StringUtils.startsWithAny(className, REFLECTION_PREFIXES); |
PhantomThief/more-lambdas-java | core/src/main/java/com/github/phantomthief/concurrent/TryWaitResult.java | // Path: core/src/main/java/com/github/phantomthief/util/MoreSuppliers.java
// public static <T> CloseableSupplier<T> lazy(Supplier<T> delegate) {
// return lazy(delegate, true);
// }
| import static com.github.phantomthief.util.MoreSuppliers.lazy;
import static com.google.common.base.MoreObjects.toStringHelper;
import static java.util.stream.Collectors.toMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nonnull; | package com.github.phantomthief.concurrent;
/**
* @author w.vela
* Created on 2018-06-25.
*/
class TryWaitResult<K, V> {
private final Map<Future<? extends V>, V> success;
private final Map<Future<? extends V>, Throwable> failed;
private final Map<Future<? extends V>, TimeoutException> timeout;
private final Map<Future<? extends V>, CancellationException> cancel;
private final Map<Future<? extends V>, K> futureMap;
private final Supplier<Map<K, V>> successMap;
private final Supplier<Map<K, Throwable>> failedMap;
private final Supplier<Map<K, TimeoutException>> timeoutMap;
private final Supplier<Map<K, CancellationException>> cancelMap;
TryWaitResult(Map<Future<? extends V>, V> success, Map<Future<? extends V>, Throwable> failed,
Map<Future<? extends V>, TimeoutException> timeout,
Map<Future<? extends V>, CancellationException> cancel,
Map<Future<? extends V>, K> futureMap) {
this.success = success;
this.failed = failed;
this.timeout = timeout;
this.cancel = cancel;
this.futureMap = futureMap; | // Path: core/src/main/java/com/github/phantomthief/util/MoreSuppliers.java
// public static <T> CloseableSupplier<T> lazy(Supplier<T> delegate) {
// return lazy(delegate, true);
// }
// Path: core/src/main/java/com/github/phantomthief/concurrent/TryWaitResult.java
import static com.github.phantomthief.util.MoreSuppliers.lazy;
import static com.google.common.base.MoreObjects.toStringHelper;
import static java.util.stream.Collectors.toMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
package com.github.phantomthief.concurrent;
/**
* @author w.vela
* Created on 2018-06-25.
*/
class TryWaitResult<K, V> {
private final Map<Future<? extends V>, V> success;
private final Map<Future<? extends V>, Throwable> failed;
private final Map<Future<? extends V>, TimeoutException> timeout;
private final Map<Future<? extends V>, CancellationException> cancel;
private final Map<Future<? extends V>, K> futureMap;
private final Supplier<Map<K, V>> successMap;
private final Supplier<Map<K, Throwable>> failedMap;
private final Supplier<Map<K, TimeoutException>> timeoutMap;
private final Supplier<Map<K, CancellationException>> cancelMap;
TryWaitResult(Map<Future<? extends V>, V> success, Map<Future<? extends V>, Throwable> failed,
Map<Future<? extends V>, TimeoutException> timeout,
Map<Future<? extends V>, CancellationException> cancel,
Map<Future<? extends V>, K> futureMap) {
this.success = success;
this.failed = failed;
this.timeout = timeout;
this.cancel = cancel;
this.futureMap = futureMap; | successMap = lazy(() -> transfer(this.success, this.futureMap)); |
PhantomThief/more-lambdas-java | core/src/main/java/com/github/phantomthief/util/NameServiceUtils.java | // Path: core/src/main/java/com/github/phantomthief/tuple/Tuple.java
// public final class Tuple {
//
// private Tuple() {
// throw new UnsupportedOperationException();
// }
//
// public static <A, B> TwoTuple<A, B> tuple(final A a, final B b) {
// return new TwoTuple<>(a, b);
// }
//
// public static <A, B, C> ThreeTuple<A, B, C> tuple(final A a, final B b, final C c) {
// return new ThreeTuple<>(a, b, c);
// }
//
// public static <A, B, C, D> FourTuple<A, B, C, D> tuple(final A a, final B b, final C c,
// final D d) {
// return new FourTuple<>(a, b, c, d);
// }
//
// }
//
// Path: core/src/main/java/com/github/phantomthief/tuple/TwoTuple.java
// public class TwoTuple<A, B> {
//
// public final A first;
//
// public final B second;
//
// /**
// * use {@link Tuple#tuple(Object, Object)} instead
// */
// @Deprecated
// public TwoTuple(final A a, final B b) {
// first = a;
// second = b;
// }
//
// public A getFirst() {
// return first;
// }
//
// public B getSecond() {
// return second;
// }
//
// @Override
// public String toString() {
// return "(" + first + ", " + second + ")";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (first == null ? 0 : first.hashCode());
// result = prime * result + (second == null ? 0 : second.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final TwoTuple<?, ?> other = (TwoTuple<?, ?>) obj;
// if (first == null) {
// if (other.first != null) {
// return false;
// }
// } else if (!first.equals(other.first)) {
// return false;
// }
// if (second == null) {
// return other.second == null;
// } else {
// return second.equals(other.second);
// }
// }
//
// }
| import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.reflect.Reflection.newProxy;
import static org.apache.commons.lang3.reflect.FieldUtils.readDeclaredStaticField;
import static org.apache.commons.lang3.reflect.FieldUtils.writeStaticField;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import com.github.phantomthief.tuple.Tuple;
import com.github.phantomthief.tuple.TwoTuple; | package com.github.phantomthief.util;
/**
* @author w.vela
* Created on 2019-12-25.
*/
public class NameServiceUtils {
private static final byte[] LOCAL_HOST = {127, 0, 0, 1};
private static <T, R> R doInvoke(Object object, String method, T it) throws UnknownHostException {
try {
//noinspection unchecked
return (R) MethodUtils.invokeMethod(object, true, method, it);
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new AssertionError(e);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof UnknownHostException) {
throw (UnknownHostException) cause;
}
throwIfUnchecked(cause);
throw new AssertionError(cause);
}
}
| // Path: core/src/main/java/com/github/phantomthief/tuple/Tuple.java
// public final class Tuple {
//
// private Tuple() {
// throw new UnsupportedOperationException();
// }
//
// public static <A, B> TwoTuple<A, B> tuple(final A a, final B b) {
// return new TwoTuple<>(a, b);
// }
//
// public static <A, B, C> ThreeTuple<A, B, C> tuple(final A a, final B b, final C c) {
// return new ThreeTuple<>(a, b, c);
// }
//
// public static <A, B, C, D> FourTuple<A, B, C, D> tuple(final A a, final B b, final C c,
// final D d) {
// return new FourTuple<>(a, b, c, d);
// }
//
// }
//
// Path: core/src/main/java/com/github/phantomthief/tuple/TwoTuple.java
// public class TwoTuple<A, B> {
//
// public final A first;
//
// public final B second;
//
// /**
// * use {@link Tuple#tuple(Object, Object)} instead
// */
// @Deprecated
// public TwoTuple(final A a, final B b) {
// first = a;
// second = b;
// }
//
// public A getFirst() {
// return first;
// }
//
// public B getSecond() {
// return second;
// }
//
// @Override
// public String toString() {
// return "(" + first + ", " + second + ")";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (first == null ? 0 : first.hashCode());
// result = prime * result + (second == null ? 0 : second.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final TwoTuple<?, ?> other = (TwoTuple<?, ?>) obj;
// if (first == null) {
// if (other.first != null) {
// return false;
// }
// } else if (!first.equals(other.first)) {
// return false;
// }
// if (second == null) {
// return other.second == null;
// } else {
// return second.equals(other.second);
// }
// }
//
// }
// Path: core/src/main/java/com/github/phantomthief/util/NameServiceUtils.java
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.reflect.Reflection.newProxy;
import static org.apache.commons.lang3.reflect.FieldUtils.readDeclaredStaticField;
import static org.apache.commons.lang3.reflect.FieldUtils.writeStaticField;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import com.github.phantomthief.tuple.Tuple;
import com.github.phantomthief.tuple.TwoTuple;
package com.github.phantomthief.util;
/**
* @author w.vela
* Created on 2019-12-25.
*/
public class NameServiceUtils {
private static final byte[] LOCAL_HOST = {127, 0, 0, 1};
private static <T, R> R doInvoke(Object object, String method, T it) throws UnknownHostException {
try {
//noinspection unchecked
return (R) MethodUtils.invokeMethod(object, true, method, it);
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new AssertionError(e);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof UnknownHostException) {
throw (UnknownHostException) cause;
}
throwIfUnchecked(cause);
throw new AssertionError(cause);
}
}
| private static TwoTuple<Object, List<Object>> unwrapList(Object object) { |
PhantomThief/more-lambdas-java | core/src/main/java/com/github/phantomthief/util/NameServiceUtils.java | // Path: core/src/main/java/com/github/phantomthief/tuple/Tuple.java
// public final class Tuple {
//
// private Tuple() {
// throw new UnsupportedOperationException();
// }
//
// public static <A, B> TwoTuple<A, B> tuple(final A a, final B b) {
// return new TwoTuple<>(a, b);
// }
//
// public static <A, B, C> ThreeTuple<A, B, C> tuple(final A a, final B b, final C c) {
// return new ThreeTuple<>(a, b, c);
// }
//
// public static <A, B, C, D> FourTuple<A, B, C, D> tuple(final A a, final B b, final C c,
// final D d) {
// return new FourTuple<>(a, b, c, d);
// }
//
// }
//
// Path: core/src/main/java/com/github/phantomthief/tuple/TwoTuple.java
// public class TwoTuple<A, B> {
//
// public final A first;
//
// public final B second;
//
// /**
// * use {@link Tuple#tuple(Object, Object)} instead
// */
// @Deprecated
// public TwoTuple(final A a, final B b) {
// first = a;
// second = b;
// }
//
// public A getFirst() {
// return first;
// }
//
// public B getSecond() {
// return second;
// }
//
// @Override
// public String toString() {
// return "(" + first + ", " + second + ")";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (first == null ? 0 : first.hashCode());
// result = prime * result + (second == null ? 0 : second.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final TwoTuple<?, ?> other = (TwoTuple<?, ?>) obj;
// if (first == null) {
// if (other.first != null) {
// return false;
// }
// } else if (!first.equals(other.first)) {
// return false;
// }
// if (second == null) {
// return other.second == null;
// } else {
// return second.equals(other.second);
// }
// }
//
// }
| import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.reflect.Reflection.newProxy;
import static org.apache.commons.lang3.reflect.FieldUtils.readDeclaredStaticField;
import static org.apache.commons.lang3.reflect.FieldUtils.writeStaticField;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import com.github.phantomthief.tuple.Tuple;
import com.github.phantomthief.tuple.TwoTuple; | package com.github.phantomthief.util;
/**
* @author w.vela
* Created on 2019-12-25.
*/
public class NameServiceUtils {
private static final byte[] LOCAL_HOST = {127, 0, 0, 1};
private static <T, R> R doInvoke(Object object, String method, T it) throws UnknownHostException {
try {
//noinspection unchecked
return (R) MethodUtils.invokeMethod(object, true, method, it);
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new AssertionError(e);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof UnknownHostException) {
throw (UnknownHostException) cause;
}
throwIfUnchecked(cause);
throw new AssertionError(cause);
}
}
private static TwoTuple<Object, List<Object>> unwrapList(Object object) {
if (object instanceof List) {
List<Object> list = (List<Object>) object;
checkState(!list.isEmpty(), "empty nameService in jdk8");
checkState(list.size() == 1, "multiple nameServices in jdk8"); | // Path: core/src/main/java/com/github/phantomthief/tuple/Tuple.java
// public final class Tuple {
//
// private Tuple() {
// throw new UnsupportedOperationException();
// }
//
// public static <A, B> TwoTuple<A, B> tuple(final A a, final B b) {
// return new TwoTuple<>(a, b);
// }
//
// public static <A, B, C> ThreeTuple<A, B, C> tuple(final A a, final B b, final C c) {
// return new ThreeTuple<>(a, b, c);
// }
//
// public static <A, B, C, D> FourTuple<A, B, C, D> tuple(final A a, final B b, final C c,
// final D d) {
// return new FourTuple<>(a, b, c, d);
// }
//
// }
//
// Path: core/src/main/java/com/github/phantomthief/tuple/TwoTuple.java
// public class TwoTuple<A, B> {
//
// public final A first;
//
// public final B second;
//
// /**
// * use {@link Tuple#tuple(Object, Object)} instead
// */
// @Deprecated
// public TwoTuple(final A a, final B b) {
// first = a;
// second = b;
// }
//
// public A getFirst() {
// return first;
// }
//
// public B getSecond() {
// return second;
// }
//
// @Override
// public String toString() {
// return "(" + first + ", " + second + ")";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (first == null ? 0 : first.hashCode());
// result = prime * result + (second == null ? 0 : second.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final TwoTuple<?, ?> other = (TwoTuple<?, ?>) obj;
// if (first == null) {
// if (other.first != null) {
// return false;
// }
// } else if (!first.equals(other.first)) {
// return false;
// }
// if (second == null) {
// return other.second == null;
// } else {
// return second.equals(other.second);
// }
// }
//
// }
// Path: core/src/main/java/com/github/phantomthief/util/NameServiceUtils.java
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.reflect.Reflection.newProxy;
import static org.apache.commons.lang3.reflect.FieldUtils.readDeclaredStaticField;
import static org.apache.commons.lang3.reflect.FieldUtils.writeStaticField;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import com.github.phantomthief.tuple.Tuple;
import com.github.phantomthief.tuple.TwoTuple;
package com.github.phantomthief.util;
/**
* @author w.vela
* Created on 2019-12-25.
*/
public class NameServiceUtils {
private static final byte[] LOCAL_HOST = {127, 0, 0, 1};
private static <T, R> R doInvoke(Object object, String method, T it) throws UnknownHostException {
try {
//noinspection unchecked
return (R) MethodUtils.invokeMethod(object, true, method, it);
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new AssertionError(e);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof UnknownHostException) {
throw (UnknownHostException) cause;
}
throwIfUnchecked(cause);
throw new AssertionError(cause);
}
}
private static TwoTuple<Object, List<Object>> unwrapList(Object object) {
if (object instanceof List) {
List<Object> list = (List<Object>) object;
checkState(!list.isEmpty(), "empty nameService in jdk8");
checkState(list.size() == 1, "multiple nameServices in jdk8"); | return Tuple.tuple(list.get(0), list); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.