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 |
|---|---|---|---|---|---|---|
marmelo/chili | chili/src/main/java/me/defying/chili/timeout/TimeoutInvoker.java | // Path: chili/src/main/java/me/defying/chili/module/ChiliException.java
// public class ChiliException extends Exception {
//
// /**
// * Creates a new instance of <code>ChiliException</code> without detail
// * message.
// */
// public ChiliException() {
// // empty
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified detail message.
// *
// * @param message the detail message.
// */
// public ChiliException(final String message) {
// super(message);
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified cause.
// *
// * @param cause the cause.
// */
// public ChiliException(final Throwable cause) {
// super(cause);
// }
// }
| import java.util.concurrent.Callable;
import me.defying.chili.module.ChiliException;
import org.aopalliance.intercept.MethodInvocation; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.timeout;
/**
* Invokes the underlying method of a timeout operation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class TimeoutInvoker implements Callable<Object> {
/**
* The method invocation.
*/
private final MethodInvocation invocation;
/**
* Constructs an instance of <code>TimeoutInvoker</code>.
*
* @param invocation the method invocation.
*/
public TimeoutInvoker(final MethodInvocation invocation) {
this.invocation = invocation;
}
@Override
public Object call() throws Exception {
try {
return invocation.proceed();
} catch (final Throwable ex) {
// when the underlying method invokation throws an exception it is
// wrapped and sent to the interceptor in order to existing code get
// the real exception | // Path: chili/src/main/java/me/defying/chili/module/ChiliException.java
// public class ChiliException extends Exception {
//
// /**
// * Creates a new instance of <code>ChiliException</code> without detail
// * message.
// */
// public ChiliException() {
// // empty
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified detail message.
// *
// * @param message the detail message.
// */
// public ChiliException(final String message) {
// super(message);
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified cause.
// *
// * @param cause the cause.
// */
// public ChiliException(final Throwable cause) {
// super(cause);
// }
// }
// Path: chili/src/main/java/me/defying/chili/timeout/TimeoutInvoker.java
import java.util.concurrent.Callable;
import me.defying.chili.module.ChiliException;
import org.aopalliance.intercept.MethodInvocation;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.timeout;
/**
* Invokes the underlying method of a timeout operation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class TimeoutInvoker implements Callable<Object> {
/**
* The method invocation.
*/
private final MethodInvocation invocation;
/**
* Constructs an instance of <code>TimeoutInvoker</code>.
*
* @param invocation the method invocation.
*/
public TimeoutInvoker(final MethodInvocation invocation) {
this.invocation = invocation;
}
@Override
public Object call() throws Exception {
try {
return invocation.proceed();
} catch (final Throwable ex) {
// when the underlying method invokation throws an exception it is
// wrapped and sent to the interceptor in order to existing code get
// the real exception | throw new ChiliException(ex); |
marmelo/chili | chili/src/main/java/me/defying/chili/tostring/ToStringInterceptor.java | // Path: chili/src/main/java/me/defying/chili/util/InvocationUtils.java
// public final class InvocationUtils {
//
// /**
// * Prevent instantiation of utility class.
// */
// private InvocationUtils() {
// // emtpy
// }
//
// /**
// * Returns the annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the annotation for the specified annotation type
// */
// public static <T extends Annotation> T getAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getMethod().getAnnotation(annotation);
// }
//
// /**
// * Returns the class annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the class annotation for the specified annotation type
// */
// public static <T extends Annotation> T getClassAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getThis().getClass().getSuperclass().getAnnotation(annotation);
// }
//
// /**
// * Returns the class being invoked.
// *
// * @param invocation the method invocation
// * @return the class being invoked
// */
// public static Class getClass(final MethodInvocation invocation) {
// return invocation.getThis().getClass().getSuperclass();
// }
//
// /**
// * Returns the method being invoked.
// *
// * @param invocation the method invocation
// * @return the method being invoked
// */
// public static Method getMethod(final MethodInvocation invocation) {
// return invocation.getMethod();
// }
//
// /**
// * Returns the arguments of the method invocation.
// *
// * @param invocation the method invocation
// * @return the arguments of the method invocation
// */
// public static List<Object> getArguments(final MethodInvocation invocation) {
// // get method arguments
// final List<Object> arguments = new ArrayList(Arrays.asList(invocation.getArguments()));
//
// // if the method contains a varargs then the last parameter must be flattened
// if (invocation.getMethod().isVarArgs() && !arguments.isEmpty()) {
// final int last = arguments.size() - 1;
// final Object varargs = arguments.remove(last);
// arguments.addAll(convert(varargs));
// }
//
// return arguments;
// }
//
// /**
// * Converts an {@code Object} array into a {@code List}.
// *
// * @param array the array of objects
// * @return the list of objects
// */
// private static List<Object> convert(final Object array) {
// final List<Object> result = new ArrayList<>();
// final int length = Array.getLength(array);
//
// for (int i = 0; i < length; ++i) {
// result.add(Array.get(array, i));
// }
//
// return result;
// }
// }
| import org.aopalliance.intercept.MethodInvocation;
import com.google.common.base.MoreObjects;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import me.defying.chili.ToString;
import me.defying.chili.util.InvocationUtils;
import org.aopalliance.intercept.MethodInterceptor; | /*
* The MIT License (MIT)
* Copyright (c) 2018 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.tostring;
/**
* Guice interceptor for {@code ToString} annotation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class ToStringInterceptor implements MethodInterceptor {
/**
* Constructs an instance of <code>ToStringInterceptor</code>.
*/
public ToStringInterceptor() {
// empty
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable { | // Path: chili/src/main/java/me/defying/chili/util/InvocationUtils.java
// public final class InvocationUtils {
//
// /**
// * Prevent instantiation of utility class.
// */
// private InvocationUtils() {
// // emtpy
// }
//
// /**
// * Returns the annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the annotation for the specified annotation type
// */
// public static <T extends Annotation> T getAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getMethod().getAnnotation(annotation);
// }
//
// /**
// * Returns the class annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the class annotation for the specified annotation type
// */
// public static <T extends Annotation> T getClassAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getThis().getClass().getSuperclass().getAnnotation(annotation);
// }
//
// /**
// * Returns the class being invoked.
// *
// * @param invocation the method invocation
// * @return the class being invoked
// */
// public static Class getClass(final MethodInvocation invocation) {
// return invocation.getThis().getClass().getSuperclass();
// }
//
// /**
// * Returns the method being invoked.
// *
// * @param invocation the method invocation
// * @return the method being invoked
// */
// public static Method getMethod(final MethodInvocation invocation) {
// return invocation.getMethod();
// }
//
// /**
// * Returns the arguments of the method invocation.
// *
// * @param invocation the method invocation
// * @return the arguments of the method invocation
// */
// public static List<Object> getArguments(final MethodInvocation invocation) {
// // get method arguments
// final List<Object> arguments = new ArrayList(Arrays.asList(invocation.getArguments()));
//
// // if the method contains a varargs then the last parameter must be flattened
// if (invocation.getMethod().isVarArgs() && !arguments.isEmpty()) {
// final int last = arguments.size() - 1;
// final Object varargs = arguments.remove(last);
// arguments.addAll(convert(varargs));
// }
//
// return arguments;
// }
//
// /**
// * Converts an {@code Object} array into a {@code List}.
// *
// * @param array the array of objects
// * @return the list of objects
// */
// private static List<Object> convert(final Object array) {
// final List<Object> result = new ArrayList<>();
// final int length = Array.getLength(array);
//
// for (int i = 0; i < length; ++i) {
// result.add(Array.get(array, i));
// }
//
// return result;
// }
// }
// Path: chili/src/main/java/me/defying/chili/tostring/ToStringInterceptor.java
import org.aopalliance.intercept.MethodInvocation;
import com.google.common.base.MoreObjects;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import me.defying.chili.ToString;
import me.defying.chili.util.InvocationUtils;
import org.aopalliance.intercept.MethodInterceptor;
/*
* The MIT License (MIT)
* Copyright (c) 2018 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.tostring;
/**
* Guice interceptor for {@code ToString} annotation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class ToStringInterceptor implements MethodInterceptor {
/**
* Constructs an instance of <code>ToStringInterceptor</code>.
*/
public ToStringInterceptor() {
// empty
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable { | final ToString annotation = InvocationUtils.getClassAnnotation(invocation, ToString.class); |
marmelo/chili | chili/src/test/java/me/defying/chili/LogTest.java | // Path: chili/src/test/java/me/defying/chili/log/LogTestService.java
// public class LogTestService {
//
// @Log
// public void simple() {
// // empty
// }
//
// @Log(level = LogLevel.TRACE)
// public void levelTrace() {
// // empty
// }
//
// @Log(level = LogLevel.DEBUG)
// public void levelDebug() {
// // empty
// }
//
// @Log(level = LogLevel.INFO)
// public void levelInfo() {
// // empty
// }
//
// @Log(level = LogLevel.WARNING)
// public void levelWarning() {
// // empty
// }
//
// @Log(level = LogLevel.ERROR)
// public void levelError() {
// // empty
// }
//
// @Log
// public void hasArgument(final int x) {
// // empty
// }
//
// @Log
// public void hasArguments(final int x, final int y) {
// // empty
// }
//
// @Log
// public void hasVarArgs(final int... x) {
// // empty
// }
//
// @Log
// public int hasReturn() {
// return 1;
// }
//
// @Log
// public int hasArgumentAndReturn(final int x) {
// return x;
// }
//
// @Log
// public void exception() throws Exception {
// throw new IOException();
// }
//
// @Log(onlyTypes = true)
// public int onlyTypes(final long primitive, final String string,
// final List<String> list, final Double[] array, final String nulls) {
// return 1;
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
| import java.io.IOException;
import java.util.Arrays;
import com.google.inject.Inject;
import org.junit.Test;
import me.defying.chili.log.LogTestService;
import me.defying.chili.util.ChiliTest; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for {@code Log} annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class LogTest extends ChiliTest {
@Inject | // Path: chili/src/test/java/me/defying/chili/log/LogTestService.java
// public class LogTestService {
//
// @Log
// public void simple() {
// // empty
// }
//
// @Log(level = LogLevel.TRACE)
// public void levelTrace() {
// // empty
// }
//
// @Log(level = LogLevel.DEBUG)
// public void levelDebug() {
// // empty
// }
//
// @Log(level = LogLevel.INFO)
// public void levelInfo() {
// // empty
// }
//
// @Log(level = LogLevel.WARNING)
// public void levelWarning() {
// // empty
// }
//
// @Log(level = LogLevel.ERROR)
// public void levelError() {
// // empty
// }
//
// @Log
// public void hasArgument(final int x) {
// // empty
// }
//
// @Log
// public void hasArguments(final int x, final int y) {
// // empty
// }
//
// @Log
// public void hasVarArgs(final int... x) {
// // empty
// }
//
// @Log
// public int hasReturn() {
// return 1;
// }
//
// @Log
// public int hasArgumentAndReturn(final int x) {
// return x;
// }
//
// @Log
// public void exception() throws Exception {
// throw new IOException();
// }
//
// @Log(onlyTypes = true)
// public int onlyTypes(final long primitive, final String string,
// final List<String> list, final Double[] array, final String nulls) {
// return 1;
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
// Path: chili/src/test/java/me/defying/chili/LogTest.java
import java.io.IOException;
import java.util.Arrays;
import com.google.inject.Inject;
import org.junit.Test;
import me.defying.chili.log.LogTestService;
import me.defying.chili.util.ChiliTest;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for {@code Log} annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class LogTest extends ChiliTest {
@Inject | private LogTestService service; |
marmelo/chili | chili/src/test/java/me/defying/chili/MixTest.java | // Path: chili/src/test/java/me/defying/chili/memoize/Wrap.java
// public class Wrap {
// private final Object value;
//
// public Wrap(final Object value) {
// this.value = value;
// }
//
// public Object getValue() {
// return value;
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/mix/MixTestService.java
// public class MixTestService {
//
// @Log
// @Memoize
// @Timeout
// public Wrap simple(final String x) {
// return new Wrap(x);
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
| import com.google.inject.Inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import org.junit.Test;
import me.defying.chili.memoize.Wrap;
import me.defying.chili.mix.MixTestService;
import me.defying.chili.util.ChiliTest; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for multiple annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MixTest extends ChiliTest {
@Inject | // Path: chili/src/test/java/me/defying/chili/memoize/Wrap.java
// public class Wrap {
// private final Object value;
//
// public Wrap(final Object value) {
// this.value = value;
// }
//
// public Object getValue() {
// return value;
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/mix/MixTestService.java
// public class MixTestService {
//
// @Log
// @Memoize
// @Timeout
// public Wrap simple(final String x) {
// return new Wrap(x);
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
// Path: chili/src/test/java/me/defying/chili/MixTest.java
import com.google.inject.Inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import org.junit.Test;
import me.defying.chili.memoize.Wrap;
import me.defying.chili.mix.MixTestService;
import me.defying.chili.util.ChiliTest;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for multiple annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MixTest extends ChiliTest {
@Inject | private MixTestService service; |
marmelo/chili | chili/src/test/java/me/defying/chili/MixTest.java | // Path: chili/src/test/java/me/defying/chili/memoize/Wrap.java
// public class Wrap {
// private final Object value;
//
// public Wrap(final Object value) {
// this.value = value;
// }
//
// public Object getValue() {
// return value;
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/mix/MixTestService.java
// public class MixTestService {
//
// @Log
// @Memoize
// @Timeout
// public Wrap simple(final String x) {
// return new Wrap(x);
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
| import com.google.inject.Inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import org.junit.Test;
import me.defying.chili.memoize.Wrap;
import me.defying.chili.mix.MixTestService;
import me.defying.chili.util.ChiliTest; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for multiple annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MixTest extends ChiliTest {
@Inject
private MixTestService service;
/**
* Test multiple annotations.
*/
@Test
public void simpleTest() {
// different arguments yield different results | // Path: chili/src/test/java/me/defying/chili/memoize/Wrap.java
// public class Wrap {
// private final Object value;
//
// public Wrap(final Object value) {
// this.value = value;
// }
//
// public Object getValue() {
// return value;
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/mix/MixTestService.java
// public class MixTestService {
//
// @Log
// @Memoize
// @Timeout
// public Wrap simple(final String x) {
// return new Wrap(x);
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
// Path: chili/src/test/java/me/defying/chili/MixTest.java
import com.google.inject.Inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import org.junit.Test;
import me.defying.chili.memoize.Wrap;
import me.defying.chili.mix.MixTestService;
import me.defying.chili.util.ChiliTest;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for multiple annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MixTest extends ChiliTest {
@Inject
private MixTestService service;
/**
* Test multiple annotations.
*/
@Test
public void simpleTest() {
// different arguments yield different results | final Wrap a = service.simple("a"); |
marmelo/chili | chili/src/main/java/me/defying/chili/memoize/MemoizeInvoker.java | // Path: chili/src/main/java/me/defying/chili/module/ChiliException.java
// public class ChiliException extends Exception {
//
// /**
// * Creates a new instance of <code>ChiliException</code> without detail
// * message.
// */
// public ChiliException() {
// // empty
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified detail message.
// *
// * @param message the detail message.
// */
// public ChiliException(final String message) {
// super(message);
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified cause.
// *
// * @param cause the cause.
// */
// public ChiliException(final Throwable cause) {
// super(cause);
// }
// }
| import java.util.concurrent.Callable;
import com.google.common.base.Optional;
import me.defying.chili.module.ChiliException;
import org.aopalliance.intercept.MethodInvocation; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.memoize;
/**
* Invokes the underlying method of a memoize operation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MemoizeInvoker implements Callable<Optional<Object>> {
/**
* The method invocation.
*/
private final MethodInvocation invocation;
/**
* Constructs an instance of <code>MemoizeInvoker</code>.
*
* @param invocation the method invocation.
*/
public MemoizeInvoker(final MethodInvocation invocation) {
this.invocation = invocation;
}
@Override
public Optional<Object> call() throws Exception {
Object result;
try {
result = invocation.proceed();
} catch (Throwable ex) {
// when the underlying method invokation throws an exception it is
// wrapped and sent to the interceptor in order to existing code get
// the real exception | // Path: chili/src/main/java/me/defying/chili/module/ChiliException.java
// public class ChiliException extends Exception {
//
// /**
// * Creates a new instance of <code>ChiliException</code> without detail
// * message.
// */
// public ChiliException() {
// // empty
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified detail message.
// *
// * @param message the detail message.
// */
// public ChiliException(final String message) {
// super(message);
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified cause.
// *
// * @param cause the cause.
// */
// public ChiliException(final Throwable cause) {
// super(cause);
// }
// }
// Path: chili/src/main/java/me/defying/chili/memoize/MemoizeInvoker.java
import java.util.concurrent.Callable;
import com.google.common.base.Optional;
import me.defying.chili.module.ChiliException;
import org.aopalliance.intercept.MethodInvocation;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.memoize;
/**
* Invokes the underlying method of a memoize operation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MemoizeInvoker implements Callable<Optional<Object>> {
/**
* The method invocation.
*/
private final MethodInvocation invocation;
/**
* Constructs an instance of <code>MemoizeInvoker</code>.
*
* @param invocation the method invocation.
*/
public MemoizeInvoker(final MethodInvocation invocation) {
this.invocation = invocation;
}
@Override
public Optional<Object> call() throws Exception {
Object result;
try {
result = invocation.proceed();
} catch (Throwable ex) {
// when the underlying method invokation throws an exception it is
// wrapped and sent to the interceptor in order to existing code get
// the real exception | throw new ChiliException(ex); |
wada811/Android-DialogFragments | sample/src/main/java/com/wada811/android/dialogfragments/sample/datepickerdialogfragment/DatePickerDialogFragmentExamplesActivity.java | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
| import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.DatePicker;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.R; | /*
* Copyright 2014 wada811
*
* 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.wada811.android.dialogfragments.sample.datepickerdialogfragment;
public class DatePickerDialogFragmentExamplesActivity extends ActionBarActivity
implements DialogFragmentCallbackProvider {
final DatePickerDialogFragmentExamplesActivity self = this;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_date_picker_dialog_fragment_examples_in_activity : R.string.title_activity_date_picker_dialog_fragment_examples_in_fragment);
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, DatePickerDialogFragmentExamplesFragment.newInstance(isInActivity))
.commit();
}
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){ | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
// Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/datepickerdialogfragment/DatePickerDialogFragmentExamplesActivity.java
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.DatePicker;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.R;
/*
* Copyright 2014 wada811
*
* 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.wada811.android.dialogfragments.sample.datepickerdialogfragment;
public class DatePickerDialogFragmentExamplesActivity extends ActionBarActivity
implements DialogFragmentCallbackProvider {
final DatePickerDialogFragmentExamplesActivity self = this;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_date_picker_dialog_fragment_examples_in_activity : R.string.title_activity_date_picker_dialog_fragment_examples_in_fragment);
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, DatePickerDialogFragmentExamplesFragment.newInstance(isInActivity))
.commit();
}
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){ | return new SimpleDialogFragmentCallback() { |
wada811/Android-DialogFragments | sample/src/main/java/com/wada811/android/dialogfragments/sample/datepickerdialogfragment/DatePickerDialogFragmentExamplesActivity.java | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
| import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.DatePicker;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.R; | /*
* Copyright 2014 wada811
*
* 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.wada811.android.dialogfragments.sample.datepickerdialogfragment;
public class DatePickerDialogFragmentExamplesActivity extends ActionBarActivity
implements DialogFragmentCallbackProvider {
final DatePickerDialogFragmentExamplesActivity self = this;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_date_picker_dialog_fragment_examples_in_activity : R.string.title_activity_date_picker_dialog_fragment_examples_in_fragment);
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, DatePickerDialogFragmentExamplesFragment.newInstance(isInActivity))
.commit();
}
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){
return new SimpleDialogFragmentCallback() {
@Override | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
// Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/datepickerdialogfragment/DatePickerDialogFragmentExamplesActivity.java
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.DatePicker;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.R;
/*
* Copyright 2014 wada811
*
* 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.wada811.android.dialogfragments.sample.datepickerdialogfragment;
public class DatePickerDialogFragmentExamplesActivity extends ActionBarActivity
implements DialogFragmentCallbackProvider {
final DatePickerDialogFragmentExamplesActivity self = this;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_date_picker_dialog_fragment_examples_in_activity : R.string.title_activity_date_picker_dialog_fragment_examples_in_fragment);
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, DatePickerDialogFragmentExamplesFragment.newInstance(isInActivity))
.commit();
}
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){
return new SimpleDialogFragmentCallback() {
@Override | public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){ |
wada811/Android-DialogFragments | sample/src/main/java/com/wada811/android/dialogfragments/sample/numberpickerdialogfragment/examples/traditional/BasicNumberPickerDialogExample.java | // Path: library/src/main/java/com/wada811/android/dialogfragments/traditional/NumberPickerDialogFragment.java
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public class NumberPickerDialogFragment extends AlertDialogFragment
// implements DialogFragmentInterface, NumberPickerDialogInterface, OnNumberSetListener {
//
// private NumberPickerDialog numberPickerDialog;
//
// public static NumberPickerDialogFragment newInstance(DialogFragmentCallbackProvider provider, int value, int minValue, int maxValue){
// return newInstanceInternal(provider, VALUE_NULL, value, minValue, maxValue);
// }
//
// public static NumberPickerDialogFragment newInstance(DialogFragmentCallbackProvider provider, int theme, int value, int minValue, int maxValue){
// return newInstanceInternal(provider, theme, value, minValue, maxValue);
// }
//
// public static NumberPickerDialogFragment newInstanceInternal(DialogFragmentCallbackProvider provider, int theme, int value, int minValue, int maxValue){
// assertListenerBindable(provider);
// NumberPickerDialogFragment fragment = new NumberPickerDialogFragment();
// Bundle args = new Bundle();
// args.putInt(THEME, theme);
// args.putInt(VALUE, value);
// args.putInt(MIN_VALUE, minValue);
// args.putInt(MAX_VALUE, maxValue);
// fragment.setArguments(args);
// return fragment;
//
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState){
// super.onCreate(savedInstanceState);
// Log.w(TAG, "onCreate");
// Log.w(TAG, "onCreate:savedInstanceState: " + savedInstanceState);
// }
//
// @NonNull
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState){
// final Bundle args = getArguments();
// final int theme = args.getInt(THEME);
// final int value = args.getInt(VALUE);
// final int minValue = args.getInt(MIN_VALUE);
// final int maxValue = args.getInt(MAX_VALUE);
//
// if(theme == VALUE_NULL){
// numberPickerDialog = new NumberPickerDialog(getActivity(), this, value, minValue, maxValue);
// }else{
// numberPickerDialog = new NumberPickerDialog(getActivity(), theme, this, value, minValue, maxValue);
// }
// if(iconId != VALUE_NULL){
// setIcon(iconId);
// }
// if(title != null){
// setTitle(title);
// }
// if(titleId != VALUE_NULL){
// setTitle(titleId);
// }
// return numberPickerDialog;
// }
//
// @Override
// public void onSaveInstanceState(Bundle outState){
// super.onSaveInstanceState(outState);
// Log.w(TAG, "onSaveInstanceState");
// }
//
// @Override
// public void onDestroyView(){
// super.onDestroyView();
// Log.w(TAG, "onDestroyView");
// numberPickerDialog = null;
// }
//
// @Override
// public Dialog getDialog(){
// return numberPickerDialog;
// }
//
// @Override
// public NumberPicker getNumberPicker(){
// return numberPickerDialog.getNumberPicker();
// }
//
// @Override
// public void updateNumber(int value){
// if(numberPickerDialog != null){
// numberPickerDialog.updateNumber(value);
// }
//
// }
//
// @Override
// public void onNumberSet(NumberPicker numberPicker, int value){
// DialogFragmentCallback listener = getDialogFragmentCallback();
// if(listener != null){
// listener.onNumberSet(self, numberPicker, value);
// }
// }
// }
| import android.support.v4.app.FragmentManager;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.sample.Example;
import com.wada811.android.dialogfragments.sample.R;
import com.wada811.android.dialogfragments.traditional.NumberPickerDialogFragment; | /*
* Copyright 2014 wada811
*
* 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.wada811.android.dialogfragments.sample.numberpickerdialogfragment.examples.traditional;
public class BasicNumberPickerDialogExample extends Example {
public BasicNumberPickerDialogExample(){
super(BasicNumberPickerDialogExample.class.getSimpleName() + "(Traditional)");
}
@Override
public void showDialog(DialogFragmentCallbackProvider provider, FragmentManager fragmentManager){
int value = 1;
int min = 1;
int max = 10; | // Path: library/src/main/java/com/wada811/android/dialogfragments/traditional/NumberPickerDialogFragment.java
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public class NumberPickerDialogFragment extends AlertDialogFragment
// implements DialogFragmentInterface, NumberPickerDialogInterface, OnNumberSetListener {
//
// private NumberPickerDialog numberPickerDialog;
//
// public static NumberPickerDialogFragment newInstance(DialogFragmentCallbackProvider provider, int value, int minValue, int maxValue){
// return newInstanceInternal(provider, VALUE_NULL, value, minValue, maxValue);
// }
//
// public static NumberPickerDialogFragment newInstance(DialogFragmentCallbackProvider provider, int theme, int value, int minValue, int maxValue){
// return newInstanceInternal(provider, theme, value, minValue, maxValue);
// }
//
// public static NumberPickerDialogFragment newInstanceInternal(DialogFragmentCallbackProvider provider, int theme, int value, int minValue, int maxValue){
// assertListenerBindable(provider);
// NumberPickerDialogFragment fragment = new NumberPickerDialogFragment();
// Bundle args = new Bundle();
// args.putInt(THEME, theme);
// args.putInt(VALUE, value);
// args.putInt(MIN_VALUE, minValue);
// args.putInt(MAX_VALUE, maxValue);
// fragment.setArguments(args);
// return fragment;
//
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState){
// super.onCreate(savedInstanceState);
// Log.w(TAG, "onCreate");
// Log.w(TAG, "onCreate:savedInstanceState: " + savedInstanceState);
// }
//
// @NonNull
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState){
// final Bundle args = getArguments();
// final int theme = args.getInt(THEME);
// final int value = args.getInt(VALUE);
// final int minValue = args.getInt(MIN_VALUE);
// final int maxValue = args.getInt(MAX_VALUE);
//
// if(theme == VALUE_NULL){
// numberPickerDialog = new NumberPickerDialog(getActivity(), this, value, minValue, maxValue);
// }else{
// numberPickerDialog = new NumberPickerDialog(getActivity(), theme, this, value, minValue, maxValue);
// }
// if(iconId != VALUE_NULL){
// setIcon(iconId);
// }
// if(title != null){
// setTitle(title);
// }
// if(titleId != VALUE_NULL){
// setTitle(titleId);
// }
// return numberPickerDialog;
// }
//
// @Override
// public void onSaveInstanceState(Bundle outState){
// super.onSaveInstanceState(outState);
// Log.w(TAG, "onSaveInstanceState");
// }
//
// @Override
// public void onDestroyView(){
// super.onDestroyView();
// Log.w(TAG, "onDestroyView");
// numberPickerDialog = null;
// }
//
// @Override
// public Dialog getDialog(){
// return numberPickerDialog;
// }
//
// @Override
// public NumberPicker getNumberPicker(){
// return numberPickerDialog.getNumberPicker();
// }
//
// @Override
// public void updateNumber(int value){
// if(numberPickerDialog != null){
// numberPickerDialog.updateNumber(value);
// }
//
// }
//
// @Override
// public void onNumberSet(NumberPicker numberPicker, int value){
// DialogFragmentCallback listener = getDialogFragmentCallback();
// if(listener != null){
// listener.onNumberSet(self, numberPicker, value);
// }
// }
// }
// Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/numberpickerdialogfragment/examples/traditional/BasicNumberPickerDialogExample.java
import android.support.v4.app.FragmentManager;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.sample.Example;
import com.wada811.android.dialogfragments.sample.R;
import com.wada811.android.dialogfragments.traditional.NumberPickerDialogFragment;
/*
* Copyright 2014 wada811
*
* 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.wada811.android.dialogfragments.sample.numberpickerdialogfragment.examples.traditional;
public class BasicNumberPickerDialogExample extends Example {
public BasicNumberPickerDialogExample(){
super(BasicNumberPickerDialogExample.class.getSimpleName() + "(Traditional)");
}
@Override
public void showDialog(DialogFragmentCallbackProvider provider, FragmentManager fragmentManager){
int value = 1;
int min = 1;
int max = 10; | NumberPickerDialogFragment dialogFragment = NumberPickerDialogFragment.newInstance(provider, value, min, max); |
wada811/Android-DialogFragments | sample/src/main/java/com/wada811/android/dialogfragments/sample/numberpickerdialogfragment/NumberPickerDialogFragmentExamplesActivity.java | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
| import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.NumberPicker;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.R; | /*
* Copyright 2014 wada811
*
* 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.wada811.android.dialogfragments.sample.numberpickerdialogfragment;
public class NumberPickerDialogFragmentExamplesActivity extends ActionBarActivity
implements DialogFragmentCallbackProvider {
final NumberPickerDialogFragmentExamplesActivity self = this;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_number_picker_dialog_fragment_examples_in_activity : R.string.title_activity_number_picker_dialog_fragment_examples_in_fragment);
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, NumberPickerDialogFragmentExamplesFragment.newInstance(isInActivity))
.commit();
}
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){ | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
// Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/numberpickerdialogfragment/NumberPickerDialogFragmentExamplesActivity.java
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.NumberPicker;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.R;
/*
* Copyright 2014 wada811
*
* 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.wada811.android.dialogfragments.sample.numberpickerdialogfragment;
public class NumberPickerDialogFragmentExamplesActivity extends ActionBarActivity
implements DialogFragmentCallbackProvider {
final NumberPickerDialogFragmentExamplesActivity self = this;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_number_picker_dialog_fragment_examples_in_activity : R.string.title_activity_number_picker_dialog_fragment_examples_in_fragment);
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, NumberPickerDialogFragmentExamplesFragment.newInstance(isInActivity))
.commit();
}
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){ | return new SimpleDialogFragmentCallback() { |
wada811/Android-DialogFragments | sample/src/main/java/com/wada811/android/dialogfragments/sample/numberpickerdialogfragment/NumberPickerDialogFragmentExamplesActivity.java | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
| import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.NumberPicker;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.R; | /*
* Copyright 2014 wada811
*
* 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.wada811.android.dialogfragments.sample.numberpickerdialogfragment;
public class NumberPickerDialogFragmentExamplesActivity extends ActionBarActivity
implements DialogFragmentCallbackProvider {
final NumberPickerDialogFragmentExamplesActivity self = this;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_number_picker_dialog_fragment_examples_in_activity : R.string.title_activity_number_picker_dialog_fragment_examples_in_fragment);
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, NumberPickerDialogFragmentExamplesFragment.newInstance(isInActivity))
.commit();
}
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){
return new SimpleDialogFragmentCallback() {
@Override | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
// Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/numberpickerdialogfragment/NumberPickerDialogFragmentExamplesActivity.java
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.NumberPicker;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.R;
/*
* Copyright 2014 wada811
*
* 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.wada811.android.dialogfragments.sample.numberpickerdialogfragment;
public class NumberPickerDialogFragmentExamplesActivity extends ActionBarActivity
implements DialogFragmentCallbackProvider {
final NumberPickerDialogFragmentExamplesActivity self = this;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_number_picker_dialog_fragment_examples_in_activity : R.string.title_activity_number_picker_dialog_fragment_examples_in_fragment);
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, NumberPickerDialogFragmentExamplesFragment.newInstance(isInActivity))
.commit();
}
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){
return new SimpleDialogFragmentCallback() {
@Override | public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){ |
wada811/Android-DialogFragments | sample/src/main/java/com/wada811/android/dialogfragments/sample/stringpickerdialogfragment/StringPickerDialogFragmentExamplesFragment.java | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
| import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.Example;
import com.wada811.android.dialogfragments.view.StringPicker; | return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
initExample();
initListFragment();
}
private void initExample(){
items = new ArrayList<>();
items.add(new com.wada811.android.dialogfragments.sample.stringpickerdialogfragment.examples.traditional.BasicStringPickerDialogExample());
items.add(new com.wada811.android.dialogfragments.sample.stringpickerdialogfragment.examples.material.BasicStringPickerDialogExample());
}
private void initListFragment(){
setListAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, items));
}
@Override
public void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
Example item = items.get(position);
boolean isInActivity = getArguments().getBoolean(Const.KEY_IS_IN_ACTIVITY);
item.showDialog(this, isInActivity ? getFragmentManager() : getChildFragmentManager());
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){ | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
// Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/stringpickerdialogfragment/StringPickerDialogFragmentExamplesFragment.java
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.Example;
import com.wada811.android.dialogfragments.view.StringPicker;
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
initExample();
initListFragment();
}
private void initExample(){
items = new ArrayList<>();
items.add(new com.wada811.android.dialogfragments.sample.stringpickerdialogfragment.examples.traditional.BasicStringPickerDialogExample());
items.add(new com.wada811.android.dialogfragments.sample.stringpickerdialogfragment.examples.material.BasicStringPickerDialogExample());
}
private void initListFragment(){
setListAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, items));
}
@Override
public void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
Example item = items.get(position);
boolean isInActivity = getArguments().getBoolean(Const.KEY_IS_IN_ACTIVITY);
item.showDialog(this, isInActivity ? getFragmentManager() : getChildFragmentManager());
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){ | return new SimpleDialogFragmentCallback() { |
wada811/Android-DialogFragments | sample/src/main/java/com/wada811/android/dialogfragments/sample/stringpickerdialogfragment/StringPickerDialogFragmentExamplesFragment.java | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
| import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.Example;
import com.wada811.android.dialogfragments.view.StringPicker; |
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
initExample();
initListFragment();
}
private void initExample(){
items = new ArrayList<>();
items.add(new com.wada811.android.dialogfragments.sample.stringpickerdialogfragment.examples.traditional.BasicStringPickerDialogExample());
items.add(new com.wada811.android.dialogfragments.sample.stringpickerdialogfragment.examples.material.BasicStringPickerDialogExample());
}
private void initListFragment(){
setListAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, items));
}
@Override
public void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
Example item = items.get(position);
boolean isInActivity = getArguments().getBoolean(Const.KEY_IS_IN_ACTIVITY);
item.showDialog(this, isInActivity ? getFragmentManager() : getChildFragmentManager());
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){
return new SimpleDialogFragmentCallback() {
@Override | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
// Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/stringpickerdialogfragment/StringPickerDialogFragmentExamplesFragment.java
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.Example;
import com.wada811.android.dialogfragments.view.StringPicker;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
initExample();
initListFragment();
}
private void initExample(){
items = new ArrayList<>();
items.add(new com.wada811.android.dialogfragments.sample.stringpickerdialogfragment.examples.traditional.BasicStringPickerDialogExample());
items.add(new com.wada811.android.dialogfragments.sample.stringpickerdialogfragment.examples.material.BasicStringPickerDialogExample());
}
private void initListFragment(){
setListAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, items));
}
@Override
public void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
Example item = items.get(position);
boolean isInActivity = getArguments().getBoolean(Const.KEY_IS_IN_ACTIVITY);
item.showDialog(this, isInActivity ? getFragmentManager() : getChildFragmentManager());
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){
return new SimpleDialogFragmentCallback() {
@Override | public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){ |
wada811/Android-DialogFragments | library/src/main/java/com/wada811/android/dialogfragments/traditional/NumberPickerDialogFragment.java | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
| import android.annotation.TargetApi;
import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.NumberPicker;
import com.wada811.android.dialogfragments.traditional.NumberPickerDialogInterface.OnNumberSetListener;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface; | /*
* Copyright 2014 wada811
*
* 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.wada811.android.dialogfragments.traditional;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class NumberPickerDialogFragment extends AlertDialogFragment | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
// Path: library/src/main/java/com/wada811/android/dialogfragments/traditional/NumberPickerDialogFragment.java
import android.annotation.TargetApi;
import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.NumberPicker;
import com.wada811.android.dialogfragments.traditional.NumberPickerDialogInterface.OnNumberSetListener;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
/*
* Copyright 2014 wada811
*
* 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.wada811.android.dialogfragments.traditional;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class NumberPickerDialogFragment extends AlertDialogFragment | implements DialogFragmentInterface, NumberPickerDialogInterface, OnNumberSetListener { |
wada811/Android-DialogFragments | sample/src/main/java/com/wada811/android/dialogfragments/sample/datepickerdialogfragment/DatePickerDialogFragmentExamplesFragment.java | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
| import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.Example; | return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
initExample();
initListFragment();
}
private void initExample(){
items = new ArrayList<>();
items.add(new com.wada811.android.dialogfragments.sample.datepickerdialogfragment.examples.traditional.BasicDatePickerDialogExample());
items.add(new com.wada811.android.dialogfragments.sample.datepickerdialogfragment.examples.material.BasicDatePickerDialogExample());
}
private void initListFragment(){
setListAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, items));
}
@Override
public void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
Example item = items.get(position);
boolean isInActivity = getArguments().getBoolean(Const.KEY_IS_IN_ACTIVITY);
item.showDialog(this, isInActivity ? getFragmentManager() : getChildFragmentManager());
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){ | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
// Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/datepickerdialogfragment/DatePickerDialogFragmentExamplesFragment.java
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.Example;
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
initExample();
initListFragment();
}
private void initExample(){
items = new ArrayList<>();
items.add(new com.wada811.android.dialogfragments.sample.datepickerdialogfragment.examples.traditional.BasicDatePickerDialogExample());
items.add(new com.wada811.android.dialogfragments.sample.datepickerdialogfragment.examples.material.BasicDatePickerDialogExample());
}
private void initListFragment(){
setListAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, items));
}
@Override
public void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
Example item = items.get(position);
boolean isInActivity = getArguments().getBoolean(Const.KEY_IS_IN_ACTIVITY);
item.showDialog(this, isInActivity ? getFragmentManager() : getChildFragmentManager());
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){ | return new SimpleDialogFragmentCallback() { |
wada811/Android-DialogFragments | sample/src/main/java/com/wada811/android/dialogfragments/sample/datepickerdialogfragment/DatePickerDialogFragmentExamplesFragment.java | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
| import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.Example; |
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
initExample();
initListFragment();
}
private void initExample(){
items = new ArrayList<>();
items.add(new com.wada811.android.dialogfragments.sample.datepickerdialogfragment.examples.traditional.BasicDatePickerDialogExample());
items.add(new com.wada811.android.dialogfragments.sample.datepickerdialogfragment.examples.material.BasicDatePickerDialogExample());
}
private void initListFragment(){
setListAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, items));
}
@Override
public void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
Example item = items.get(position);
boolean isInActivity = getArguments().getBoolean(Const.KEY_IS_IN_ACTIVITY);
item.showDialog(this, isInActivity ? getFragmentManager() : getChildFragmentManager());
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){
return new SimpleDialogFragmentCallback() {
@Override | // Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/DialogFragmentInterface.java
// public interface DialogFragmentInterface {
//
// String getTag();
//
// void show(FragmentManager manager, String tag);
//
// int show(FragmentTransaction transaction, String tag);
//
// void dismiss();
//
// void dismissAllowingStateLoss();
//
// Dialog getDialog();
//
// DialogFragmentInterface setExtra(Bundle extra);
//
// Bundle getExtra();
//
// }
//
// Path: library/src/main/java/com/wada811/android/dialogfragments/interfaces/SimpleDialogFragmentCallback.java
// public class SimpleDialogFragmentCallback implements DialogFragmentCallback {
//
// @Override
// public void onShow(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnShowListener called, but #onShow has not implemented.");
// }
//
// @Override
// public void onCancel(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnCancelListener called, but #onCancel has not implemented.");
// }
//
// @Override
// public void onDismiss(DialogFragmentInterface dialog){
// throw new RuntimeException("#setOnDismissListener called, but #onDismiss has not implemented.");
// }
//
// @Override
// public void onClickPositive(DialogFragmentInterface dialog){
// throw new RuntimeException("#setPositiveButton called, but #onClickPositive has not implemented.");
// }
//
// @Override
// public void onClickNegative(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNegativeButton called, but #onClickNegative has not implemented.");
// }
//
// @Override
// public void onClickNeutral(DialogFragmentInterface dialog){
// throw new RuntimeException("#setNeutralButton called, but #onClickNeutral has not implemented.");
// }
//
// @Override
// public void onItemClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setItems or #setAdapter called, but #onItemClick has not implemented.");
// }
//
// @Override
// public void onSingleChoiceClick(DialogFragmentInterface dialog, int position){
// throw new RuntimeException("#setSingleChoiceItems called, but #onSingleChoiceClick has not implemented.");
// }
//
// @Override
// public void onMultiChoiceClick(DialogFragmentInterface dialog, int position, boolean isChecked){
// throw new RuntimeException("#setMultiChoiceItems called, but #onMultiChoiceClick has not implemented.");
// }
//
// @Override
// public boolean onKey(DialogFragmentInterface dialog, int keyCode, KeyEvent event){
// throw new RuntimeException("#setOnKeyListener called, but #onKey has not implemented.");
// }
//
// @Override
// public View getCustomTitle(DialogFragmentInterface dialog){
// throw new RuntimeException("#setCustomTitle called, but #getCustomTitle has not implemented.");
// }
//
// @Override
// public View getView(DialogFragmentInterface dialog){
// throw new RuntimeException("#setView called, but #getView has not implemented.");
// }
//
// @Override
// public ListAdapter getAdapter(DialogFragmentInterface dialog){
// throw new RuntimeException("#setAdapter called, but #getAdapter has not implemented.");
// }
//
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// throw new RuntimeException("DatePickerDialogFragment has instantiated, but #onDateSet has not implemented.");
// }
//
// @Override
// public void onTimeSet(DialogFragmentInterface dialog, TimePicker timePicker, int hour, int minute){
// throw new RuntimeException("TimePickerDialogFragment has instantiated, but #onTimeSet has not implemented.");
// }
//
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// throw new RuntimeException("NumberPickerDialogFragment has instantiated, but #onNumberSet has not implemented.");
// }
//
// @Override
// public void onStringSet(DialogFragmentInterface dialog, StringPicker stringPicker, String value){
// throw new RuntimeException("StringPickerDialogFragment has instantiated, but #onStringSet has not implemented.");
// }
// }
// Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/datepickerdialogfragment/DatePickerDialogFragmentExamplesFragment.java
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Toast;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallback;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentCallbackProvider;
import com.wada811.android.dialogfragments.interfaces.DialogFragmentInterface;
import com.wada811.android.dialogfragments.interfaces.SimpleDialogFragmentCallback;
import com.wada811.android.dialogfragments.sample.Const;
import com.wada811.android.dialogfragments.sample.Example;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
initExample();
initListFragment();
}
private void initExample(){
items = new ArrayList<>();
items.add(new com.wada811.android.dialogfragments.sample.datepickerdialogfragment.examples.traditional.BasicDatePickerDialogExample());
items.add(new com.wada811.android.dialogfragments.sample.datepickerdialogfragment.examples.material.BasicDatePickerDialogExample());
}
private void initListFragment(){
setListAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, items));
}
@Override
public void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
Example item = items.get(position);
boolean isInActivity = getArguments().getBoolean(Const.KEY_IS_IN_ACTIVITY);
item.showDialog(this, isInActivity ? getFragmentManager() : getChildFragmentManager());
}
@Override
public DialogFragmentCallback getDialogFragmentCallback(){
return new SimpleDialogFragmentCallback() {
@Override | public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){ |
wada811/Android-DialogFragments | sample/src/main/java/com/wada811/android/dialogfragments/sample/ExamplesFragment.java | // Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/datepickerdialogfragment/DatePickerDialogFragmentExamplesActivity.java
// public class DatePickerDialogFragmentExamplesActivity extends ActionBarActivity
// implements DialogFragmentCallbackProvider {
//
// final DatePickerDialogFragmentExamplesActivity self = this;
//
// @Override
// protected void onCreate(Bundle savedInstanceState){
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity);
//
// boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
// getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_date_picker_dialog_fragment_examples_in_activity : R.string.title_activity_date_picker_dialog_fragment_examples_in_fragment);
// if(savedInstanceState == null){
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.container, DatePickerDialogFragmentExamplesFragment.newInstance(isInActivity))
// .commit();
// }
// }
//
// @Override
// public DialogFragmentCallback getDialogFragmentCallback(){
// return new SimpleDialogFragmentCallback() {
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// String text = "onDateSet[year: " + year + ", month: " + month + ", day: " + day + "]";
// Log.v(dialog.getTag(), text);
// Toast.makeText(self, text, Toast.LENGTH_SHORT).show();
// }
// };
// }
// }
//
// Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/numberpickerdialogfragment/NumberPickerDialogFragmentExamplesActivity.java
// public class NumberPickerDialogFragmentExamplesActivity extends ActionBarActivity
// implements DialogFragmentCallbackProvider {
//
// final NumberPickerDialogFragmentExamplesActivity self = this;
//
// @Override
// protected void onCreate(Bundle savedInstanceState){
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity);
//
// boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
// getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_number_picker_dialog_fragment_examples_in_activity : R.string.title_activity_number_picker_dialog_fragment_examples_in_fragment);
// if(savedInstanceState == null){
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.container, NumberPickerDialogFragmentExamplesFragment.newInstance(isInActivity))
// .commit();
// }
// }
//
// @Override
// public DialogFragmentCallback getDialogFragmentCallback(){
// return new SimpleDialogFragmentCallback() {
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// String text = "onTimeSet[value: " + value + "]";
// Log.v(dialog.getTag(), text);
// Toast.makeText(self, text, Toast.LENGTH_SHORT).show();
// }
// };
// }
// }
| import java.util.ArrayList;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.wada811.android.dialogfragments.sample.alertdialogfragment.AlertDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.datepickerdialogfragment.DatePickerDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.dialogfragmentcallbackprovider.DialogFragmentCallbackProviderActivity;
import com.wada811.android.dialogfragments.sample.numberpickerdialogfragment.NumberPickerDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.progressdialogfragment.ProgressDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.stringpickerdialogfragment.StringPickerDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.timepickerdialogfragment.TimePickerDialogFragmentExamplesActivity; | public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
initExamples();
setListAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, items));
}
private void initExamples(){
items = new ArrayList<>();
{
Intent intent = new Intent(getActivity(), DialogFragmentCallbackProviderActivity.class);
items.add(new Examples(getString(R.string.title_activity_dialog_fragment_callback_provider), intent));
}
{
Intent intent = new Intent(getActivity(), AlertDialogFragmentExamplesActivity.class);
intent.putExtra(Const.KEY_IS_IN_ACTIVITY, true);
String label = getString(R.string.title_activity_alert_dialog_fragment_examples_in_activity);
items.add(new Examples(label, intent));
}
{
Intent intent = new Intent(getActivity(), AlertDialogFragmentExamplesActivity.class);
intent.putExtra(Const.KEY_IS_IN_ACTIVITY, false);
String label = getString(R.string.title_activity_alert_dialog_fragment_examples_in_fragment);
items.add(new Examples(label, intent));
}
{
Intent intent = new Intent(getActivity(), ProgressDialogFragmentExamplesActivity.class);
items.add(new Examples(getString(R.string.title_activity_progress_dialog_fragment_examples), intent));
}
{ | // Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/datepickerdialogfragment/DatePickerDialogFragmentExamplesActivity.java
// public class DatePickerDialogFragmentExamplesActivity extends ActionBarActivity
// implements DialogFragmentCallbackProvider {
//
// final DatePickerDialogFragmentExamplesActivity self = this;
//
// @Override
// protected void onCreate(Bundle savedInstanceState){
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity);
//
// boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
// getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_date_picker_dialog_fragment_examples_in_activity : R.string.title_activity_date_picker_dialog_fragment_examples_in_fragment);
// if(savedInstanceState == null){
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.container, DatePickerDialogFragmentExamplesFragment.newInstance(isInActivity))
// .commit();
// }
// }
//
// @Override
// public DialogFragmentCallback getDialogFragmentCallback(){
// return new SimpleDialogFragmentCallback() {
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// String text = "onDateSet[year: " + year + ", month: " + month + ", day: " + day + "]";
// Log.v(dialog.getTag(), text);
// Toast.makeText(self, text, Toast.LENGTH_SHORT).show();
// }
// };
// }
// }
//
// Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/numberpickerdialogfragment/NumberPickerDialogFragmentExamplesActivity.java
// public class NumberPickerDialogFragmentExamplesActivity extends ActionBarActivity
// implements DialogFragmentCallbackProvider {
//
// final NumberPickerDialogFragmentExamplesActivity self = this;
//
// @Override
// protected void onCreate(Bundle savedInstanceState){
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity);
//
// boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
// getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_number_picker_dialog_fragment_examples_in_activity : R.string.title_activity_number_picker_dialog_fragment_examples_in_fragment);
// if(savedInstanceState == null){
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.container, NumberPickerDialogFragmentExamplesFragment.newInstance(isInActivity))
// .commit();
// }
// }
//
// @Override
// public DialogFragmentCallback getDialogFragmentCallback(){
// return new SimpleDialogFragmentCallback() {
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// String text = "onTimeSet[value: " + value + "]";
// Log.v(dialog.getTag(), text);
// Toast.makeText(self, text, Toast.LENGTH_SHORT).show();
// }
// };
// }
// }
// Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/ExamplesFragment.java
import java.util.ArrayList;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.wada811.android.dialogfragments.sample.alertdialogfragment.AlertDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.datepickerdialogfragment.DatePickerDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.dialogfragmentcallbackprovider.DialogFragmentCallbackProviderActivity;
import com.wada811.android.dialogfragments.sample.numberpickerdialogfragment.NumberPickerDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.progressdialogfragment.ProgressDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.stringpickerdialogfragment.StringPickerDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.timepickerdialogfragment.TimePickerDialogFragmentExamplesActivity;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
initExamples();
setListAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, items));
}
private void initExamples(){
items = new ArrayList<>();
{
Intent intent = new Intent(getActivity(), DialogFragmentCallbackProviderActivity.class);
items.add(new Examples(getString(R.string.title_activity_dialog_fragment_callback_provider), intent));
}
{
Intent intent = new Intent(getActivity(), AlertDialogFragmentExamplesActivity.class);
intent.putExtra(Const.KEY_IS_IN_ACTIVITY, true);
String label = getString(R.string.title_activity_alert_dialog_fragment_examples_in_activity);
items.add(new Examples(label, intent));
}
{
Intent intent = new Intent(getActivity(), AlertDialogFragmentExamplesActivity.class);
intent.putExtra(Const.KEY_IS_IN_ACTIVITY, false);
String label = getString(R.string.title_activity_alert_dialog_fragment_examples_in_fragment);
items.add(new Examples(label, intent));
}
{
Intent intent = new Intent(getActivity(), ProgressDialogFragmentExamplesActivity.class);
items.add(new Examples(getString(R.string.title_activity_progress_dialog_fragment_examples), intent));
}
{ | Intent intent = new Intent(getActivity(), DatePickerDialogFragmentExamplesActivity.class); |
wada811/Android-DialogFragments | sample/src/main/java/com/wada811/android/dialogfragments/sample/ExamplesFragment.java | // Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/datepickerdialogfragment/DatePickerDialogFragmentExamplesActivity.java
// public class DatePickerDialogFragmentExamplesActivity extends ActionBarActivity
// implements DialogFragmentCallbackProvider {
//
// final DatePickerDialogFragmentExamplesActivity self = this;
//
// @Override
// protected void onCreate(Bundle savedInstanceState){
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity);
//
// boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
// getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_date_picker_dialog_fragment_examples_in_activity : R.string.title_activity_date_picker_dialog_fragment_examples_in_fragment);
// if(savedInstanceState == null){
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.container, DatePickerDialogFragmentExamplesFragment.newInstance(isInActivity))
// .commit();
// }
// }
//
// @Override
// public DialogFragmentCallback getDialogFragmentCallback(){
// return new SimpleDialogFragmentCallback() {
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// String text = "onDateSet[year: " + year + ", month: " + month + ", day: " + day + "]";
// Log.v(dialog.getTag(), text);
// Toast.makeText(self, text, Toast.LENGTH_SHORT).show();
// }
// };
// }
// }
//
// Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/numberpickerdialogfragment/NumberPickerDialogFragmentExamplesActivity.java
// public class NumberPickerDialogFragmentExamplesActivity extends ActionBarActivity
// implements DialogFragmentCallbackProvider {
//
// final NumberPickerDialogFragmentExamplesActivity self = this;
//
// @Override
// protected void onCreate(Bundle savedInstanceState){
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity);
//
// boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
// getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_number_picker_dialog_fragment_examples_in_activity : R.string.title_activity_number_picker_dialog_fragment_examples_in_fragment);
// if(savedInstanceState == null){
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.container, NumberPickerDialogFragmentExamplesFragment.newInstance(isInActivity))
// .commit();
// }
// }
//
// @Override
// public DialogFragmentCallback getDialogFragmentCallback(){
// return new SimpleDialogFragmentCallback() {
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// String text = "onTimeSet[value: " + value + "]";
// Log.v(dialog.getTag(), text);
// Toast.makeText(self, text, Toast.LENGTH_SHORT).show();
// }
// };
// }
// }
| import java.util.ArrayList;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.wada811.android.dialogfragments.sample.alertdialogfragment.AlertDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.datepickerdialogfragment.DatePickerDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.dialogfragmentcallbackprovider.DialogFragmentCallbackProviderActivity;
import com.wada811.android.dialogfragments.sample.numberpickerdialogfragment.NumberPickerDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.progressdialogfragment.ProgressDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.stringpickerdialogfragment.StringPickerDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.timepickerdialogfragment.TimePickerDialogFragmentExamplesActivity; | }
{
Intent intent = new Intent(getActivity(), ProgressDialogFragmentExamplesActivity.class);
items.add(new Examples(getString(R.string.title_activity_progress_dialog_fragment_examples), intent));
}
{
Intent intent = new Intent(getActivity(), DatePickerDialogFragmentExamplesActivity.class);
intent.putExtra(Const.KEY_IS_IN_ACTIVITY, true);
String label = getString(R.string.title_activity_date_picker_dialog_fragment_examples_in_activity);
items.add(new Examples(label, intent));
}
{
Intent intent = new Intent(getActivity(), DatePickerDialogFragmentExamplesActivity.class);
intent.putExtra(Const.KEY_IS_IN_ACTIVITY, false);
String label = getString(R.string.title_activity_date_picker_dialog_fragment_examples_in_fragment);
items.add(new Examples(label, intent));
}
{
Intent intent = new Intent(getActivity(), TimePickerDialogFragmentExamplesActivity.class);
intent.putExtra(Const.KEY_IS_IN_ACTIVITY, true);
String label = getString(R.string.title_activity_time_picker_dialog_fragment_examples_in_activity);
items.add(new Examples(label, intent));
}
{
Intent intent = new Intent(getActivity(), TimePickerDialogFragmentExamplesActivity.class);
intent.putExtra(Const.KEY_IS_IN_ACTIVITY, false);
String label = getString(R.string.title_activity_time_picker_dialog_fragment_examples_in_fragment);
items.add(new Examples(label, intent));
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){ | // Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/datepickerdialogfragment/DatePickerDialogFragmentExamplesActivity.java
// public class DatePickerDialogFragmentExamplesActivity extends ActionBarActivity
// implements DialogFragmentCallbackProvider {
//
// final DatePickerDialogFragmentExamplesActivity self = this;
//
// @Override
// protected void onCreate(Bundle savedInstanceState){
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity);
//
// boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
// getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_date_picker_dialog_fragment_examples_in_activity : R.string.title_activity_date_picker_dialog_fragment_examples_in_fragment);
// if(savedInstanceState == null){
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.container, DatePickerDialogFragmentExamplesFragment.newInstance(isInActivity))
// .commit();
// }
// }
//
// @Override
// public DialogFragmentCallback getDialogFragmentCallback(){
// return new SimpleDialogFragmentCallback() {
// @Override
// public void onDateSet(DialogFragmentInterface dialog, DatePicker datePicker, int year, int month, int day){
// String text = "onDateSet[year: " + year + ", month: " + month + ", day: " + day + "]";
// Log.v(dialog.getTag(), text);
// Toast.makeText(self, text, Toast.LENGTH_SHORT).show();
// }
// };
// }
// }
//
// Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/numberpickerdialogfragment/NumberPickerDialogFragmentExamplesActivity.java
// public class NumberPickerDialogFragmentExamplesActivity extends ActionBarActivity
// implements DialogFragmentCallbackProvider {
//
// final NumberPickerDialogFragmentExamplesActivity self = this;
//
// @Override
// protected void onCreate(Bundle savedInstanceState){
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity);
//
// boolean isInActivity = getIntent().getBooleanExtra(Const.KEY_IS_IN_ACTIVITY, true);
// getSupportActionBar().setTitle(isInActivity ? R.string.title_activity_number_picker_dialog_fragment_examples_in_activity : R.string.title_activity_number_picker_dialog_fragment_examples_in_fragment);
// if(savedInstanceState == null){
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.container, NumberPickerDialogFragmentExamplesFragment.newInstance(isInActivity))
// .commit();
// }
// }
//
// @Override
// public DialogFragmentCallback getDialogFragmentCallback(){
// return new SimpleDialogFragmentCallback() {
// @Override
// public void onNumberSet(DialogFragmentInterface dialog, NumberPicker numberPicker, int value){
// String text = "onTimeSet[value: " + value + "]";
// Log.v(dialog.getTag(), text);
// Toast.makeText(self, text, Toast.LENGTH_SHORT).show();
// }
// };
// }
// }
// Path: sample/src/main/java/com/wada811/android/dialogfragments/sample/ExamplesFragment.java
import java.util.ArrayList;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.wada811.android.dialogfragments.sample.alertdialogfragment.AlertDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.datepickerdialogfragment.DatePickerDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.dialogfragmentcallbackprovider.DialogFragmentCallbackProviderActivity;
import com.wada811.android.dialogfragments.sample.numberpickerdialogfragment.NumberPickerDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.progressdialogfragment.ProgressDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.stringpickerdialogfragment.StringPickerDialogFragmentExamplesActivity;
import com.wada811.android.dialogfragments.sample.timepickerdialogfragment.TimePickerDialogFragmentExamplesActivity;
}
{
Intent intent = new Intent(getActivity(), ProgressDialogFragmentExamplesActivity.class);
items.add(new Examples(getString(R.string.title_activity_progress_dialog_fragment_examples), intent));
}
{
Intent intent = new Intent(getActivity(), DatePickerDialogFragmentExamplesActivity.class);
intent.putExtra(Const.KEY_IS_IN_ACTIVITY, true);
String label = getString(R.string.title_activity_date_picker_dialog_fragment_examples_in_activity);
items.add(new Examples(label, intent));
}
{
Intent intent = new Intent(getActivity(), DatePickerDialogFragmentExamplesActivity.class);
intent.putExtra(Const.KEY_IS_IN_ACTIVITY, false);
String label = getString(R.string.title_activity_date_picker_dialog_fragment_examples_in_fragment);
items.add(new Examples(label, intent));
}
{
Intent intent = new Intent(getActivity(), TimePickerDialogFragmentExamplesActivity.class);
intent.putExtra(Const.KEY_IS_IN_ACTIVITY, true);
String label = getString(R.string.title_activity_time_picker_dialog_fragment_examples_in_activity);
items.add(new Examples(label, intent));
}
{
Intent intent = new Intent(getActivity(), TimePickerDialogFragmentExamplesActivity.class);
intent.putExtra(Const.KEY_IS_IN_ACTIVITY, false);
String label = getString(R.string.title_activity_time_picker_dialog_fragment_examples_in_fragment);
items.add(new Examples(label, intent));
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){ | Intent intent = new Intent(getActivity(), NumberPickerDialogFragmentExamplesActivity.class); |
trc492/Frc2017FirstSteamWorks | src/trclib/TrcRGBLight.java | // Path: src/trclib/TrcTaskMgr.java
// public enum TaskType
// {
// /**
// * START_TASK is called one time before a competition mode is about to start.
// */
// START_TASK,
//
// /**
// * STOP_TASK is called one time before a competition mode is about to end.
// */
// STOP_TASK,
//
// /**
// * PREPERIODIC_TASK is called periodically at a rate about 50Hz before runPeriodic().
// */
// PREPERIODIC_TASK,
//
// /**
// * POSTPERIODIC_TASK is called periodically at a rate about 50Hz after runPeriodic().
// */
// POSTPERIODIC_TASK,
//
// /**
// * PRECONTINUOUS_TASK is called periodically at a rate as fast as the scheduler is able to loop and is run
// * before runContinuous() typically 10 msec interval.
// */
// PRECONTINUOUS_TASK,
//
// /**
// * POSTCONTINUOUS_TASK is called periodically at a rate as fast as the schedule is able to loop and is run
// * after runContinuous() typically 10 msec interval.
// */
// POSTCONTINUOUS_TASK
//
// } //enum TaskType
| import trclib.TrcTaskMgr.TaskType; | timerEvent = new TrcEvent(moduleName + ".timer");
} //TrcRGBLight
/**
* This method returns the instance name.
*
* @return instance name.
*/
public String toString()
{
return instanceName;
} //toString
/**
* This method enables/disables the RGB light task that keeps track of the blinking period of the RGB light.
*
* @param enabled specifies true to enable RGB light task, false to disable.
*/
private void setTaskEnabled(boolean enabled)
{
final String funcName = "setTaskEnabled";
if (debugEnabled)
{
dbgTrace.traceEnter(funcName, TrcDbgTrace.TraceLevel.FUNC, "enabled=%s", Boolean.toString(enabled));
dbgTrace.traceExit(funcName, TrcDbgTrace.TraceLevel.FUNC);
}
if (enabled)
{ | // Path: src/trclib/TrcTaskMgr.java
// public enum TaskType
// {
// /**
// * START_TASK is called one time before a competition mode is about to start.
// */
// START_TASK,
//
// /**
// * STOP_TASK is called one time before a competition mode is about to end.
// */
// STOP_TASK,
//
// /**
// * PREPERIODIC_TASK is called periodically at a rate about 50Hz before runPeriodic().
// */
// PREPERIODIC_TASK,
//
// /**
// * POSTPERIODIC_TASK is called periodically at a rate about 50Hz after runPeriodic().
// */
// POSTPERIODIC_TASK,
//
// /**
// * PRECONTINUOUS_TASK is called periodically at a rate as fast as the scheduler is able to loop and is run
// * before runContinuous() typically 10 msec interval.
// */
// PRECONTINUOUS_TASK,
//
// /**
// * POSTCONTINUOUS_TASK is called periodically at a rate as fast as the schedule is able to loop and is run
// * after runContinuous() typically 10 msec interval.
// */
// POSTCONTINUOUS_TASK
//
// } //enum TaskType
// Path: src/trclib/TrcRGBLight.java
import trclib.TrcTaskMgr.TaskType;
timerEvent = new TrcEvent(moduleName + ".timer");
} //TrcRGBLight
/**
* This method returns the instance name.
*
* @return instance name.
*/
public String toString()
{
return instanceName;
} //toString
/**
* This method enables/disables the RGB light task that keeps track of the blinking period of the RGB light.
*
* @param enabled specifies true to enable RGB light task, false to disable.
*/
private void setTaskEnabled(boolean enabled)
{
final String funcName = "setTaskEnabled";
if (debugEnabled)
{
dbgTrace.traceEnter(funcName, TrcDbgTrace.TraceLevel.FUNC, "enabled=%s", Boolean.toString(enabled));
dbgTrace.traceExit(funcName, TrcDbgTrace.TraceLevel.FUNC);
}
if (enabled)
{ | TrcTaskMgr.getInstance().registerTask(moduleName, this, TaskType.POSTCONTINUOUS_TASK); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/ProfileParametersServiceImpl.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
| import com.intellij.openapi.diagnostic.Logger;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import jetbrains.buildServer.dotNet.buildRunner.agent.FileService;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class ProfileParametersServiceImpl implements ProfileParametersService {
private static final Logger LOG = Logger.getInstance(ProfileParametersServiceImpl.class.getName());
private final Map<String, Configuration> myProfiles = new HashMap<String, Configuration>();
private final AgentParametersService myAgentParametersService;
private final PathsService myPathsService;
private final FileService myFileService;
private final CryptographicService myCryptographicService;
public ProfileParametersServiceImpl(
@NotNull final AgentParametersService runnerParametersService,
@NotNull final PathsService pathsService,
@NotNull final FileService fileService,
@NotNull final CryptographicService cryptographicService) {
myAgentParametersService = runnerParametersService;
myPathsService = pathsService;
myFileService = fileService;
myCryptographicService = cryptographicService;
}
@Override
public void load() {
myProfiles.clear(); | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/ProfileParametersServiceImpl.java
import com.intellij.openapi.diagnostic.Logger;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import jetbrains.buildServer.dotNet.buildRunner.agent.FileService;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class ProfileParametersServiceImpl implements ProfileParametersService {
private static final Logger LOG = Logger.getInstance(ProfileParametersServiceImpl.class.getName());
private final Map<String, Configuration> myProfiles = new HashMap<String, Configuration>();
private final AgentParametersService myAgentParametersService;
private final PathsService myPathsService;
private final FileService myFileService;
private final CryptographicService myCryptographicService;
public ProfileParametersServiceImpl(
@NotNull final AgentParametersService runnerParametersService,
@NotNull final PathsService pathsService,
@NotNull final FileService fileService,
@NotNull final CryptographicService cryptographicService) {
myAgentParametersService = runnerParametersService;
myPathsService = pathsService;
myFileService = fileService;
myCryptographicService = cryptographicService;
}
@Override
public void load() {
myProfiles.clear(); | final String credentialsDirectoryStr = myAgentParametersService.tryGetConfigParameter(jetbrains.buildServer.runAs.common.Constants.CREDENTIALS_DIRECTORY); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/RunAsPlatformSpecificSetupBuilder.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
| import java.io.File;
import java.util.*;
import jetbrains.buildServer.agent.BuildAgentSystemInfo;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.Constants;
import org.jetbrains.annotations.NotNull; | final File commandFile = myFileService.getTempFileName(myCommandFileExtension);
resources.add(new CommandLineFile(myBeforeBuildPublisher, commandFile.getAbsoluteFile(), myRunAsCmdGenerator.create(params)));
final ArrayList<AccessControlEntry> acl = new ArrayList<AccessControlEntry>();
for (AccessControlEntry ace: myAccessControlListProvider.getAcl(userCredentials)) {
acl.add(ace);
}
acl.add(new AccessControlEntry(commandFile, AccessControlAccount.forUser(userCredentials.getUser()), EnumSet.of(AccessPermissions.GrantExecute), AccessControlScope.Step));
final File runAsToolPath = getTool();
final AccessControlEntry runAsToolAce = new AccessControlEntry(runAsToolPath, AccessControlAccount.forUser(userCredentials.getUser()), EnumSet.of(AccessPermissions.GrantExecute), AccessControlScope.Build);
acl.add(runAsToolAce);
myAccessControlResource.setAcl(new AccessControlList(acl));
resources.add(myAccessControlResource);
final CommandLineSetup runAsCommandLineSetup = new CommandLineSetup(
runAsToolPath.getAbsolutePath(),
Arrays.asList(
new CommandLineArgument(settingsFile.getAbsolutePath(), CommandLineArgument.Type.PARAMETER),
new CommandLineArgument(commandFile.getAbsolutePath(), CommandLineArgument.Type.PARAMETER),
new CommandLineArgument(myBuildAgentSystemInfo.bitness().toString(), CommandLineArgument.Type.PARAMETER),
new CommandLineArgument(myArgumentConverter.convert(userCredentials.getPassword()), CommandLineArgument.Type.PARAMETER)),
resources);
myRunAsLogger.LogRunAs(userCredentials, commandLineSetup, runAsCommandLineSetup);
return Collections.singleton(runAsCommandLineSetup);
}
private File getTool() { | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/RunAsPlatformSpecificSetupBuilder.java
import java.io.File;
import java.util.*;
import jetbrains.buildServer.agent.BuildAgentSystemInfo;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.Constants;
import org.jetbrains.annotations.NotNull;
final File commandFile = myFileService.getTempFileName(myCommandFileExtension);
resources.add(new CommandLineFile(myBeforeBuildPublisher, commandFile.getAbsoluteFile(), myRunAsCmdGenerator.create(params)));
final ArrayList<AccessControlEntry> acl = new ArrayList<AccessControlEntry>();
for (AccessControlEntry ace: myAccessControlListProvider.getAcl(userCredentials)) {
acl.add(ace);
}
acl.add(new AccessControlEntry(commandFile, AccessControlAccount.forUser(userCredentials.getUser()), EnumSet.of(AccessPermissions.GrantExecute), AccessControlScope.Step));
final File runAsToolPath = getTool();
final AccessControlEntry runAsToolAce = new AccessControlEntry(runAsToolPath, AccessControlAccount.forUser(userCredentials.getUser()), EnumSet.of(AccessPermissions.GrantExecute), AccessControlScope.Build);
acl.add(runAsToolAce);
myAccessControlResource.setAcl(new AccessControlList(acl));
resources.add(myAccessControlResource);
final CommandLineSetup runAsCommandLineSetup = new CommandLineSetup(
runAsToolPath.getAbsolutePath(),
Arrays.asList(
new CommandLineArgument(settingsFile.getAbsolutePath(), CommandLineArgument.Type.PARAMETER),
new CommandLineArgument(commandFile.getAbsolutePath(), CommandLineArgument.Type.PARAMETER),
new CommandLineArgument(myBuildAgentSystemInfo.bitness().toString(), CommandLineArgument.Type.PARAMETER),
new CommandLineArgument(myArgumentConverter.convert(userCredentials.getPassword()), CommandLineArgument.Type.PARAMETER)),
resources);
myRunAsLogger.LogRunAs(userCredentials, commandLineSetup, runAsCommandLineSetup);
return Collections.singleton(runAsCommandLineSetup);
}
private File getTool() { | final File path = new File(myRunnerParametersService.getToolPath(Constants.RUN_AS_TOOL_NAME), TOOL_FILE_NAME + myCommandFileExtension); |
JetBrains/teamcity-runas-plugin | runAs-server/src/main/java/jetbrains/buildServer/runAs/server/RunAsBean.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.server;
public class RunAsBean {
public static final RunAsBean Shared = new RunAsBean();
@NotNull
public String getRunAsUserKey() { | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-server/src/main/java/jetbrains/buildServer/runAs/server/RunAsBean.java
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.server;
public class RunAsBean {
public static final RunAsBean Shared = new RunAsBean();
@NotNull
public String getRunAsUserKey() { | return Constants.USER; |
JetBrains/teamcity-runas-plugin | runAs-server/src/main/java/jetbrains/buildServer/runAs/server/RunAsBean.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.server;
public class RunAsBean {
public static final RunAsBean Shared = new RunAsBean();
@NotNull
public String getRunAsUserKey() {
return Constants.USER;
}
@NotNull
public String getRunAsPasswordKey() {
return Constants.PASSWORD;
}
@NotNull
public String getAdditionalCommandLineParametersKey() {
return Constants.ADDITIONAL_ARGS;
}
@NotNull
public String getWindowsIntegrityLevelKey() {
return Constants.WINDOWS_INTEGRITY_LEVEL;
}
@NotNull | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-server/src/main/java/jetbrains/buildServer/runAs/server/RunAsBean.java
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.server;
public class RunAsBean {
public static final RunAsBean Shared = new RunAsBean();
@NotNull
public String getRunAsUserKey() {
return Constants.USER;
}
@NotNull
public String getRunAsPasswordKey() {
return Constants.PASSWORD;
}
@NotNull
public String getAdditionalCommandLineParametersKey() {
return Constants.ADDITIONAL_ARGS;
}
@NotNull
public String getWindowsIntegrityLevelKey() {
return Constants.WINDOWS_INTEGRITY_LEVEL;
}
@NotNull | public List<WindowsIntegrityLevel> getWindowsIntegrityLevels() { |
JetBrains/teamcity-runas-plugin | runAs-server/src/main/java/jetbrains/buildServer/runAs/server/RunAsBean.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.server;
public class RunAsBean {
public static final RunAsBean Shared = new RunAsBean();
@NotNull
public String getRunAsUserKey() {
return Constants.USER;
}
@NotNull
public String getRunAsPasswordKey() {
return Constants.PASSWORD;
}
@NotNull
public String getAdditionalCommandLineParametersKey() {
return Constants.ADDITIONAL_ARGS;
}
@NotNull
public String getWindowsIntegrityLevelKey() {
return Constants.WINDOWS_INTEGRITY_LEVEL;
}
@NotNull
public List<WindowsIntegrityLevel> getWindowsIntegrityLevels() {
return Arrays.asList(WindowsIntegrityLevel.values());
}
@NotNull
public String getWindowsLoggingLevelKey() {
return Constants.LOGGING_LEVEL;
}
@NotNull | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-server/src/main/java/jetbrains/buildServer/runAs/server/RunAsBean.java
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.server;
public class RunAsBean {
public static final RunAsBean Shared = new RunAsBean();
@NotNull
public String getRunAsUserKey() {
return Constants.USER;
}
@NotNull
public String getRunAsPasswordKey() {
return Constants.PASSWORD;
}
@NotNull
public String getAdditionalCommandLineParametersKey() {
return Constants.ADDITIONAL_ARGS;
}
@NotNull
public String getWindowsIntegrityLevelKey() {
return Constants.WINDOWS_INTEGRITY_LEVEL;
}
@NotNull
public List<WindowsIntegrityLevel> getWindowsIntegrityLevels() {
return Arrays.asList(WindowsIntegrityLevel.values());
}
@NotNull
public String getWindowsLoggingLevelKey() {
return Constants.LOGGING_LEVEL;
}
@NotNull | public List<LoggingLevel> getLoggingLevels() { |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/RunAsPlatformSpecificSetupBuilderTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.io.IOException;
import java.util.*;
import jetbrains.buildServer.agent.BuildAgentSystemInfo;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.Bitness;
import org.jetbrains.annotations.NotNull;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction; | myCommandLineResource2,
new CommandLineFile(myBeforeBuildPublisher, credentialsFile.getAbsoluteFile(), credentialsContent),
new CommandLineFile(myBeforeBuildPublisher, cmdFile.getAbsoluteFile(), cmdContent),
myAccessControlResource));
myCtx.checking(new Expectations() {{
oneOf(myRunAsAccessService).getIsRunAsEnabled();
will(returnValue(true));
oneOf(myUserCredentialsService).tryGetUserCredentials();
will(returnValue(userCredentials));
oneOf(myAccessControlListProvider).getAcl(userCredentials);
will(returnValue(stepAcl));
oneOf(myFileService).getTempFileName(RunAsPlatformSpecificSetupBuilder.ARGS_EXT);
will(returnValue(credentialsFile));
oneOf(myBuildAgentSystemInfo).bitness();
will(returnValue(Bitness.BIT64));
oneOf(myFileService).getTempFileName(".abc");
will(returnValue(cmdFile));
oneOf(myCredentialsGenerator).create(with(userCredentials));
will(returnValue(credentialsContent));
oneOf(myArgsGenerator).create(params);
will(returnValue(cmdContent));
| // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/RunAsPlatformSpecificSetupBuilderTest.java
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.io.IOException;
import java.util.*;
import jetbrains.buildServer.agent.BuildAgentSystemInfo;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.Bitness;
import org.jetbrains.annotations.NotNull;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
myCommandLineResource2,
new CommandLineFile(myBeforeBuildPublisher, credentialsFile.getAbsoluteFile(), credentialsContent),
new CommandLineFile(myBeforeBuildPublisher, cmdFile.getAbsoluteFile(), cmdContent),
myAccessControlResource));
myCtx.checking(new Expectations() {{
oneOf(myRunAsAccessService).getIsRunAsEnabled();
will(returnValue(true));
oneOf(myUserCredentialsService).tryGetUserCredentials();
will(returnValue(userCredentials));
oneOf(myAccessControlListProvider).getAcl(userCredentials);
will(returnValue(stepAcl));
oneOf(myFileService).getTempFileName(RunAsPlatformSpecificSetupBuilder.ARGS_EXT);
will(returnValue(credentialsFile));
oneOf(myBuildAgentSystemInfo).bitness();
will(returnValue(Bitness.BIT64));
oneOf(myFileService).getTempFileName(".abc");
will(returnValue(cmdFile));
oneOf(myCredentialsGenerator).create(with(userCredentials));
will(returnValue(credentialsContent));
oneOf(myArgsGenerator).create(params);
will(returnValue(cmdContent));
| oneOf(myRunnerParametersService).getToolPath(Constants.RUN_AS_TOOL_NAME); |
JetBrains/teamcity-runas-plugin | runAs-server/src/main/java/jetbrains/buildServer/runAs/server/RunAsConfiguration.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
| import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.serverSide.TeamCityProperties; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.server;
public class RunAsConfiguration {
public boolean getIsUiSupported() { | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
// Path: runAs-server/src/main/java/jetbrains/buildServer/runAs/server/RunAsConfiguration.java
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.serverSide.TeamCityProperties;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.server;
public class RunAsConfiguration {
public boolean getIsUiSupported() { | return TeamCityProperties.getBooleanOrTrue(Constants.RUN_AS_UI_ENABLED); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/WindowsSettingsGenerator.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import com.intellij.openapi.util.text.StringUtil;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.ResourceGenerator;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.CollectionsUtil;
import jetbrains.buildServer.util.Converter;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class WindowsSettingsGenerator implements ResourceGenerator<UserCredentials> {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
private static final String USER_CMD_KEY = "-u:";
private static final String INTEGRITY_LEVEL_CMD_KEY = "-il:";
private static final String LOGGING_LEVEL_CMD_KEY = "-l:";
@NotNull
@Override
public String create(@NotNull final UserCredentials userCredentials) {
final StringBuilder sb = new StringBuilder();
final String user = userCredentials.getUser();
if(!StringUtil.isEmptyOrSpaces(user)) {
sb.append(USER_CMD_KEY);
sb.append(userCredentials.getUser());
}
| // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/WindowsSettingsGenerator.java
import com.intellij.openapi.util.text.StringUtil;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.ResourceGenerator;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.CollectionsUtil;
import jetbrains.buildServer.util.Converter;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class WindowsSettingsGenerator implements ResourceGenerator<UserCredentials> {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
private static final String USER_CMD_KEY = "-u:";
private static final String INTEGRITY_LEVEL_CMD_KEY = "-il:";
private static final String LOGGING_LEVEL_CMD_KEY = "-l:";
@NotNull
@Override
public String create(@NotNull final UserCredentials userCredentials) {
final StringBuilder sb = new StringBuilder();
final String user = userCredentials.getUser();
if(!StringUtil.isEmptyOrSpaces(user)) {
sb.append(USER_CMD_KEY);
sb.append(userCredentials.getUser());
}
| if(userCredentials.getWindowsIntegrityLevel() != WindowsIntegrityLevel.Auto) { |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/WindowsSettingsGenerator.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import com.intellij.openapi.util.text.StringUtil;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.ResourceGenerator;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.CollectionsUtil;
import jetbrains.buildServer.util.Converter;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class WindowsSettingsGenerator implements ResourceGenerator<UserCredentials> {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
private static final String USER_CMD_KEY = "-u:";
private static final String INTEGRITY_LEVEL_CMD_KEY = "-il:";
private static final String LOGGING_LEVEL_CMD_KEY = "-l:";
@NotNull
@Override
public String create(@NotNull final UserCredentials userCredentials) {
final StringBuilder sb = new StringBuilder();
final String user = userCredentials.getUser();
if(!StringUtil.isEmptyOrSpaces(user)) {
sb.append(USER_CMD_KEY);
sb.append(userCredentials.getUser());
}
if(userCredentials.getWindowsIntegrityLevel() != WindowsIntegrityLevel.Auto) {
if(sb.length() > 0)
{
sb.append(LINE_SEPARATOR);
}
sb.append(INTEGRITY_LEVEL_CMD_KEY);
sb.append(userCredentials.getWindowsIntegrityLevel().getValue());
}
| // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/WindowsSettingsGenerator.java
import com.intellij.openapi.util.text.StringUtil;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.ResourceGenerator;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.CollectionsUtil;
import jetbrains.buildServer.util.Converter;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class WindowsSettingsGenerator implements ResourceGenerator<UserCredentials> {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
private static final String USER_CMD_KEY = "-u:";
private static final String INTEGRITY_LEVEL_CMD_KEY = "-il:";
private static final String LOGGING_LEVEL_CMD_KEY = "-l:";
@NotNull
@Override
public String create(@NotNull final UserCredentials userCredentials) {
final StringBuilder sb = new StringBuilder();
final String user = userCredentials.getUser();
if(!StringUtil.isEmptyOrSpaces(user)) {
sb.append(USER_CMD_KEY);
sb.append(userCredentials.getUser());
}
if(userCredentials.getWindowsIntegrityLevel() != WindowsIntegrityLevel.Auto) {
if(sb.length() > 0)
{
sb.append(LINE_SEPARATOR);
}
sb.append(INTEGRITY_LEVEL_CMD_KEY);
sb.append(userCredentials.getWindowsIntegrityLevel().getValue());
}
| if(userCredentials.getLoggingLevel() != LoggingLevel.Off) { |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/AccessControlListProviderTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
| import org.testng.annotations.Test;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL_DEFAULTS_ENABLED;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.io.IOException;
import java.util.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.TextParser;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider; | new AccessControlList(Arrays.asList(
new AccessControlEntry(new File("someFile2"), AccessControlAccount.forAll(), EnumSet.of(AccessPermissions.GrantRead), AccessControlScope.Global)))},
};
}
@Test(dataProvider = "getAclCases")
public void shouldGetAcl(
@Nullable final String isDefaultsAclEnabledStr,
@NotNull final String profile,
@Nullable final String agentAclStr,
@Nullable final AccessControlList agentAcl,
@Nullable final String profileAclStr,
@Nullable final AccessControlList profileAcl) throws IOException {
// Given
final String username = "user";
final File work = new File("work");
final File tools = new File("tools");
final File plugins = new File("plugins");
final File lib = new File("lib");
final File config = new File("config");
final File log = new File("log");
final File checkout = new File("checkout");
final File system = new File("system");
final File agentTemp = new File("agentTemp");
final File buildTemp = new File("buildTemp");
final File globalTemp = new File("globalTemp");
UserCredentials userCredentials = new UserCredentials(
profile,
username,
"password78", | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/AccessControlListProviderTest.java
import org.testng.annotations.Test;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL_DEFAULTS_ENABLED;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.io.IOException;
import java.util.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.TextParser;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
new AccessControlList(Arrays.asList(
new AccessControlEntry(new File("someFile2"), AccessControlAccount.forAll(), EnumSet.of(AccessPermissions.GrantRead), AccessControlScope.Global)))},
};
}
@Test(dataProvider = "getAclCases")
public void shouldGetAcl(
@Nullable final String isDefaultsAclEnabledStr,
@NotNull final String profile,
@Nullable final String agentAclStr,
@Nullable final AccessControlList agentAcl,
@Nullable final String profileAclStr,
@Nullable final AccessControlList profileAcl) throws IOException {
// Given
final String username = "user";
final File work = new File("work");
final File tools = new File("tools");
final File plugins = new File("plugins");
final File lib = new File("lib");
final File config = new File("config");
final File log = new File("log");
final File checkout = new File("checkout");
final File system = new File("system");
final File agentTemp = new File("agentTemp");
final File buildTemp = new File("buildTemp");
final File globalTemp = new File("globalTemp");
UserCredentials userCredentials = new UserCredentials(
profile,
username,
"password78", | WindowsIntegrityLevel.High, |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/AccessControlListProviderTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
| import org.testng.annotations.Test;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL_DEFAULTS_ENABLED;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.io.IOException;
import java.util.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.TextParser;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider; | new AccessControlEntry(new File("someFile2"), AccessControlAccount.forAll(), EnumSet.of(AccessPermissions.GrantRead), AccessControlScope.Global)))},
};
}
@Test(dataProvider = "getAclCases")
public void shouldGetAcl(
@Nullable final String isDefaultsAclEnabledStr,
@NotNull final String profile,
@Nullable final String agentAclStr,
@Nullable final AccessControlList agentAcl,
@Nullable final String profileAclStr,
@Nullable final AccessControlList profileAcl) throws IOException {
// Given
final String username = "user";
final File work = new File("work");
final File tools = new File("tools");
final File plugins = new File("plugins");
final File lib = new File("lib");
final File config = new File("config");
final File log = new File("log");
final File checkout = new File("checkout");
final File system = new File("system");
final File agentTemp = new File("agentTemp");
final File buildTemp = new File("buildTemp");
final File globalTemp = new File("globalTemp");
UserCredentials userCredentials = new UserCredentials(
profile,
username,
"password78",
WindowsIntegrityLevel.High, | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/AccessControlListProviderTest.java
import org.testng.annotations.Test;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL_DEFAULTS_ENABLED;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.io.IOException;
import java.util.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.TextParser;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
new AccessControlEntry(new File("someFile2"), AccessControlAccount.forAll(), EnumSet.of(AccessPermissions.GrantRead), AccessControlScope.Global)))},
};
}
@Test(dataProvider = "getAclCases")
public void shouldGetAcl(
@Nullable final String isDefaultsAclEnabledStr,
@NotNull final String profile,
@Nullable final String agentAclStr,
@Nullable final AccessControlList agentAcl,
@Nullable final String profileAclStr,
@Nullable final AccessControlList profileAcl) throws IOException {
// Given
final String username = "user";
final File work = new File("work");
final File tools = new File("tools");
final File plugins = new File("plugins");
final File lib = new File("lib");
final File config = new File("config");
final File log = new File("log");
final File checkout = new File("checkout");
final File system = new File("system");
final File agentTemp = new File("agentTemp");
final File buildTemp = new File("buildTemp");
final File globalTemp = new File("globalTemp");
UserCredentials userCredentials = new UserCredentials(
profile,
username,
"password78",
WindowsIntegrityLevel.High, | LoggingLevel.Debug, |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/AccessControlListProviderTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
| import org.testng.annotations.Test;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL_DEFAULTS_ENABLED;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.io.IOException;
import java.util.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.TextParser;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider; | @Nullable final String agentAclStr,
@Nullable final AccessControlList agentAcl,
@Nullable final String profileAclStr,
@Nullable final AccessControlList profileAcl) throws IOException {
// Given
final String username = "user";
final File work = new File("work");
final File tools = new File("tools");
final File plugins = new File("plugins");
final File lib = new File("lib");
final File config = new File("config");
final File log = new File("log");
final File checkout = new File("checkout");
final File system = new File("system");
final File agentTemp = new File("agentTemp");
final File buildTemp = new File("buildTemp");
final File globalTemp = new File("globalTemp");
UserCredentials userCredentials = new UserCredentials(
profile,
username,
"password78",
WindowsIntegrityLevel.High,
LoggingLevel.Debug,
Arrays.asList(new CommandLineArgument("arg1", CommandLineArgument.Type.PARAMETER), new CommandLineArgument("arg2", CommandLineArgument.Type.PARAMETER)));
myCtx.checking(new Expectations() {{
configureExpectations();
}
void configureExpectations() { | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/AccessControlListProviderTest.java
import org.testng.annotations.Test;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL_DEFAULTS_ENABLED;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.io.IOException;
import java.util.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.TextParser;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
@Nullable final String agentAclStr,
@Nullable final AccessControlList agentAcl,
@Nullable final String profileAclStr,
@Nullable final AccessControlList profileAcl) throws IOException {
// Given
final String username = "user";
final File work = new File("work");
final File tools = new File("tools");
final File plugins = new File("plugins");
final File lib = new File("lib");
final File config = new File("config");
final File log = new File("log");
final File checkout = new File("checkout");
final File system = new File("system");
final File agentTemp = new File("agentTemp");
final File buildTemp = new File("buildTemp");
final File globalTemp = new File("globalTemp");
UserCredentials userCredentials = new UserCredentials(
profile,
username,
"password78",
WindowsIntegrityLevel.High,
LoggingLevel.Debug,
Arrays.asList(new CommandLineArgument("arg1", CommandLineArgument.Type.PARAMETER), new CommandLineArgument("arg2", CommandLineArgument.Type.PARAMETER)));
myCtx.checking(new Expectations() {{
configureExpectations();
}
void configureExpectations() { | one(myAgentParametersService).tryGetConfigParameter(RUN_AS_ACL_DEFAULTS_ENABLED); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/AccessControlListProviderTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
| import org.testng.annotations.Test;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL_DEFAULTS_ENABLED;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.io.IOException;
import java.util.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.TextParser;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider; | allowing(myPathsService).getPath(WellKnownPaths.Tools);
will(returnValue(tools));
allowing(myPathsService).getPath(WellKnownPaths.Plugins);
will(returnValue(plugins));
allowing(myPathsService).getPath(WellKnownPaths.Lib);
will(returnValue(lib));
allowing(myPathsService).getPath(WellKnownPaths.Config);
will(returnValue(config));
allowing(myPathsService).getPath(WellKnownPaths.Log);
will(returnValue(log));
allowing(myPathsService).getPath(WellKnownPaths.Checkout);
will(returnValue(checkout));
allowing(myPathsService).getPath(WellKnownPaths.System);
will(returnValue(system));
allowing(myPathsService).getPath(WellKnownPaths.AgentTemp);
will(returnValue(agentTemp));
allowing(myPathsService).getPath(WellKnownPaths.BuildTemp);
will(returnValue(buildTemp));
allowing(myPathsService).getPath(WellKnownPaths.GlobalTemp);
will(returnValue(globalTemp));
| // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/AccessControlListProviderTest.java
import org.testng.annotations.Test;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_ACL_DEFAULTS_ENABLED;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.io.IOException;
import java.util.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.TextParser;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
allowing(myPathsService).getPath(WellKnownPaths.Tools);
will(returnValue(tools));
allowing(myPathsService).getPath(WellKnownPaths.Plugins);
will(returnValue(plugins));
allowing(myPathsService).getPath(WellKnownPaths.Lib);
will(returnValue(lib));
allowing(myPathsService).getPath(WellKnownPaths.Config);
will(returnValue(config));
allowing(myPathsService).getPath(WellKnownPaths.Log);
will(returnValue(log));
allowing(myPathsService).getPath(WellKnownPaths.Checkout);
will(returnValue(checkout));
allowing(myPathsService).getPath(WellKnownPaths.System);
will(returnValue(system));
allowing(myPathsService).getPath(WellKnownPaths.AgentTemp);
will(returnValue(agentTemp));
allowing(myPathsService).getPath(WellKnownPaths.BuildTemp);
will(returnValue(buildTemp));
allowing(myPathsService).getPath(WellKnownPaths.GlobalTemp);
will(returnValue(globalTemp));
| allowing(myAgentParametersService).tryGetConfigParameter(RUN_AS_ACL); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/RunAsLoggerTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
| import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_LOG_ENABLED;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.util.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; | "true",
new String[] {
"Starting: tool cred cmd abc",
"as user: username",
"Starting: origTool arg1",
"in directory: CheckoutDirectory" }
},
// when log is disabled
{
"false",
new String[] {
"Starting: origTool arg1",
"in directory: CheckoutDirectory" }
},
// when log is disabled by default
{
null,
new String[] {
"Starting: origTool arg1",
"in directory: CheckoutDirectory" }
}
};
}
@Test(dataProvider = "getLogRunAsCases")
public void shouldLogRunAs(@Nullable final String isLogEnabledConfigParamValue, @NotNull final String[] expectedLogLines) {
// Given
final String password = "abc"; | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/RunAsLoggerTest.java
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_LOG_ENABLED;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.util.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
"true",
new String[] {
"Starting: tool cred cmd abc",
"as user: username",
"Starting: origTool arg1",
"in directory: CheckoutDirectory" }
},
// when log is disabled
{
"false",
new String[] {
"Starting: origTool arg1",
"in directory: CheckoutDirectory" }
},
// when log is disabled by default
{
null,
new String[] {
"Starting: origTool arg1",
"in directory: CheckoutDirectory" }
}
};
}
@Test(dataProvider = "getLogRunAsCases")
public void shouldLogRunAs(@Nullable final String isLogEnabledConfigParamValue, @NotNull final String[] expectedLogLines) {
// Given
final String password = "abc"; | final UserCredentials userCredentials = new UserCredentials("", "username", password, WindowsIntegrityLevel.Auto, LoggingLevel.Normal, Collections.<CommandLineArgument>emptyList()); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/RunAsLoggerTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
| import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_LOG_ENABLED;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.util.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; | "true",
new String[] {
"Starting: tool cred cmd abc",
"as user: username",
"Starting: origTool arg1",
"in directory: CheckoutDirectory" }
},
// when log is disabled
{
"false",
new String[] {
"Starting: origTool arg1",
"in directory: CheckoutDirectory" }
},
// when log is disabled by default
{
null,
new String[] {
"Starting: origTool arg1",
"in directory: CheckoutDirectory" }
}
};
}
@Test(dataProvider = "getLogRunAsCases")
public void shouldLogRunAs(@Nullable final String isLogEnabledConfigParamValue, @NotNull final String[] expectedLogLines) {
// Given
final String password = "abc"; | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/RunAsLoggerTest.java
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_LOG_ENABLED;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.util.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
"true",
new String[] {
"Starting: tool cred cmd abc",
"as user: username",
"Starting: origTool arg1",
"in directory: CheckoutDirectory" }
},
// when log is disabled
{
"false",
new String[] {
"Starting: origTool arg1",
"in directory: CheckoutDirectory" }
},
// when log is disabled by default
{
null,
new String[] {
"Starting: origTool arg1",
"in directory: CheckoutDirectory" }
}
};
}
@Test(dataProvider = "getLogRunAsCases")
public void shouldLogRunAs(@Nullable final String isLogEnabledConfigParamValue, @NotNull final String[] expectedLogLines) {
// Given
final String password = "abc"; | final UserCredentials userCredentials = new UserCredentials("", "username", password, WindowsIntegrityLevel.Auto, LoggingLevel.Normal, Collections.<CommandLineArgument>emptyList()); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/RunAsLoggerTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
| import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_LOG_ENABLED;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.util.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; | "in directory: CheckoutDirectory" }
}
};
}
@Test(dataProvider = "getLogRunAsCases")
public void shouldLogRunAs(@Nullable final String isLogEnabledConfigParamValue, @NotNull final String[] expectedLogLines) {
// Given
final String password = "abc";
final UserCredentials userCredentials = new UserCredentials("", "username", password, WindowsIntegrityLevel.Auto, LoggingLevel.Normal, Collections.<CommandLineArgument>emptyList());
final File checkoutDirectory = new File("CheckoutDirectory");
final ArrayList<String> logMessages = new ArrayList<String>();
final CommandLineSetup baseCommandLineSetup = new CommandLineSetup(
"origTool",
Arrays.asList(
new CommandLineArgument("arg1", CommandLineArgument.Type.PARAMETER)),
Arrays.asList(
myCommandLineResource1));
final CommandLineSetup runAsCommandLineSetup = new CommandLineSetup(
"tool",
Arrays.asList(
new CommandLineArgument("cred", CommandLineArgument.Type.PARAMETER),
new CommandLineArgument("cmd", CommandLineArgument.Type.PARAMETER),
new CommandLineArgument(password, CommandLineArgument.Type.PARAMETER)),
Arrays.asList(
myCommandLineResource1,
myCommandLineResource2));
myCtx.checking(new Expectations() {{ | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/RunAsLoggerTest.java
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_LOG_ENABLED;
import static org.assertj.core.api.BDDAssertions.then;
import java.io.File;
import java.util.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
"in directory: CheckoutDirectory" }
}
};
}
@Test(dataProvider = "getLogRunAsCases")
public void shouldLogRunAs(@Nullable final String isLogEnabledConfigParamValue, @NotNull final String[] expectedLogLines) {
// Given
final String password = "abc";
final UserCredentials userCredentials = new UserCredentials("", "username", password, WindowsIntegrityLevel.Auto, LoggingLevel.Normal, Collections.<CommandLineArgument>emptyList());
final File checkoutDirectory = new File("CheckoutDirectory");
final ArrayList<String> logMessages = new ArrayList<String>();
final CommandLineSetup baseCommandLineSetup = new CommandLineSetup(
"origTool",
Arrays.asList(
new CommandLineArgument("arg1", CommandLineArgument.Type.PARAMETER)),
Arrays.asList(
myCommandLineResource1));
final CommandLineSetup runAsCommandLineSetup = new CommandLineSetup(
"tool",
Arrays.asList(
new CommandLineArgument("cred", CommandLineArgument.Type.PARAMETER),
new CommandLineArgument("cmd", CommandLineArgument.Type.PARAMETER),
new CommandLineArgument(password, CommandLineArgument.Type.PARAMETER)),
Arrays.asList(
myCommandLineResource1,
myCommandLineResource2));
myCtx.checking(new Expectations() {{ | oneOf(myRunnerParametersService).tryGetConfigParameter(RUN_AS_LOG_ENABLED); |
JetBrains/teamcity-runas-plugin | runAs-server/src/main/java/jetbrains/buildServer/runAs/server/RunAsBuildFeature.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
| import java.util.*;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.serverSide.BuildFeature;
import jetbrains.buildServer.serverSide.InvalidProperty;
import jetbrains.buildServer.serverSide.PropertiesProcessor;
import jetbrains.buildServer.util.CollectionsUtil;
import jetbrains.buildServer.web.openapi.PluginDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import static com.intellij.openapi.util.text.StringUtil.isEmpty; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.server;
public class RunAsBuildFeature extends BuildFeature {
private static final Map<String, String> OurDefaultRunnerProperties = CollectionsUtil.asMap(
RunAsBean.Shared.getAdditionalCommandLineParametersKey(), null,
RunAsBean.Shared.getWindowsIntegrityLevelKey(), RunAsBean.Shared.getWindowsIntegrityLevels().get(0).getValue(),
RunAsBean.Shared.getWindowsLoggingLevelKey(), RunAsBean.Shared.getLoggingLevels().get(0).getValue()
);
private final String myEditUrl;
private final RunAsBean myBean;
@Autowired
public RunAsBuildFeature(
@NotNull final RunAsBean bean,
@NotNull final PluginDescriptor descriptor) {
myBean = bean;
myEditUrl = descriptor.getPluginResourcesPath("runAsBuildFeature.jsp");
}
@NotNull
@Override
public String getType() { | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
// Path: runAs-server/src/main/java/jetbrains/buildServer/runAs/server/RunAsBuildFeature.java
import java.util.*;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.serverSide.BuildFeature;
import jetbrains.buildServer.serverSide.InvalidProperty;
import jetbrains.buildServer.serverSide.PropertiesProcessor;
import jetbrains.buildServer.util.CollectionsUtil;
import jetbrains.buildServer.web.openapi.PluginDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import static com.intellij.openapi.util.text.StringUtil.isEmpty;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.server;
public class RunAsBuildFeature extends BuildFeature {
private static final Map<String, String> OurDefaultRunnerProperties = CollectionsUtil.asMap(
RunAsBean.Shared.getAdditionalCommandLineParametersKey(), null,
RunAsBean.Shared.getWindowsIntegrityLevelKey(), RunAsBean.Shared.getWindowsIntegrityLevels().get(0).getValue(),
RunAsBean.Shared.getWindowsLoggingLevelKey(), RunAsBean.Shared.getLoggingLevels().get(0).getValue()
);
private final String myEditUrl;
private final RunAsBean myBean;
@Autowired
public RunAsBuildFeature(
@NotNull final RunAsBean bean,
@NotNull final PluginDescriptor descriptor) {
myBean = bean;
myEditUrl = descriptor.getPluginResourcesPath("runAsBuildFeature.jsp");
}
@NotNull
@Override
public String getType() { | return Constants.BUILD_FEATURE_TYPE; |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/LinuxSettingsGeneratorTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import java.util.Arrays;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.ResourceGenerator;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class LinuxSettingsGeneratorTest {
private Mockery myCtx;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
}
@Test()
public void shouldGenerateContent() {
// Given
final String expectedContent = "nik";
final List<CommandLineArgument> additionalArgs = Arrays.asList(new CommandLineArgument("arg1", CommandLineArgument.Type.PARAMETER), new CommandLineArgument("arg 2", CommandLineArgument.Type.PARAMETER));
final ResourceGenerator<UserCredentials> instance = createInstance();
// When | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/LinuxSettingsGeneratorTest.java
import java.util.Arrays;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.ResourceGenerator;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class LinuxSettingsGeneratorTest {
private Mockery myCtx;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
}
@Test()
public void shouldGenerateContent() {
// Given
final String expectedContent = "nik";
final List<CommandLineArgument> additionalArgs = Arrays.asList(new CommandLineArgument("arg1", CommandLineArgument.Type.PARAMETER), new CommandLineArgument("arg 2", CommandLineArgument.Type.PARAMETER));
final ResourceGenerator<UserCredentials> instance = createInstance();
// When | final String content = instance.create(new UserCredentials("", "nik", "aaa", WindowsIntegrityLevel.Auto, LoggingLevel.Off, additionalArgs)); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/LinuxSettingsGeneratorTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import java.util.Arrays;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.ResourceGenerator;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class LinuxSettingsGeneratorTest {
private Mockery myCtx;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
}
@Test()
public void shouldGenerateContent() {
// Given
final String expectedContent = "nik";
final List<CommandLineArgument> additionalArgs = Arrays.asList(new CommandLineArgument("arg1", CommandLineArgument.Type.PARAMETER), new CommandLineArgument("arg 2", CommandLineArgument.Type.PARAMETER));
final ResourceGenerator<UserCredentials> instance = createInstance();
// When | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/LinuxSettingsGeneratorTest.java
import java.util.Arrays;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.ResourceGenerator;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class LinuxSettingsGeneratorTest {
private Mockery myCtx;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
}
@Test()
public void shouldGenerateContent() {
// Given
final String expectedContent = "nik";
final List<CommandLineArgument> additionalArgs = Arrays.asList(new CommandLineArgument("arg1", CommandLineArgument.Type.PARAMETER), new CommandLineArgument("arg 2", CommandLineArgument.Type.PARAMETER));
final ResourceGenerator<UserCredentials> instance = createInstance();
// When | final String content = instance.create(new UserCredentials("", "nik", "aaa", WindowsIntegrityLevel.Auto, LoggingLevel.Off, additionalArgs)); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/WindowsFileAccessServiceTest.java | // Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/Constants.java
// @SuppressWarnings("SpellCheckingInspection")
// public static final String ICACLS_TOOL_NAME = "ICACLS";
| import com.intellij.execution.ExecutionException;
import java.io.File;
import java.util.*;
import java.util.Arrays;
import java.util.Collections;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineResource;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineSetup;
import jetbrains.buildServer.util.*;
import jetbrains.buildServer.util.Converter;
import org.assertj.core.util.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static jetbrains.buildServer.runAs.agent.Constants.ICACLS_TOOL_NAME;
import static org.assertj.core.api.BDDAssertions.then; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class WindowsFileAccessServiceTest {
private Mockery myCtx;
private CommandLineExecutor myCommandLineExecutor;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
myCommandLineExecutor = myCtx.mock(CommandLineExecutor.class);
}
@DataProvider(name = "getSetPermissionsForWindowsCases")
public Object[][] getSetPermissionsForWindowsCases() {
return new Object[][] {
// full access
{
new AccessControlList(Arrays.asList(
new AccessControlEntry(new File("my_file"), AccessControlAccount.forUser("user1"), EnumSet.of(AccessPermissions.GrantRead, AccessPermissions.GrantWrite, AccessPermissions.GrantExecute), AccessControlScope.Step))),
0,
null,
Arrays.asList( | // Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/Constants.java
// @SuppressWarnings("SpellCheckingInspection")
// public static final String ICACLS_TOOL_NAME = "ICACLS";
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/WindowsFileAccessServiceTest.java
import com.intellij.execution.ExecutionException;
import java.io.File;
import java.util.*;
import java.util.Arrays;
import java.util.Collections;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineResource;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineSetup;
import jetbrains.buildServer.util.*;
import jetbrains.buildServer.util.Converter;
import org.assertj.core.util.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static jetbrains.buildServer.runAs.agent.Constants.ICACLS_TOOL_NAME;
import static org.assertj.core.api.BDDAssertions.then;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class WindowsFileAccessServiceTest {
private Mockery myCtx;
private CommandLineExecutor myCommandLineExecutor;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
myCommandLineExecutor = myCtx.mock(CommandLineExecutor.class);
}
@DataProvider(name = "getSetPermissionsForWindowsCases")
public Object[][] getSetPermissionsForWindowsCases() {
return new Object[][] {
// full access
{
new AccessControlList(Arrays.asList(
new AccessControlEntry(new File("my_file"), AccessControlAccount.forUser("user1"), EnumSet.of(AccessPermissions.GrantRead, AccessPermissions.GrantWrite, AccessPermissions.GrantExecute), AccessControlScope.Step))),
0,
null,
Arrays.asList( | new CommandLineSetup(ICACLS_TOOL_NAME, Arrays.asList( |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/UserCredentialsServiceTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then; | }
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
myAgentParametersService = myCtx.mock(AgentParametersService.class);
myParametersService = myCtx.mock(ParametersService.class);
myProfileParametersService = myCtx.mock(ProfileParametersService.class);
myCommandLineArgumentsService = myCtx.mock(CommandLineArgumentsService.class);
//noinspection unchecked
myFileAccessParser = (TextParser<AccessControlList>)myCtx.mock(TextParser.class);
}
@DataProvider(name = "getUserCredentialsCases")
public Object[][] getUserCredentialsCases() {
return new Object[][] {
// Default && ret null
{
new HashMap<String, String>(),
new HashMap<String, String>(),
new HashMap<String, HashMap<String, String>>(),
null,
null
},
// Predefined && ret null
{
new HashMap<String, String>(),
new HashMap<String, String>() {{ | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/UserCredentialsServiceTest.java
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
}
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
myAgentParametersService = myCtx.mock(AgentParametersService.class);
myParametersService = myCtx.mock(ParametersService.class);
myProfileParametersService = myCtx.mock(ProfileParametersService.class);
myCommandLineArgumentsService = myCtx.mock(CommandLineArgumentsService.class);
//noinspection unchecked
myFileAccessParser = (TextParser<AccessControlList>)myCtx.mock(TextParser.class);
}
@DataProvider(name = "getUserCredentialsCases")
public Object[][] getUserCredentialsCases() {
return new Object[][] {
// Default && ret null
{
new HashMap<String, String>(),
new HashMap<String, String>(),
new HashMap<String, HashMap<String, String>>(),
null,
null
},
// Predefined && ret null
{
new HashMap<String, String>(),
new HashMap<String, String>() {{ | put(Constants.ALLOW_PROFILE_ID_FROM_SERVER, "true"); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/UserCredentialsServiceTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then; |
// Predefined && ret null
{
new HashMap<String, String>(),
new HashMap<String, String>() {{
put(Constants.ALLOW_PROFILE_ID_FROM_SERVER, "true");
put(Constants.ALLOW_CUSTOM_CREDENTIALS, "false");
}},
new HashMap<String, HashMap<String, String>>(),
null,
"RunAs user must be defined for \"" + UserCredentialsServiceImpl.DEFAULT_PROFILE + "\""
},
// Predefined credentials
{
new HashMap<String, String>() {{
put(Constants.USER, "user1");
put(Constants.PASSWORD, "password1");
}},
new HashMap<String, String>() {{
put(Constants.ALLOW_PROFILE_ID_FROM_SERVER, "true");
put(Constants.ALLOW_CUSTOM_CREDENTIALS, "false");
put(Constants.CREDENTIALS_PROFILE_ID, "user2cred");
}},
new HashMap<String, HashMap<String, String>>() {{
put("user2cred", new HashMap<String, String>() {{
put(Constants.USER, "user2");
put(Constants.CONFIG_PASSWORD, "password2");
}});
}}, | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/UserCredentialsServiceTest.java
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
// Predefined && ret null
{
new HashMap<String, String>(),
new HashMap<String, String>() {{
put(Constants.ALLOW_PROFILE_ID_FROM_SERVER, "true");
put(Constants.ALLOW_CUSTOM_CREDENTIALS, "false");
}},
new HashMap<String, HashMap<String, String>>(),
null,
"RunAs user must be defined for \"" + UserCredentialsServiceImpl.DEFAULT_PROFILE + "\""
},
// Predefined credentials
{
new HashMap<String, String>() {{
put(Constants.USER, "user1");
put(Constants.PASSWORD, "password1");
}},
new HashMap<String, String>() {{
put(Constants.ALLOW_PROFILE_ID_FROM_SERVER, "true");
put(Constants.ALLOW_CUSTOM_CREDENTIALS, "false");
put(Constants.CREDENTIALS_PROFILE_ID, "user2cred");
}},
new HashMap<String, HashMap<String, String>>() {{
put("user2cred", new HashMap<String, String>() {{
put(Constants.USER, "user2");
put(Constants.CONFIG_PASSWORD, "password2");
}});
}}, | new UserCredentials("user2cred", "user2", "password2", WindowsIntegrityLevel.Auto, LoggingLevel.Off, Arrays.<CommandLineArgument>asList()), |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/UserCredentialsServiceTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then; |
// Predefined && ret null
{
new HashMap<String, String>(),
new HashMap<String, String>() {{
put(Constants.ALLOW_PROFILE_ID_FROM_SERVER, "true");
put(Constants.ALLOW_CUSTOM_CREDENTIALS, "false");
}},
new HashMap<String, HashMap<String, String>>(),
null,
"RunAs user must be defined for \"" + UserCredentialsServiceImpl.DEFAULT_PROFILE + "\""
},
// Predefined credentials
{
new HashMap<String, String>() {{
put(Constants.USER, "user1");
put(Constants.PASSWORD, "password1");
}},
new HashMap<String, String>() {{
put(Constants.ALLOW_PROFILE_ID_FROM_SERVER, "true");
put(Constants.ALLOW_CUSTOM_CREDENTIALS, "false");
put(Constants.CREDENTIALS_PROFILE_ID, "user2cred");
}},
new HashMap<String, HashMap<String, String>>() {{
put("user2cred", new HashMap<String, String>() {{
put(Constants.USER, "user2");
put(Constants.CONFIG_PASSWORD, "password2");
}});
}}, | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/UserCredentialsServiceTest.java
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import jetbrains.buildServer.dotNet.buildRunner.agent.*;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
// Predefined && ret null
{
new HashMap<String, String>(),
new HashMap<String, String>() {{
put(Constants.ALLOW_PROFILE_ID_FROM_SERVER, "true");
put(Constants.ALLOW_CUSTOM_CREDENTIALS, "false");
}},
new HashMap<String, HashMap<String, String>>(),
null,
"RunAs user must be defined for \"" + UserCredentialsServiceImpl.DEFAULT_PROFILE + "\""
},
// Predefined credentials
{
new HashMap<String, String>() {{
put(Constants.USER, "user1");
put(Constants.PASSWORD, "password1");
}},
new HashMap<String, String>() {{
put(Constants.ALLOW_PROFILE_ID_FROM_SERVER, "true");
put(Constants.ALLOW_CUSTOM_CREDENTIALS, "false");
put(Constants.CREDENTIALS_PROFILE_ID, "user2cred");
}},
new HashMap<String, HashMap<String, String>>() {{
put("user2cred", new HashMap<String, String>() {{
put(Constants.USER, "user2");
put(Constants.CONFIG_PASSWORD, "password2");
}});
}}, | new UserCredentials("user2cred", "user2", "password2", WindowsIntegrityLevel.Auto, LoggingLevel.Off, Arrays.<CommandLineArgument>asList()), |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/UserCredentialsServiceImpl.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.dotNet.buildRunner.agent.BuildStartException;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgumentsService;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class UserCredentialsServiceImpl implements UserCredentialsService {
static final String DEFAULT_PROFILE = "default";
private static final Logger LOG = Logger.getInstance(UserCredentialsServiceImpl.class.getName());
private final ParametersService myParametersService;
private final ProfileParametersService myProfileParametersService;
private final CommandLineArgumentsService myCommandLineArgumentsService;
public UserCredentialsServiceImpl(
@NotNull final ParametersService parametersService,
@NotNull final ProfileParametersService profileParametersService,
@NotNull final CommandLineArgumentsService commandLineArgumentsService) {
myParametersService = parametersService;
myProfileParametersService = profileParametersService;
myCommandLineArgumentsService = commandLineArgumentsService;
}
@Nullable
@Override
public UserCredentials tryGetUserCredentials() { | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/UserCredentialsServiceImpl.java
import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.dotNet.buildRunner.agent.BuildStartException;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgumentsService;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class UserCredentialsServiceImpl implements UserCredentialsService {
static final String DEFAULT_PROFILE = "default";
private static final Logger LOG = Logger.getInstance(UserCredentialsServiceImpl.class.getName());
private final ParametersService myParametersService;
private final ProfileParametersService myProfileParametersService;
private final CommandLineArgumentsService myCommandLineArgumentsService;
public UserCredentialsServiceImpl(
@NotNull final ParametersService parametersService,
@NotNull final ProfileParametersService profileParametersService,
@NotNull final CommandLineArgumentsService commandLineArgumentsService) {
myParametersService = parametersService;
myProfileParametersService = profileParametersService;
myCommandLineArgumentsService = commandLineArgumentsService;
}
@Nullable
@Override
public UserCredentials tryGetUserCredentials() { | final boolean allowCustomCredentials = ParameterUtils.parseBoolean(myParametersService.tryGetConfigParameter(Constants.ALLOW_CUSTOM_CREDENTIALS), true); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/UserCredentialsServiceImpl.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.dotNet.buildRunner.agent.BuildStartException;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgumentsService;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | final String userName;
final String password;
userName = tryGetFirstNotEmpty(myProfileParametersService.tryGetProperty(profileName, Constants.USER));
if(StringUtil.isEmptyOrSpaces(userName)) {
if(trowException) {
throw new BuildStartException("RunAs user must be defined for \"" + profileName + "\"");
}
else {
return null;
}
}
password = tryGetFirstNotEmpty(myProfileParametersService.tryGetProperty(profileName, Constants.PASSWORD), myProfileParametersService.tryGetProperty(profileName, Constants.CONFIG_PASSWORD));
if(StringUtil.isEmptyOrSpaces(password)) {
if(trowException) {
throw new BuildStartException("RunAs password must be defined for \"" + profileName + "\"");
}
else {
return null;
}
}
return createCredentials(profileName, userName, password, true);
}
@NotNull
private UserCredentials createCredentials(@NotNull final String profileName, @NotNull final String userName, @NotNull final String password, boolean isPredefined)
{
// Get parameters | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/UserCredentialsServiceImpl.java
import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.dotNet.buildRunner.agent.BuildStartException;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgumentsService;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
final String userName;
final String password;
userName = tryGetFirstNotEmpty(myProfileParametersService.tryGetProperty(profileName, Constants.USER));
if(StringUtil.isEmptyOrSpaces(userName)) {
if(trowException) {
throw new BuildStartException("RunAs user must be defined for \"" + profileName + "\"");
}
else {
return null;
}
}
password = tryGetFirstNotEmpty(myProfileParametersService.tryGetProperty(profileName, Constants.PASSWORD), myProfileParametersService.tryGetProperty(profileName, Constants.CONFIG_PASSWORD));
if(StringUtil.isEmptyOrSpaces(password)) {
if(trowException) {
throw new BuildStartException("RunAs password must be defined for \"" + profileName + "\"");
}
else {
return null;
}
}
return createCredentials(profileName, userName, password, true);
}
@NotNull
private UserCredentials createCredentials(@NotNull final String profileName, @NotNull final String userName, @NotNull final String password, boolean isPredefined)
{
// Get parameters | final WindowsIntegrityLevel windowsIntegrityLevel = WindowsIntegrityLevel.tryParse(getParam(profileName, Constants.WINDOWS_INTEGRITY_LEVEL, isPredefined)); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/UserCredentialsServiceImpl.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.dotNet.buildRunner.agent.BuildStartException;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgumentsService;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | final String password;
userName = tryGetFirstNotEmpty(myProfileParametersService.tryGetProperty(profileName, Constants.USER));
if(StringUtil.isEmptyOrSpaces(userName)) {
if(trowException) {
throw new BuildStartException("RunAs user must be defined for \"" + profileName + "\"");
}
else {
return null;
}
}
password = tryGetFirstNotEmpty(myProfileParametersService.tryGetProperty(profileName, Constants.PASSWORD), myProfileParametersService.tryGetProperty(profileName, Constants.CONFIG_PASSWORD));
if(StringUtil.isEmptyOrSpaces(password)) {
if(trowException) {
throw new BuildStartException("RunAs password must be defined for \"" + profileName + "\"");
}
else {
return null;
}
}
return createCredentials(profileName, userName, password, true);
}
@NotNull
private UserCredentials createCredentials(@NotNull final String profileName, @NotNull final String userName, @NotNull final String password, boolean isPredefined)
{
// Get parameters
final WindowsIntegrityLevel windowsIntegrityLevel = WindowsIntegrityLevel.tryParse(getParam(profileName, Constants.WINDOWS_INTEGRITY_LEVEL, isPredefined)); | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/UserCredentialsServiceImpl.java
import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.dotNet.buildRunner.agent.BuildStartException;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgumentsService;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
final String password;
userName = tryGetFirstNotEmpty(myProfileParametersService.tryGetProperty(profileName, Constants.USER));
if(StringUtil.isEmptyOrSpaces(userName)) {
if(trowException) {
throw new BuildStartException("RunAs user must be defined for \"" + profileName + "\"");
}
else {
return null;
}
}
password = tryGetFirstNotEmpty(myProfileParametersService.tryGetProperty(profileName, Constants.PASSWORD), myProfileParametersService.tryGetProperty(profileName, Constants.CONFIG_PASSWORD));
if(StringUtil.isEmptyOrSpaces(password)) {
if(trowException) {
throw new BuildStartException("RunAs password must be defined for \"" + profileName + "\"");
}
else {
return null;
}
}
return createCredentials(profileName, userName, password, true);
}
@NotNull
private UserCredentials createCredentials(@NotNull final String profileName, @NotNull final String userName, @NotNull final String password, boolean isPredefined)
{
// Get parameters
final WindowsIntegrityLevel windowsIntegrityLevel = WindowsIntegrityLevel.tryParse(getParam(profileName, Constants.WINDOWS_INTEGRITY_LEVEL, isPredefined)); | final LoggingLevel loggingLevel = LoggingLevel.tryParse(getParam(profileName, Constants.LOGGING_LEVEL, isPredefined)); |
JetBrains/teamcity-runas-plugin | runAs-server/src/main/java/jetbrains/buildServer/runAs/server/RunAsBuildStartContextProcessor.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
| import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.serverSide.BuildStartContext;
import jetbrains.buildServer.serverSide.BuildStartContextProcessor;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.server;
public class RunAsBuildStartContextProcessor implements BuildStartContextProcessor {
private final RunAsConfiguration myRunAsConfiguration;
public RunAsBuildStartContextProcessor(@NotNull final RunAsConfiguration runAsConfiguration) {
myRunAsConfiguration = runAsConfiguration;
}
@Override
public void updateParameters(@NotNull final BuildStartContext buildStartContext) { | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
// Path: runAs-server/src/main/java/jetbrains/buildServer/runAs/server/RunAsBuildStartContextProcessor.java
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.serverSide.BuildStartContext;
import jetbrains.buildServer.serverSide.BuildStartContextProcessor;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.server;
public class RunAsBuildStartContextProcessor implements BuildStartContextProcessor {
private final RunAsConfiguration myRunAsConfiguration;
public RunAsBuildStartContextProcessor(@NotNull final RunAsConfiguration runAsConfiguration) {
myRunAsConfiguration = runAsConfiguration;
}
@Override
public void updateParameters(@NotNull final BuildStartContext buildStartContext) { | buildStartContext.addSharedParameter(Constants.RUN_AS_UI_ENABLED, Boolean.toString(myRunAsConfiguration.getIsUiSupported())); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/UserCredentials.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import java.util.HashMap;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class UserCredentials {
@NotNull private final String myProfile;
@NotNull private final String myUser;
@NotNull private final String myPassword; | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/UserCredentials.java
import java.util.HashMap;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class UserCredentials {
@NotNull private final String myProfile;
@NotNull private final String myUser;
@NotNull private final String myPassword; | @NotNull private final WindowsIntegrityLevel myWindowsIntegrityLevel; |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/UserCredentials.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import java.util.HashMap;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class UserCredentials {
@NotNull private final String myProfile;
@NotNull private final String myUser;
@NotNull private final String myPassword;
@NotNull private final WindowsIntegrityLevel myWindowsIntegrityLevel; | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/UserCredentials.java
import java.util.HashMap;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class UserCredentials {
@NotNull private final String myProfile;
@NotNull private final String myUser;
@NotNull private final String myPassword;
@NotNull private final WindowsIntegrityLevel myWindowsIntegrityLevel; | @NotNull private final LoggingLevel myLoggingLevel; |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/ParametersServiceTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
| import static org.assertj.core.api.BDDAssertions.then;
import java.io.IOException;
import java.util.HashMap;
import jetbrains.buildServer.dotNet.buildRunner.agent.RunnerParametersService;
import jetbrains.buildServer.runAs.common.Constants;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class ParametersServiceTest{
private Mockery myCtx;
private RunnerParametersService myRunnerParametersService;
private BuildFeatureParametersService myBuildFeatureParametersService;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
myRunnerParametersService = myCtx.mock(RunnerParametersService.class);
myBuildFeatureParametersService = myCtx.mock(BuildFeatureParametersService.class);
}
@DataProvider(name = "getParamCases")
public Object[][] getParamCases() {
return new Object[][] {
// from buildFeature
{
new HashMap<String, String>(), | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/ParametersServiceTest.java
import static org.assertj.core.api.BDDAssertions.then;
import java.io.IOException;
import java.util.HashMap;
import jetbrains.buildServer.dotNet.buildRunner.agent.RunnerParametersService;
import jetbrains.buildServer.runAs.common.Constants;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class ParametersServiceTest{
private Mockery myCtx;
private RunnerParametersService myRunnerParametersService;
private BuildFeatureParametersService myBuildFeatureParametersService;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
myRunnerParametersService = myCtx.mock(RunnerParametersService.class);
myBuildFeatureParametersService = myCtx.mock(BuildFeatureParametersService.class);
}
@DataProvider(name = "getParamCases")
public Object[][] getParamCases() {
return new Object[][] {
// from buildFeature
{
new HashMap<String, String>(), | new HashMap<String, String>() {{ put(Constants.USER, "user2"); put(Constants.CONFIG_PASSWORD, "password2"); }}, |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/WindowsFileAccessService.java | // Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/Constants.java
// @SuppressWarnings("SpellCheckingInspection")
// public static final String ICACLS_TOOL_NAME = "ICACLS";
| import static jetbrains.buildServer.runAs.agent.Constants.ICACLS_TOOL_NAME;
import com.intellij.execution.ExecutionException;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineResource;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineSetup;
import jetbrains.buildServer.util.*;
import org.jetbrains.annotations.NotNull; | grantedPermissionList.add("RX");
}
List<String> deniedPermissionList = new ArrayList<String>();
if(permissions.contains(AccessPermissions.DenyRead)) {
deniedPermissionList.add("R");
}
if(permissions.contains(AccessPermissions.DenyWrite)) {
deniedPermissionList.add("W,D,DC");
}
if(permissions.contains(AccessPermissions.DenyExecute)) {
deniedPermissionList.add("X");
}
if(grantedPermissionList.size() > 0) {
args.add(new CommandLineArgument("/grant", CommandLineArgument.Type.PARAMETER));
final boolean recursive = permissions.contains(AccessPermissions.Recursive);
final String permissionsStr = username + ":" + (recursive ? "(OI)(CI)" : "") + "(" + StringUtil.join(grantedPermissionList, ",") + ")";
args.add(new CommandLineArgument(permissionsStr, CommandLineArgument.Type.PARAMETER));
}
if(deniedPermissionList.size() > 0) {
args.add(new CommandLineArgument("/deny", CommandLineArgument.Type.PARAMETER));
final boolean recursive = permissions.contains(AccessPermissions.Recursive);
final String permissionsStr = username + ":" + (recursive ? "(OI)(CI)" : "") + "(" + StringUtil.join(deniedPermissionList, ",") + ")";
args.add(new CommandLineArgument(permissionsStr, CommandLineArgument.Type.PARAMETER));
}
| // Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/Constants.java
// @SuppressWarnings("SpellCheckingInspection")
// public static final String ICACLS_TOOL_NAME = "ICACLS";
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/WindowsFileAccessService.java
import static jetbrains.buildServer.runAs.agent.Constants.ICACLS_TOOL_NAME;
import com.intellij.execution.ExecutionException;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineResource;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineSetup;
import jetbrains.buildServer.util.*;
import org.jetbrains.annotations.NotNull;
grantedPermissionList.add("RX");
}
List<String> deniedPermissionList = new ArrayList<String>();
if(permissions.contains(AccessPermissions.DenyRead)) {
deniedPermissionList.add("R");
}
if(permissions.contains(AccessPermissions.DenyWrite)) {
deniedPermissionList.add("W,D,DC");
}
if(permissions.contains(AccessPermissions.DenyExecute)) {
deniedPermissionList.add("X");
}
if(grantedPermissionList.size() > 0) {
args.add(new CommandLineArgument("/grant", CommandLineArgument.Type.PARAMETER));
final boolean recursive = permissions.contains(AccessPermissions.Recursive);
final String permissionsStr = username + ":" + (recursive ? "(OI)(CI)" : "") + "(" + StringUtil.join(grantedPermissionList, ",") + ")";
args.add(new CommandLineArgument(permissionsStr, CommandLineArgument.Type.PARAMETER));
}
if(deniedPermissionList.size() > 0) {
args.add(new CommandLineArgument("/deny", CommandLineArgument.Type.PARAMETER));
final boolean recursive = permissions.contains(AccessPermissions.Recursive);
final String permissionsStr = username + ":" + (recursive ? "(OI)(CI)" : "") + "(" + StringUtil.join(deniedPermissionList, ",") + ")";
args.add(new CommandLineArgument(permissionsStr, CommandLineArgument.Type.PARAMETER));
}
| final CommandLineSetup icaclsCommandLineSetup = new CommandLineSetup(ICACLS_TOOL_NAME, args, Collections.<CommandLineResource>emptyList()); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/WindowsSettingsGeneratorTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import java.util.Arrays;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.ResourceGenerator;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class WindowsSettingsGeneratorTest {
private static final String ourlineSeparator = System.getProperty("line.separator");
private Mockery myCtx;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
}
@Test()
public void shouldGenerateContent() {
// Given
final String expectedContent = "-u:nik" + ourlineSeparator + "arg1" + ourlineSeparator + "arg 2";
final List<CommandLineArgument> additionalArgs = Arrays.asList(new CommandLineArgument("arg1", CommandLineArgument.Type.PARAMETER), new CommandLineArgument("arg 2", CommandLineArgument.Type.PARAMETER));
final ResourceGenerator<UserCredentials> instance = createInstance();
// When | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/WindowsSettingsGeneratorTest.java
import java.util.Arrays;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.ResourceGenerator;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class WindowsSettingsGeneratorTest {
private static final String ourlineSeparator = System.getProperty("line.separator");
private Mockery myCtx;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
}
@Test()
public void shouldGenerateContent() {
// Given
final String expectedContent = "-u:nik" + ourlineSeparator + "arg1" + ourlineSeparator + "arg 2";
final List<CommandLineArgument> additionalArgs = Arrays.asList(new CommandLineArgument("arg1", CommandLineArgument.Type.PARAMETER), new CommandLineArgument("arg 2", CommandLineArgument.Type.PARAMETER));
final ResourceGenerator<UserCredentials> instance = createInstance();
// When | final String content = instance.create(new UserCredentials("someprofile", "nik", "aaa", WindowsIntegrityLevel.Auto, LoggingLevel.Off, additionalArgs)); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/WindowsSettingsGeneratorTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
| import java.util.Arrays;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.ResourceGenerator;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class WindowsSettingsGeneratorTest {
private static final String ourlineSeparator = System.getProperty("line.separator");
private Mockery myCtx;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
}
@Test()
public void shouldGenerateContent() {
// Given
final String expectedContent = "-u:nik" + ourlineSeparator + "arg1" + ourlineSeparator + "arg 2";
final List<CommandLineArgument> additionalArgs = Arrays.asList(new CommandLineArgument("arg1", CommandLineArgument.Type.PARAMETER), new CommandLineArgument("arg 2", CommandLineArgument.Type.PARAMETER));
final ResourceGenerator<UserCredentials> instance = createInstance();
// When | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/LoggingLevel.java
// public enum LoggingLevel {
// Off("off", "Off"),
// Errors("errors", "Errors"),
// Normal("normal", "Normal"),
// Debug("debug", "Debug");
//
// private final String myValue;
// private final String myDescription;
//
// private LoggingLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static LoggingLevel tryParse(String value) {
// for (LoggingLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Off;
// }
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/WindowsIntegrityLevel.java
// public enum WindowsIntegrityLevel {
// Auto("auto", "Default"),
// Untrusted("untrusted", "Untrusted"),
// Low("low", "Low"),
// Medium("medium", "Medium"),
// MediumPlus("medium_plus", "Medium Plus"),
// High("high", "High");
//
// private final String myValue;
// private final String myDescription;
//
// private WindowsIntegrityLevel(String value, final String description) {
// myValue = value;
// myDescription = description;
// }
//
// public String getValue() {
// return myValue;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public static WindowsIntegrityLevel tryParse(String value) {
// for (WindowsIntegrityLevel v : values()) {
// if (v.getValue().equals(value)) return v;
// }
//
// return Auto;
// }
// }
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/WindowsSettingsGeneratorTest.java
import java.util.Arrays;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.ResourceGenerator;
import jetbrains.buildServer.runAs.common.LoggingLevel;
import jetbrains.buildServer.runAs.common.WindowsIntegrityLevel;
import org.jetbrains.annotations.NotNull;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class WindowsSettingsGeneratorTest {
private static final String ourlineSeparator = System.getProperty("line.separator");
private Mockery myCtx;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
}
@Test()
public void shouldGenerateContent() {
// Given
final String expectedContent = "-u:nik" + ourlineSeparator + "arg1" + ourlineSeparator + "arg 2";
final List<CommandLineArgument> additionalArgs = Arrays.asList(new CommandLineArgument("arg1", CommandLineArgument.Type.PARAMETER), new CommandLineArgument("arg 2", CommandLineArgument.Type.PARAMETER));
final ResourceGenerator<UserCredentials> instance = createInstance();
// When | final String content = instance.create(new UserCredentials("someprofile", "nik", "aaa", WindowsIntegrityLevel.Auto, LoggingLevel.Off, additionalArgs)); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/LinuxFileAccessServiceTest.java | // Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/Constants.java
// public static final String CHMOD_TOOL_NAME = "chmod";
| import com.intellij.execution.ExecutionException;
import java.io.File;
import java.util.*;
import java.util.Arrays;
import java.util.Collections;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineResource;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineSetup;
import jetbrains.buildServer.util.*;
import jetbrains.buildServer.util.Converter;
import org.assertj.core.util.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static jetbrains.buildServer.runAs.agent.Constants.CHMOD_TOOL_NAME;
import static org.assertj.core.api.BDDAssertions.then; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class LinuxFileAccessServiceTest {
private Mockery myCtx;
private CommandLineExecutor myCommandLineExecutor;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
myCommandLineExecutor = myCtx.mock(CommandLineExecutor.class);
}
@DataProvider(name = "getSetPermissionsForLinuxCases")
public Object[][] getSetPermissionsForLinuxCases() {
return new Object[][] {
// grant
{
new AccessControlList(Arrays.asList(
new AccessControlEntry(new File("my_file"), AccessControlAccount.forUser(""), EnumSet.of(AccessPermissions.GrantRead, AccessPermissions.GrantWrite, AccessPermissions.GrantExecute, AccessPermissions.Recursive), AccessControlScope.Step))),
0,
null,
Arrays.asList( | // Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/Constants.java
// public static final String CHMOD_TOOL_NAME = "chmod";
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/LinuxFileAccessServiceTest.java
import com.intellij.execution.ExecutionException;
import java.io.File;
import java.util.*;
import java.util.Arrays;
import java.util.Collections;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineResource;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineSetup;
import jetbrains.buildServer.util.*;
import jetbrains.buildServer.util.Converter;
import org.assertj.core.util.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static jetbrains.buildServer.runAs.agent.Constants.CHMOD_TOOL_NAME;
import static org.assertj.core.api.BDDAssertions.then;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class LinuxFileAccessServiceTest {
private Mockery myCtx;
private CommandLineExecutor myCommandLineExecutor;
@BeforeMethod
public void setUp()
{
myCtx = new Mockery();
myCommandLineExecutor = myCtx.mock(CommandLineExecutor.class);
}
@DataProvider(name = "getSetPermissionsForLinuxCases")
public Object[][] getSetPermissionsForLinuxCases() {
return new Object[][] {
// grant
{
new AccessControlList(Arrays.asList(
new AccessControlEntry(new File("my_file"), AccessControlAccount.forUser(""), EnumSet.of(AccessPermissions.GrantRead, AccessPermissions.GrantWrite, AccessPermissions.GrantExecute, AccessPermissions.Recursive), AccessControlScope.Step))),
0,
null,
Arrays.asList( | new CommandLineSetup(CHMOD_TOOL_NAME, Arrays.asList(new CommandLineArgument("-R", CommandLineArgument.Type.PARAMETER), new CommandLineArgument("a+rXwx", CommandLineArgument.Type.PARAMETER), new CommandLineArgument(new File("my_file").getAbsolutePath(), CommandLineArgument.Type.PARAMETER)), Collections.<CommandLineResource>emptyList())), |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/RunAsLoggerImpl.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
| import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.diagnostic.Logger;
import java.io.File;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineSetup;
import jetbrains.buildServer.dotNet.buildRunner.agent.LoggerService;
import jetbrains.buildServer.dotNet.buildRunner.agent.RunnerParametersService;
import org.jetbrains.annotations.NotNull;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_LOG_ENABLED; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class RunAsLoggerImpl implements RunAsLogger {
private static final Logger LOG = Logger.getInstance(RunAsLoggerImpl.class.getName());
private final LoggerService myLoggerService;
private final PathsService myPathsService;
private final SecuredLoggingService mySecuredLoggingService;
private final RunnerParametersService myRunnerParametersService;
public RunAsLoggerImpl(
@NotNull final LoggerService loggerService,
@NotNull final PathsService pathsService,
@NotNull final SecuredLoggingService securedLoggingService,
@NotNull final RunnerParametersService runnerParametersService) {
myLoggerService = loggerService;
myPathsService = pathsService;
mySecuredLoggingService = securedLoggingService;
myRunnerParametersService = runnerParametersService;
}
@Override
public void LogRunAs(
@NotNull final UserCredentials userCredentials,
@NotNull final CommandLineSetup baseCommandLineSetup,
@NotNull final CommandLineSetup runAsCommandLineSetup) {
mySecuredLoggingService.disableLoggingOfCommandLine();
final GeneralCommandLine baseCmd = convertToCommandLine(baseCommandLineSetup, false);
final GeneralCommandLine runAsCmd = convertToCommandLine(runAsCommandLineSetup, true);
LOG.info("Run as user \"" + userCredentials.getUser() + "\": " + runAsCmd.getCommandLineString()); | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/RunAsLoggerImpl.java
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.diagnostic.Logger;
import java.io.File;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineSetup;
import jetbrains.buildServer.dotNet.buildRunner.agent.LoggerService;
import jetbrains.buildServer.dotNet.buildRunner.agent.RunnerParametersService;
import org.jetbrains.annotations.NotNull;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_LOG_ENABLED;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class RunAsLoggerImpl implements RunAsLogger {
private static final Logger LOG = Logger.getInstance(RunAsLoggerImpl.class.getName());
private final LoggerService myLoggerService;
private final PathsService myPathsService;
private final SecuredLoggingService mySecuredLoggingService;
private final RunnerParametersService myRunnerParametersService;
public RunAsLoggerImpl(
@NotNull final LoggerService loggerService,
@NotNull final PathsService pathsService,
@NotNull final SecuredLoggingService securedLoggingService,
@NotNull final RunnerParametersService runnerParametersService) {
myLoggerService = loggerService;
myPathsService = pathsService;
mySecuredLoggingService = securedLoggingService;
myRunnerParametersService = runnerParametersService;
}
@Override
public void LogRunAs(
@NotNull final UserCredentials userCredentials,
@NotNull final CommandLineSetup baseCommandLineSetup,
@NotNull final CommandLineSetup runAsCommandLineSetup) {
mySecuredLoggingService.disableLoggingOfCommandLine();
final GeneralCommandLine baseCmd = convertToCommandLine(baseCommandLineSetup, false);
final GeneralCommandLine runAsCmd = convertToCommandLine(runAsCommandLineSetup, true);
LOG.info("Run as user \"" + userCredentials.getUser() + "\": " + runAsCmd.getCommandLineString()); | if(Boolean.parseBoolean(myRunnerParametersService.tryGetConfigParameter(RUN_AS_LOG_ENABLED))) { |
JetBrains/teamcity-runas-plugin | runAs-server/src/main/java/jetbrains/buildServer/runAs/server/RunAsPasswordsProvider.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.serverSide.*;
import jetbrains.buildServer.serverSide.parameters.types.PasswordsProvider;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.server;
public class RunAsPasswordsProvider implements PasswordsProvider {
private final RunAsConfiguration myRunAsConfiguration;
public RunAsPasswordsProvider(@NotNull final RunAsConfiguration runAsConfiguration) {
myRunAsConfiguration = runAsConfiguration;
}
@NotNull
@Override
public Collection<Parameter> getPasswordParameters(@NotNull final SBuild build) {
final ArrayList<Parameter> passwords = new ArrayList<Parameter>();
if (myRunAsConfiguration.getIsUiSupported()) {
final SBuildType buildType = build.getBuildType();
if (buildType != null) {
for (SBuildRunnerDescriptor runner : buildType.getBuildRunners()) { | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
// Path: runAs-server/src/main/java/jetbrains/buildServer/runAs/server/RunAsPasswordsProvider.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.serverSide.*;
import jetbrains.buildServer.serverSide.parameters.types.PasswordsProvider;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.server;
public class RunAsPasswordsProvider implements PasswordsProvider {
private final RunAsConfiguration myRunAsConfiguration;
public RunAsPasswordsProvider(@NotNull final RunAsConfiguration runAsConfiguration) {
myRunAsConfiguration = runAsConfiguration;
}
@NotNull
@Override
public Collection<Parameter> getPasswordParameters(@NotNull final SBuild build) {
final ArrayList<Parameter> passwords = new ArrayList<Parameter>();
if (myRunAsConfiguration.getIsUiSupported()) {
final SBuildType buildType = build.getBuildType();
if (buildType != null) {
for (SBuildRunnerDescriptor runner : buildType.getBuildRunners()) { | final String password = runner.getParameters().get(Constants.PASSWORD); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/RunAsToolProvider.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
| import java.io.File;
import jetbrains.buildServer.agent.AgentRunningBuild;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.agent.ToolCannotBeFoundException;
import jetbrains.buildServer.agent.ToolProvidersRegistry;
import jetbrains.buildServer.agent.plugins.beans.PluginDescriptor;
import jetbrains.buildServer.runAs.common.Constants;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class RunAsToolProvider {
static final String BIN_PATH = "bin";
public RunAsToolProvider(
@NotNull final PluginDescriptor pluginDescriptor,
@NotNull final ToolProvidersRegistry toolProvidersRegistry) {
toolProvidersRegistry.registerToolProvider(new jetbrains.buildServer.agent.ToolProvider() {
@Override
public boolean supports(@NotNull final String toolName) { | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/RunAsToolProvider.java
import java.io.File;
import jetbrains.buildServer.agent.AgentRunningBuild;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.agent.ToolCannotBeFoundException;
import jetbrains.buildServer.agent.ToolProvidersRegistry;
import jetbrains.buildServer.agent.plugins.beans.PluginDescriptor;
import jetbrains.buildServer.runAs.common.Constants;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class RunAsToolProvider {
static final String BIN_PATH = "bin";
public RunAsToolProvider(
@NotNull final PluginDescriptor pluginDescriptor,
@NotNull final ToolProvidersRegistry toolProvidersRegistry) {
toolProvidersRegistry.registerToolProvider(new jetbrains.buildServer.agent.ToolProvider() {
@Override
public boolean supports(@NotNull final String toolName) { | return Constants.RUN_AS_TOOL_NAME.equalsIgnoreCase(toolName); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/RunAsToolProviderTest.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
| import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
import com.intellij.execution.ExecutionException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jetbrains.buildServer.agent.ToolProvider;
import jetbrains.buildServer.agent.ToolProvidersRegistry;
import jetbrains.buildServer.agent.plugins.beans.PluginDescriptor;
import jetbrains.buildServer.runAs.common.Constants;
import org.jetbrains.annotations.NotNull;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction; | myCtx = new Mockery();
myPluginDescriptor = myCtx.mock(PluginDescriptor.class);
myToolProvidersRegistry = myCtx.mock(ToolProvidersRegistry.class);
}
@Test
public void shouldGetPath() throws IOException, ExecutionException {
// Given
final File pluginRootDir = new File("plugin");
final File binPath = new File(pluginRootDir, RunAsToolProvider.BIN_PATH);
final List<ToolProvider> toolProviders = new ArrayList<ToolProvider>();
myCtx.checking(new Expectations() {{
oneOf(myPluginDescriptor).getPluginRoot();
will(returnValue(pluginRootDir));
oneOf(myToolProvidersRegistry).registerToolProvider(with(any(ToolProvider.class)));
will(new CustomAction("registerToolProvider") {
@Override
public Object invoke(final Invocation invocation) throws Throwable {
toolProviders.add((ToolProvider)invocation.getParameter(0));
return null;
}
});
}});
// When
createInstance();
final ToolProvider toolProvider = toolProviders.get(0); | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
// Path: runAs-agent/src/test/java/jetbrains/buildServer/runAs/agent/RunAsToolProviderTest.java
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.assertj.core.api.BDDAssertions.then;
import com.intellij.execution.ExecutionException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jetbrains.buildServer.agent.ToolProvider;
import jetbrains.buildServer.agent.ToolProvidersRegistry;
import jetbrains.buildServer.agent.plugins.beans.PluginDescriptor;
import jetbrains.buildServer.runAs.common.Constants;
import org.jetbrains.annotations.NotNull;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
myCtx = new Mockery();
myPluginDescriptor = myCtx.mock(PluginDescriptor.class);
myToolProvidersRegistry = myCtx.mock(ToolProvidersRegistry.class);
}
@Test
public void shouldGetPath() throws IOException, ExecutionException {
// Given
final File pluginRootDir = new File("plugin");
final File binPath = new File(pluginRootDir, RunAsToolProvider.BIN_PATH);
final List<ToolProvider> toolProviders = new ArrayList<ToolProvider>();
myCtx.checking(new Expectations() {{
oneOf(myPluginDescriptor).getPluginRoot();
will(returnValue(pluginRootDir));
oneOf(myToolProvidersRegistry).registerToolProvider(with(any(ToolProvider.class)));
will(new CustomAction("registerToolProvider") {
@Override
public Object invoke(final Invocation invocation) throws Throwable {
toolProviders.add((ToolProvider)invocation.getParameter(0));
return null;
}
});
}});
// When
createInstance();
final ToolProvider toolProvider = toolProviders.get(0); | final String toolPath = toolProvider.getPath(Constants.RUN_AS_TOOL_NAME); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/ParametersServiceImpl.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
| import jetbrains.buildServer.dotNet.buildRunner.agent.RunnerParametersService;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class ParametersServiceImpl implements ParametersService {
private final RunnerParametersService myRunnerParametersService;
private final BuildFeatureParametersService myBuildFeatureParametersService;
public ParametersServiceImpl(
@NotNull final RunnerParametersService runnerParametersService,
@NotNull final BuildFeatureParametersService buildFeatureParametersService) {
myRunnerParametersService = runnerParametersService;
myBuildFeatureParametersService = buildFeatureParametersService;
}
@Nullable
@Override
public String tryGetParameter(@NotNull final String paramName) { | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/ParametersServiceImpl.java
import jetbrains.buildServer.dotNet.buildRunner.agent.RunnerParametersService;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class ParametersServiceImpl implements ParametersService {
private final RunnerParametersService myRunnerParametersService;
private final BuildFeatureParametersService myBuildFeatureParametersService;
public ParametersServiceImpl(
@NotNull final RunnerParametersService runnerParametersService,
@NotNull final BuildFeatureParametersService buildFeatureParametersService) {
myRunnerParametersService = runnerParametersService;
myBuildFeatureParametersService = buildFeatureParametersService;
}
@Nullable
@Override
public String tryGetParameter(@NotNull final String paramName) { | final String isRunAsUiEnabledStr = myRunnerParametersService.tryGetConfigParameter(Constants.RUN_AS_UI_ENABLED); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/RunAsPropertiesExtension.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/Constants.java
// public class Constants {
// @SuppressWarnings("SpellCheckingInspection")
// public static final String ICACLS_TOOL_NAME = "ICACLS";
// public static final String CHMOD_TOOL_NAME = "chmod";
// public static final String SU_TOOL_NAME = "su";
// public static final String RUN_AS_WIN32_TOOL_NAME = "JetBrains.runAs.exe";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_TOOL_NAME = "runAs";
| import com.intellij.execution.ExecutionException;
import com.intellij.openapi.diagnostic.Logger;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.agent.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.BuildRunnerContextProvider;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineResource;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineSetup;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.util.EventDispatcher;
import jetbrains.buildServer.util.StringUtil;
import jetbrains.buildServer.util.positioning.PositionAware;
import jetbrains.buildServer.util.positioning.PositionConstraint;
import org.jetbrains.annotations.NotNull;
import static jetbrains.buildServer.runAs.agent.Constants.*;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_TOOL_NAME; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
@SuppressWarnings("deprecation")
public class RunAsPropertiesExtension extends AgentLifeCycleAdapter implements RunAsAccessService, PositionAware {
private static final String TOOL_FILE_NAME_LINUX = "runAs.sh";
private static final String TOOL_FILE_NAME_MAC = "runAs_mac.sh";
private static final Logger LOG = Logger.getInstance(RunAsPropertiesExtension.class.getName()); | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/Constants.java
// public class Constants {
// @SuppressWarnings("SpellCheckingInspection")
// public static final String ICACLS_TOOL_NAME = "ICACLS";
// public static final String CHMOD_TOOL_NAME = "chmod";
// public static final String SU_TOOL_NAME = "su";
// public static final String RUN_AS_WIN32_TOOL_NAME = "JetBrains.runAs.exe";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_TOOL_NAME = "runAs";
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/RunAsPropertiesExtension.java
import com.intellij.execution.ExecutionException;
import com.intellij.openapi.diagnostic.Logger;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.agent.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.BuildRunnerContextProvider;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineResource;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineSetup;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.util.EventDispatcher;
import jetbrains.buildServer.util.StringUtil;
import jetbrains.buildServer.util.positioning.PositionAware;
import jetbrains.buildServer.util.positioning.PositionConstraint;
import org.jetbrains.annotations.NotNull;
import static jetbrains.buildServer.runAs.agent.Constants.*;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_TOOL_NAME;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
@SuppressWarnings("deprecation")
public class RunAsPropertiesExtension extends AgentLifeCycleAdapter implements RunAsAccessService, PositionAware {
private static final String TOOL_FILE_NAME_LINUX = "runAs.sh";
private static final String TOOL_FILE_NAME_MAC = "runAs_mac.sh";
private static final Logger LOG = Logger.getInstance(RunAsPropertiesExtension.class.getName()); | private static final String[] OurProtectedParams = new String[] { Constants.PASSWORD, Constants.CONFIG_PASSWORD }; |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/RunAsPropertiesExtension.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/Constants.java
// public class Constants {
// @SuppressWarnings("SpellCheckingInspection")
// public static final String ICACLS_TOOL_NAME = "ICACLS";
// public static final String CHMOD_TOOL_NAME = "chmod";
// public static final String SU_TOOL_NAME = "su";
// public static final String RUN_AS_WIN32_TOOL_NAME = "JetBrains.runAs.exe";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_TOOL_NAME = "runAs";
| import com.intellij.execution.ExecutionException;
import com.intellij.openapi.diagnostic.Logger;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.agent.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.BuildRunnerContextProvider;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineResource;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineSetup;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.util.EventDispatcher;
import jetbrains.buildServer.util.StringUtil;
import jetbrains.buildServer.util.positioning.PositionAware;
import jetbrains.buildServer.util.positioning.PositionConstraint;
import org.jetbrains.annotations.NotNull;
import static jetbrains.buildServer.runAs.agent.Constants.*;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_TOOL_NAME; | }
@NotNull
@Override
public PositionConstraint getConstraint() {
return PositionConstraint.first();
}
@Override
public void agentInitialized(@NotNull final BuildAgent agent) {
updateIsRunAsEnabled(agent.getConfiguration());
super.agentInitialized(agent);
}
@Override
public void buildStarted(@NotNull final AgentRunningBuild runningBuild) {
myBuildRunnerContextProvider.initialize(((AgentRunningBuildEx)runningBuild).getCurrentRunnerContext());
protectProperties(runningBuild);
super.buildStarted(runningBuild);
}
@Override
public void buildFinished(@NotNull final AgentRunningBuild build, @NotNull final BuildFinishedStatus buildStatus) {
super.buildFinished(build, buildStatus);
myBuildFileAccessCacheManager.reset();
}
private void updateIsRunAsEnabled(final @NotNull BuildAgentConfiguration config) {
myIsRunAsEnabled = false;
| // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
//
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/Constants.java
// public class Constants {
// @SuppressWarnings("SpellCheckingInspection")
// public static final String ICACLS_TOOL_NAME = "ICACLS";
// public static final String CHMOD_TOOL_NAME = "chmod";
// public static final String SU_TOOL_NAME = "su";
// public static final String RUN_AS_WIN32_TOOL_NAME = "JetBrains.runAs.exe";
// }
//
// Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public static final String RUN_AS_TOOL_NAME = "runAs";
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/RunAsPropertiesExtension.java
import com.intellij.execution.ExecutionException;
import com.intellij.openapi.diagnostic.Logger;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.agent.*;
import jetbrains.buildServer.dotNet.buildRunner.agent.BuildRunnerContextProvider;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineResource;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineSetup;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.util.EventDispatcher;
import jetbrains.buildServer.util.StringUtil;
import jetbrains.buildServer.util.positioning.PositionAware;
import jetbrains.buildServer.util.positioning.PositionConstraint;
import org.jetbrains.annotations.NotNull;
import static jetbrains.buildServer.runAs.agent.Constants.*;
import static jetbrains.buildServer.runAs.common.Constants.RUN_AS_TOOL_NAME;
}
@NotNull
@Override
public PositionConstraint getConstraint() {
return PositionConstraint.first();
}
@Override
public void agentInitialized(@NotNull final BuildAgent agent) {
updateIsRunAsEnabled(agent.getConfiguration());
super.agentInitialized(agent);
}
@Override
public void buildStarted(@NotNull final AgentRunningBuild runningBuild) {
myBuildRunnerContextProvider.initialize(((AgentRunningBuildEx)runningBuild).getCurrentRunnerContext());
protectProperties(runningBuild);
super.buildStarted(runningBuild);
}
@Override
public void buildFinished(@NotNull final AgentRunningBuild build, @NotNull final BuildFinishedStatus buildStatus) {
super.buildFinished(build, buildStatus);
myBuildFileAccessCacheManager.reset();
}
private void updateIsRunAsEnabled(final @NotNull BuildAgentConfiguration config) {
myIsRunAsEnabled = false;
| final ToolProvider toolProvider = myToolProvidersRegistry.findToolProvider(RUN_AS_TOOL_NAME); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/LinuxFileAccessService.java | // Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/Constants.java
// public static final String CHMOD_TOOL_NAME = "chmod";
| import static jetbrains.buildServer.runAs.agent.Constants.CHMOD_TOOL_NAME;
import com.intellij.execution.ExecutionException;
import com.intellij.openapi.diagnostic.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineResource;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineSetup;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | break;
case All:
permissionsList.add(0, "a-");
break;
}
final Result<AccessControlEntry, Boolean> result = tryExecChmod(entry, permissionsList);
if(result != null) {
results.add(result);
}
}
return results;
}
@Nullable
private Result<AccessControlEntry, Boolean> tryExecChmod(@NotNull final AccessControlEntry entry, @NotNull final Iterable<String> chmodPermissions)
{
final String chmodPermissionsStr = StringUtil.join("", chmodPermissions);
if(StringUtil.isEmptyOrSpaces(chmodPermissionsStr)) {
return null;
}
final ArrayList<CommandLineArgument> args = new ArrayList<CommandLineArgument>();
if (entry.getPermissions().contains(AccessPermissions.Recursive)) {
args.add(new CommandLineArgument("-R", CommandLineArgument.Type.PARAMETER));
}
args.add(new CommandLineArgument(chmodPermissionsStr, CommandLineArgument.Type.PARAMETER));
args.add(new CommandLineArgument(entry.getFile().getAbsolutePath(), CommandLineArgument.Type.PARAMETER)); | // Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/Constants.java
// public static final String CHMOD_TOOL_NAME = "chmod";
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/LinuxFileAccessService.java
import static jetbrains.buildServer.runAs.agent.Constants.CHMOD_TOOL_NAME;
import com.intellij.execution.ExecutionException;
import com.intellij.openapi.diagnostic.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineResource;
import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineSetup;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
break;
case All:
permissionsList.add(0, "a-");
break;
}
final Result<AccessControlEntry, Boolean> result = tryExecChmod(entry, permissionsList);
if(result != null) {
results.add(result);
}
}
return results;
}
@Nullable
private Result<AccessControlEntry, Boolean> tryExecChmod(@NotNull final AccessControlEntry entry, @NotNull final Iterable<String> chmodPermissions)
{
final String chmodPermissionsStr = StringUtil.join("", chmodPermissions);
if(StringUtil.isEmptyOrSpaces(chmodPermissionsStr)) {
return null;
}
final ArrayList<CommandLineArgument> args = new ArrayList<CommandLineArgument>();
if (entry.getPermissions().contains(AccessPermissions.Recursive)) {
args.add(new CommandLineArgument("-R", CommandLineArgument.Type.PARAMETER));
}
args.add(new CommandLineArgument(chmodPermissionsStr, CommandLineArgument.Type.PARAMETER));
args.add(new CommandLineArgument(entry.getFile().getAbsolutePath(), CommandLineArgument.Type.PARAMETER)); | final CommandLineSetup chmodCommandLineSetup = new CommandLineSetup(CHMOD_TOOL_NAME, args, Collections.<CommandLineResource>emptyList()); |
JetBrains/teamcity-runas-plugin | runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/AccessControlListProviderImpl.java | // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
| import com.intellij.openapi.diagnostic.Logger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.TextParser;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class AccessControlListProviderImpl implements AccessControlListProvider {
@NotNull private static final Logger LOG = Logger.getInstance(AccessControlListProviderImpl.class.getName());
@NotNull private final PathsService myPathsService;
@NotNull private final TextParser<AccessControlList> myFileAccessParser;
@NotNull private final AgentParametersService myAgentParametersService;
@NotNull private final ProfileParametersService myProfileParametersService;
@Nullable private List<AccessControlEntry> myDefaultAcl;
public AccessControlListProviderImpl(
@NotNull final PathsService pathsService,
@NotNull final TextParser<AccessControlList> fileAccessParser,
@NotNull final AgentParametersService agentParametersService,
@NotNull final ProfileParametersService profileParametersService) {
myPathsService = pathsService;
myFileAccessParser = fileAccessParser;
myAgentParametersService = agentParametersService;
myProfileParametersService = profileParametersService;
}
@NotNull
@Override
public AccessControlList getAcl(@NotNull final UserCredentials userCredentials) {
final List<AccessControlEntry> aceList = new ArrayList<AccessControlEntry>();
| // Path: runAs-common/src/main/java/jetbrains/buildServer/runAs/common/Constants.java
// public class Constants {
// // Plugin's ids
// public static final String BUILD_FEATURE_TYPE = "runAs-build-feature";
// public static final String RUN_AS_TOOL_NAME = "runAs";
//
// // Parameter names
// public static final String USER = "teamcity.runAs.username";
// public static final String PASSWORD = "secure:teamcity.runAs.password";
// public static final String CONFIG_PASSWORD = "teamcity.runAs.password";
// public static final String ADDITIONAL_ARGS = "teamcity.runAs.additionalCommandLine";
// public static final String RUN_AS_ENABLED = "teamcity.agent.runAs.enabled";
// public static final String CREDENTIALS_PROFILE_ID = "teamcity.runAs.profileId";
// public static final String WINDOWS_INTEGRITY_LEVEL = "teamcity.runAs.windowsIntegrityLlevel";
// public static final String LOGGING_LEVEL = "teamcity.runAs.loggingLevel";
// public static final String ALLOW_CUSTOM_CREDENTIALS = "teamcity.runAs.allowCustomCredentials";
// public static final String ALLOW_PROFILE_ID_FROM_SERVER = "teamcity.runAs.allowProfileIdFromServer";
// public static final String CREDENTIALS_DIRECTORY = "teamcity.runAs.configDir";
// public static final String RUN_AS_UI_ENABLED = "teamcity.runAs.ui.enabled";
// public static final String RUN_AS_UI_STEPS_ENABLED = "teamcity.runAs.ui.steps.enabled";
// public static final String RUN_AS_LOG_ENABLED = "teamcity.runAs.log.enabled";
// public static final String RUN_AS_ACL = "teamcity.runAs.acl";
// public static final String RUN_AS_ACL_DEFAULTS_ENABLED = "teamcity.runAs.acl.defaults.enabled";
// }
// Path: runAs-agent/src/main/java/jetbrains/buildServer/runAs/agent/AccessControlListProviderImpl.java
import com.intellij.openapi.diagnostic.Logger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import jetbrains.buildServer.dotNet.buildRunner.agent.TextParser;
import jetbrains.buildServer.runAs.common.Constants;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.runAs.agent;
public class AccessControlListProviderImpl implements AccessControlListProvider {
@NotNull private static final Logger LOG = Logger.getInstance(AccessControlListProviderImpl.class.getName());
@NotNull private final PathsService myPathsService;
@NotNull private final TextParser<AccessControlList> myFileAccessParser;
@NotNull private final AgentParametersService myAgentParametersService;
@NotNull private final ProfileParametersService myProfileParametersService;
@Nullable private List<AccessControlEntry> myDefaultAcl;
public AccessControlListProviderImpl(
@NotNull final PathsService pathsService,
@NotNull final TextParser<AccessControlList> fileAccessParser,
@NotNull final AgentParametersService agentParametersService,
@NotNull final ProfileParametersService profileParametersService) {
myPathsService = pathsService;
myFileAccessParser = fileAccessParser;
myAgentParametersService = agentParametersService;
myProfileParametersService = profileParametersService;
}
@NotNull
@Override
public AccessControlList getAcl(@NotNull final UserCredentials userCredentials) {
final List<AccessControlEntry> aceList = new ArrayList<AccessControlEntry>();
| final boolean isAclDefaultsEnabled = ParameterUtils.parseBoolean(myAgentParametersService.tryGetConfigParameter(Constants.RUN_AS_ACL_DEFAULTS_ENABLED), false); |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/util/LogUtils.java | // Path: app/src/main/java/com/bean/simplenews/common/Constants.java
// public class Constants {
// public static boolean DEBUG = true;
// public static boolean NIGHT = false;
// public static final String TYPE = "TYPE";
// public static final String NEWS = "NEWS";
// public static final int NEWS_TYPE_TOP = 0;
// public static final int NEWS_TYPE_NBA = 1;
// public static final int NEWS_TYPE_TEC = 2;
// public static final int NEWS_TYPE_FIN = 3;
// public static final int NEWS_TYPE_CARS = 4;
// public static final int NEWS_TYPE_JOKES = 5;
// public static final String prefix =
// "<style type=\"text/css\">body{font-size:100%;text-align:justify;color:#424242;padding:10px;}p{font-weight:500;font-size:0.78em;line-height:1.5;}p strong{font-weight:600}h3{font-size:1.4em}</style><body>";
// public static final String suffix = "</body>";
// }
| import android.util.Log;
import com.bean.simplenews.common.Constants; | package com.bean.simplenews.util;
public class LogUtils {
public static void v(String tag, String message) { | // Path: app/src/main/java/com/bean/simplenews/common/Constants.java
// public class Constants {
// public static boolean DEBUG = true;
// public static boolean NIGHT = false;
// public static final String TYPE = "TYPE";
// public static final String NEWS = "NEWS";
// public static final int NEWS_TYPE_TOP = 0;
// public static final int NEWS_TYPE_NBA = 1;
// public static final int NEWS_TYPE_TEC = 2;
// public static final int NEWS_TYPE_FIN = 3;
// public static final int NEWS_TYPE_CARS = 4;
// public static final int NEWS_TYPE_JOKES = 5;
// public static final String prefix =
// "<style type=\"text/css\">body{font-size:100%;text-align:justify;color:#424242;padding:10px;}p{font-weight:500;font-size:0.78em;line-height:1.5;}p strong{font-weight:600}h3{font-size:1.4em}</style><body>";
// public static final String suffix = "</body>";
// }
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
import android.util.Log;
import com.bean.simplenews.common.Constants;
package com.bean.simplenews.util;
public class LogUtils {
public static void v(String tag, String message) { | if(Constants.DEBUG) { |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/model/NewsListHelper.java | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsListConverterFactory.java
// public final class NewsListConverterFactory extends Converter.Factory{
//
// private JsonParser parser;
//
// public static NewsListConverterFactory create() {
// LogUtils.e("fuck","factory created");
// return new NewsListConverterFactory();
// }
//
// private NewsListConverterFactory() {
// parser=new JsonParser();
// }
//
// /*这个方法每一次http请求都被调用,返回一个新建的Converter对象,因此每一个http线程都持有一个Converter对象,
// *彼此不会发生冲突。
// */
// @Override
// public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
// return new NewsListResponseBodyConverter<List<NewsBean>>(parser);
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
| import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.module.news.model.converter.NewsListConverterFactory;
import com.bean.simplenews.util.LogUtils;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit; | package com.bean.simplenews.module.news.model;
public class NewsListHelper {
private Retrofit retrofit;
private NewsListService service; | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsListConverterFactory.java
// public final class NewsListConverterFactory extends Converter.Factory{
//
// private JsonParser parser;
//
// public static NewsListConverterFactory create() {
// LogUtils.e("fuck","factory created");
// return new NewsListConverterFactory();
// }
//
// private NewsListConverterFactory() {
// parser=new JsonParser();
// }
//
// /*这个方法每一次http请求都被调用,返回一个新建的Converter对象,因此每一个http线程都持有一个Converter对象,
// *彼此不会发生冲突。
// */
// @Override
// public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
// return new NewsListResponseBodyConverter<List<NewsBean>>(parser);
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/model/NewsListHelper.java
import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.module.news.model.converter.NewsListConverterFactory;
import com.bean.simplenews.util.LogUtils;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
package com.bean.simplenews.module.news.model;
public class NewsListHelper {
private Retrofit retrofit;
private NewsListService service; | private Hashtable<String, Call<List<NewsBean>>> callMap; //Hashtable是线程安全的 |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/model/NewsListHelper.java | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsListConverterFactory.java
// public final class NewsListConverterFactory extends Converter.Factory{
//
// private JsonParser parser;
//
// public static NewsListConverterFactory create() {
// LogUtils.e("fuck","factory created");
// return new NewsListConverterFactory();
// }
//
// private NewsListConverterFactory() {
// parser=new JsonParser();
// }
//
// /*这个方法每一次http请求都被调用,返回一个新建的Converter对象,因此每一个http线程都持有一个Converter对象,
// *彼此不会发生冲突。
// */
// @Override
// public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
// return new NewsListResponseBodyConverter<List<NewsBean>>(parser);
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
| import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.module.news.model.converter.NewsListConverterFactory;
import com.bean.simplenews.util.LogUtils;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit; | package com.bean.simplenews.module.news.model;
public class NewsListHelper {
private Retrofit retrofit;
private NewsListService service;
private Hashtable<String, Call<List<NewsBean>>> callMap; //Hashtable是线程安全的
private static NewsListHelper instance;
private NewsListHelper() {
retrofit = new Retrofit.Builder()
.baseUrl("http://c.m.163.com/nc/article/") | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsListConverterFactory.java
// public final class NewsListConverterFactory extends Converter.Factory{
//
// private JsonParser parser;
//
// public static NewsListConverterFactory create() {
// LogUtils.e("fuck","factory created");
// return new NewsListConverterFactory();
// }
//
// private NewsListConverterFactory() {
// parser=new JsonParser();
// }
//
// /*这个方法每一次http请求都被调用,返回一个新建的Converter对象,因此每一个http线程都持有一个Converter对象,
// *彼此不会发生冲突。
// */
// @Override
// public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
// return new NewsListResponseBodyConverter<List<NewsBean>>(parser);
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/model/NewsListHelper.java
import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.module.news.model.converter.NewsListConverterFactory;
import com.bean.simplenews.util.LogUtils;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
package com.bean.simplenews.module.news.model;
public class NewsListHelper {
private Retrofit retrofit;
private NewsListService service;
private Hashtable<String, Call<List<NewsBean>>> callMap; //Hashtable是线程安全的
private static NewsListHelper instance;
private NewsListHelper() {
retrofit = new Retrofit.Builder()
.baseUrl("http://c.m.163.com/nc/article/") | .addConverterFactory(NewsListConverterFactory.create()) |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/NewsAdapter.java | // Path: app/src/main/java/com/bean/simplenews/api/Urls.java
// public class Urls {
//
// //http://c.m.163.com/nc/article/headline/T1348647909107/0-20.html
// public static final int PAGE_SIZE = 20;
// public static final String CATEGORY_TOP = "headline";
// public static final String CATEGORY_COMMON = "list";
//
// public static final String TOP_ID = "T1348647909107";
// public static final String NBA_ID = "T1348649145984";
// public static final String TEC_ID = "T1348649580692";
// public static final String FIN_ID = "T1348648756099";
// public static final String CAR_ID = "T1348654060988";
// public static final String JOKE_ID = "T1350383429665";
// }
//
// Path: app/src/main/java/com/bean/simplenews/common/base/BaseApp.java
// public class BaseApp extends Application{
//
// //private static Typeface typeFace;
//
// @Override
// public void onCreate() {
// super.onCreate();
// //typeFace = Typeface.createFromAsset(getAssets(),"fonts/1mRegular.ttf");
// }
//
// /*public static Typeface getTypeface(){
// return typeFace;
// }*/
// }
//
// Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/ImageLoaderUtils.java
// public class ImageLoaderUtils {
//
// public static void display(Context context, ImageView imageView, String url, int placeholder, int error) {
// if(imageView == null) {
// throw new IllegalArgumentException("argument error");
// }
// Glide.with(context).load(url).placeholder(placeholder)
// .error(error).crossFade().into(imageView);
// }
//
// public static void display(Context context, ImageView imageView, String url) {
// if(imageView == null) {
// throw new IllegalArgumentException("argument error");
// }
// Glide.with(context).load(url).placeholder(R.drawable.ic_image_loading)
// .error(R.drawable.ic_image_loadfail).crossFade().into(imageView);
// }
//
//
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bean.simplenews.R;
import com.bean.simplenews.api.Urls;
import com.bean.simplenews.common.base.BaseApp;
import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.ImageLoaderUtils;
import java.util.List; | package com.bean.simplenews.module.news;
public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private static final int TYPE_FOOTER = 2;
| // Path: app/src/main/java/com/bean/simplenews/api/Urls.java
// public class Urls {
//
// //http://c.m.163.com/nc/article/headline/T1348647909107/0-20.html
// public static final int PAGE_SIZE = 20;
// public static final String CATEGORY_TOP = "headline";
// public static final String CATEGORY_COMMON = "list";
//
// public static final String TOP_ID = "T1348647909107";
// public static final String NBA_ID = "T1348649145984";
// public static final String TEC_ID = "T1348649580692";
// public static final String FIN_ID = "T1348648756099";
// public static final String CAR_ID = "T1348654060988";
// public static final String JOKE_ID = "T1350383429665";
// }
//
// Path: app/src/main/java/com/bean/simplenews/common/base/BaseApp.java
// public class BaseApp extends Application{
//
// //private static Typeface typeFace;
//
// @Override
// public void onCreate() {
// super.onCreate();
// //typeFace = Typeface.createFromAsset(getAssets(),"fonts/1mRegular.ttf");
// }
//
// /*public static Typeface getTypeface(){
// return typeFace;
// }*/
// }
//
// Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/ImageLoaderUtils.java
// public class ImageLoaderUtils {
//
// public static void display(Context context, ImageView imageView, String url, int placeholder, int error) {
// if(imageView == null) {
// throw new IllegalArgumentException("argument error");
// }
// Glide.with(context).load(url).placeholder(placeholder)
// .error(error).crossFade().into(imageView);
// }
//
// public static void display(Context context, ImageView imageView, String url) {
// if(imageView == null) {
// throw new IllegalArgumentException("argument error");
// }
// Glide.with(context).load(url).placeholder(R.drawable.ic_image_loading)
// .error(R.drawable.ic_image_loadfail).crossFade().into(imageView);
// }
//
//
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/NewsAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bean.simplenews.R;
import com.bean.simplenews.api.Urls;
import com.bean.simplenews.common.base.BaseApp;
import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.ImageLoaderUtils;
import java.util.List;
package com.bean.simplenews.module.news;
public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private static final int TYPE_FOOTER = 2;
| private List<NewsBean> mData; |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/NewsAdapter.java | // Path: app/src/main/java/com/bean/simplenews/api/Urls.java
// public class Urls {
//
// //http://c.m.163.com/nc/article/headline/T1348647909107/0-20.html
// public static final int PAGE_SIZE = 20;
// public static final String CATEGORY_TOP = "headline";
// public static final String CATEGORY_COMMON = "list";
//
// public static final String TOP_ID = "T1348647909107";
// public static final String NBA_ID = "T1348649145984";
// public static final String TEC_ID = "T1348649580692";
// public static final String FIN_ID = "T1348648756099";
// public static final String CAR_ID = "T1348654060988";
// public static final String JOKE_ID = "T1350383429665";
// }
//
// Path: app/src/main/java/com/bean/simplenews/common/base/BaseApp.java
// public class BaseApp extends Application{
//
// //private static Typeface typeFace;
//
// @Override
// public void onCreate() {
// super.onCreate();
// //typeFace = Typeface.createFromAsset(getAssets(),"fonts/1mRegular.ttf");
// }
//
// /*public static Typeface getTypeface(){
// return typeFace;
// }*/
// }
//
// Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/ImageLoaderUtils.java
// public class ImageLoaderUtils {
//
// public static void display(Context context, ImageView imageView, String url, int placeholder, int error) {
// if(imageView == null) {
// throw new IllegalArgumentException("argument error");
// }
// Glide.with(context).load(url).placeholder(placeholder)
// .error(error).crossFade().into(imageView);
// }
//
// public static void display(Context context, ImageView imageView, String url) {
// if(imageView == null) {
// throw new IllegalArgumentException("argument error");
// }
// Glide.with(context).load(url).placeholder(R.drawable.ic_image_loading)
// .error(R.drawable.ic_image_loadfail).crossFade().into(imageView);
// }
//
//
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bean.simplenews.R;
import com.bean.simplenews.api.Urls;
import com.bean.simplenews.common.base.BaseApp;
import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.ImageLoaderUtils;
import java.util.List; | package com.bean.simplenews.module.news;
public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private static final int TYPE_FOOTER = 2;
private List<NewsBean> mData;
private int mPageIndex;
private boolean mShowFooter = true;
private Context mContext;
private OnItemClickListener mOnItemClickListener;
public NewsAdapter(Context context) {
this.mContext = context;
}
@Override
public int getItemViewType(int position) {
if (position + 1 == getItemCount()) { // 如果只有一项先判断为footer
return TYPE_FOOTER; | // Path: app/src/main/java/com/bean/simplenews/api/Urls.java
// public class Urls {
//
// //http://c.m.163.com/nc/article/headline/T1348647909107/0-20.html
// public static final int PAGE_SIZE = 20;
// public static final String CATEGORY_TOP = "headline";
// public static final String CATEGORY_COMMON = "list";
//
// public static final String TOP_ID = "T1348647909107";
// public static final String NBA_ID = "T1348649145984";
// public static final String TEC_ID = "T1348649580692";
// public static final String FIN_ID = "T1348648756099";
// public static final String CAR_ID = "T1348654060988";
// public static final String JOKE_ID = "T1350383429665";
// }
//
// Path: app/src/main/java/com/bean/simplenews/common/base/BaseApp.java
// public class BaseApp extends Application{
//
// //private static Typeface typeFace;
//
// @Override
// public void onCreate() {
// super.onCreate();
// //typeFace = Typeface.createFromAsset(getAssets(),"fonts/1mRegular.ttf");
// }
//
// /*public static Typeface getTypeface(){
// return typeFace;
// }*/
// }
//
// Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/ImageLoaderUtils.java
// public class ImageLoaderUtils {
//
// public static void display(Context context, ImageView imageView, String url, int placeholder, int error) {
// if(imageView == null) {
// throw new IllegalArgumentException("argument error");
// }
// Glide.with(context).load(url).placeholder(placeholder)
// .error(error).crossFade().into(imageView);
// }
//
// public static void display(Context context, ImageView imageView, String url) {
// if(imageView == null) {
// throw new IllegalArgumentException("argument error");
// }
// Glide.with(context).load(url).placeholder(R.drawable.ic_image_loading)
// .error(R.drawable.ic_image_loadfail).crossFade().into(imageView);
// }
//
//
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/NewsAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bean.simplenews.R;
import com.bean.simplenews.api.Urls;
import com.bean.simplenews.common.base.BaseApp;
import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.ImageLoaderUtils;
import java.util.List;
package com.bean.simplenews.module.news;
public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private static final int TYPE_FOOTER = 2;
private List<NewsBean> mData;
private int mPageIndex;
private boolean mShowFooter = true;
private Context mContext;
private OnItemClickListener mOnItemClickListener;
public NewsAdapter(Context context) {
this.mContext = context;
}
@Override
public int getItemViewType(int position) {
if (position + 1 == getItemCount()) { // 如果只有一项先判断为footer
return TYPE_FOOTER; | } else if (position == 0 && (mPageIndex == 0 || mPageIndex == Urls.PAGE_SIZE)) { |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/NewsAdapter.java | // Path: app/src/main/java/com/bean/simplenews/api/Urls.java
// public class Urls {
//
// //http://c.m.163.com/nc/article/headline/T1348647909107/0-20.html
// public static final int PAGE_SIZE = 20;
// public static final String CATEGORY_TOP = "headline";
// public static final String CATEGORY_COMMON = "list";
//
// public static final String TOP_ID = "T1348647909107";
// public static final String NBA_ID = "T1348649145984";
// public static final String TEC_ID = "T1348649580692";
// public static final String FIN_ID = "T1348648756099";
// public static final String CAR_ID = "T1348654060988";
// public static final String JOKE_ID = "T1350383429665";
// }
//
// Path: app/src/main/java/com/bean/simplenews/common/base/BaseApp.java
// public class BaseApp extends Application{
//
// //private static Typeface typeFace;
//
// @Override
// public void onCreate() {
// super.onCreate();
// //typeFace = Typeface.createFromAsset(getAssets(),"fonts/1mRegular.ttf");
// }
//
// /*public static Typeface getTypeface(){
// return typeFace;
// }*/
// }
//
// Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/ImageLoaderUtils.java
// public class ImageLoaderUtils {
//
// public static void display(Context context, ImageView imageView, String url, int placeholder, int error) {
// if(imageView == null) {
// throw new IllegalArgumentException("argument error");
// }
// Glide.with(context).load(url).placeholder(placeholder)
// .error(error).crossFade().into(imageView);
// }
//
// public static void display(Context context, ImageView imageView, String url) {
// if(imageView == null) {
// throw new IllegalArgumentException("argument error");
// }
// Glide.with(context).load(url).placeholder(R.drawable.ic_image_loading)
// .error(R.drawable.ic_image_loadfail).crossFade().into(imageView);
// }
//
//
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bean.simplenews.R;
import com.bean.simplenews.api.Urls;
import com.bean.simplenews.common.base.BaseApp;
import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.ImageLoaderUtils;
import java.util.List; | return TYPE_FOOTER;
} else if (position == 0 && (mPageIndex == 0 || mPageIndex == Urls.PAGE_SIZE)) {
return TYPE_HEADER;
} else {
return TYPE_ITEM;
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_HEADER) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_header, parent, false);
return new HeaderViewHolder(view);
} else if (viewType == TYPE_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
return new ItemViewHolder(v);
} else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_footer, null);
view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
return new FooterViewHolder(view);
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof HeaderViewHolder) {
NewsBean news = mData.get(position);
if (news == null) {
return;
} | // Path: app/src/main/java/com/bean/simplenews/api/Urls.java
// public class Urls {
//
// //http://c.m.163.com/nc/article/headline/T1348647909107/0-20.html
// public static final int PAGE_SIZE = 20;
// public static final String CATEGORY_TOP = "headline";
// public static final String CATEGORY_COMMON = "list";
//
// public static final String TOP_ID = "T1348647909107";
// public static final String NBA_ID = "T1348649145984";
// public static final String TEC_ID = "T1348649580692";
// public static final String FIN_ID = "T1348648756099";
// public static final String CAR_ID = "T1348654060988";
// public static final String JOKE_ID = "T1350383429665";
// }
//
// Path: app/src/main/java/com/bean/simplenews/common/base/BaseApp.java
// public class BaseApp extends Application{
//
// //private static Typeface typeFace;
//
// @Override
// public void onCreate() {
// super.onCreate();
// //typeFace = Typeface.createFromAsset(getAssets(),"fonts/1mRegular.ttf");
// }
//
// /*public static Typeface getTypeface(){
// return typeFace;
// }*/
// }
//
// Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/ImageLoaderUtils.java
// public class ImageLoaderUtils {
//
// public static void display(Context context, ImageView imageView, String url, int placeholder, int error) {
// if(imageView == null) {
// throw new IllegalArgumentException("argument error");
// }
// Glide.with(context).load(url).placeholder(placeholder)
// .error(error).crossFade().into(imageView);
// }
//
// public static void display(Context context, ImageView imageView, String url) {
// if(imageView == null) {
// throw new IllegalArgumentException("argument error");
// }
// Glide.with(context).load(url).placeholder(R.drawable.ic_image_loading)
// .error(R.drawable.ic_image_loadfail).crossFade().into(imageView);
// }
//
//
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/NewsAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bean.simplenews.R;
import com.bean.simplenews.api.Urls;
import com.bean.simplenews.common.base.BaseApp;
import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.ImageLoaderUtils;
import java.util.List;
return TYPE_FOOTER;
} else if (position == 0 && (mPageIndex == 0 || mPageIndex == Urls.PAGE_SIZE)) {
return TYPE_HEADER;
} else {
return TYPE_ITEM;
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_HEADER) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_header, parent, false);
return new HeaderViewHolder(view);
} else if (viewType == TYPE_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
return new ItemViewHolder(v);
} else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_footer, null);
view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
return new FooterViewHolder(view);
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof HeaderViewHolder) {
NewsBean news = mData.get(position);
if (news == null) {
return;
} | ImageLoaderUtils.display(mContext, ((HeaderViewHolder) holder).mImage, news.getImgsrc()); |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/model/NewsDetailHelper.java | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsDetailBean.java
// public class NewsDetailBean implements Serializable {
//
// private String title;
// private String body;
// private List<Image> img; //图片列表
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getBody() {
// return body;
// }
// public void setBody(String body) {
// this.body = body;
// }
// public List<Image> getImg() {
// return img;
// }
// public void setImg(List<Image> imgList) {
// this.img = imgList;
// }
//
// public class Image {
// private String ref;
// private String src;
//
// public String getRef() {
// return ref;
// }
// public void setRef(String ref) {
// this.ref = ref;
// }
// public String getSrc() {
// return src;
// }
// public void setSrc(String src) {
// this.src = src;
// }
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsDetailConverterFactory.java
// public class NewsDetailConverterFactory extends Converter.Factory{
//
// private JsonParser parser;
//
// public static NewsDetailConverterFactory create() {
// return new NewsDetailConverterFactory();
// }
//
// private NewsDetailConverterFactory() {
// parser = new JsonParser();
// }
//
// @Override
// public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
// return new NewsDetailResponseBodyConverter<NewsDetailBean>(parser);
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
| import com.bean.simplenews.module.news.model.bean.NewsDetailBean;
import com.bean.simplenews.module.news.model.converter.NewsDetailConverterFactory;
import com.bean.simplenews.util.LogUtils;
import java.util.Hashtable;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit; | package com.bean.simplenews.module.news.model;
public class NewsDetailHelper {
private Retrofit retrofit;
private NewsDetailService service; | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsDetailBean.java
// public class NewsDetailBean implements Serializable {
//
// private String title;
// private String body;
// private List<Image> img; //图片列表
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getBody() {
// return body;
// }
// public void setBody(String body) {
// this.body = body;
// }
// public List<Image> getImg() {
// return img;
// }
// public void setImg(List<Image> imgList) {
// this.img = imgList;
// }
//
// public class Image {
// private String ref;
// private String src;
//
// public String getRef() {
// return ref;
// }
// public void setRef(String ref) {
// this.ref = ref;
// }
// public String getSrc() {
// return src;
// }
// public void setSrc(String src) {
// this.src = src;
// }
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsDetailConverterFactory.java
// public class NewsDetailConverterFactory extends Converter.Factory{
//
// private JsonParser parser;
//
// public static NewsDetailConverterFactory create() {
// return new NewsDetailConverterFactory();
// }
//
// private NewsDetailConverterFactory() {
// parser = new JsonParser();
// }
//
// @Override
// public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
// return new NewsDetailResponseBodyConverter<NewsDetailBean>(parser);
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/model/NewsDetailHelper.java
import com.bean.simplenews.module.news.model.bean.NewsDetailBean;
import com.bean.simplenews.module.news.model.converter.NewsDetailConverterFactory;
import com.bean.simplenews.util.LogUtils;
import java.util.Hashtable;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
package com.bean.simplenews.module.news.model;
public class NewsDetailHelper {
private Retrofit retrofit;
private NewsDetailService service; | private Hashtable<String,Call<NewsDetailBean>> callMap; //Hashtable是线程安全的 |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/model/NewsDetailHelper.java | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsDetailBean.java
// public class NewsDetailBean implements Serializable {
//
// private String title;
// private String body;
// private List<Image> img; //图片列表
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getBody() {
// return body;
// }
// public void setBody(String body) {
// this.body = body;
// }
// public List<Image> getImg() {
// return img;
// }
// public void setImg(List<Image> imgList) {
// this.img = imgList;
// }
//
// public class Image {
// private String ref;
// private String src;
//
// public String getRef() {
// return ref;
// }
// public void setRef(String ref) {
// this.ref = ref;
// }
// public String getSrc() {
// return src;
// }
// public void setSrc(String src) {
// this.src = src;
// }
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsDetailConverterFactory.java
// public class NewsDetailConverterFactory extends Converter.Factory{
//
// private JsonParser parser;
//
// public static NewsDetailConverterFactory create() {
// return new NewsDetailConverterFactory();
// }
//
// private NewsDetailConverterFactory() {
// parser = new JsonParser();
// }
//
// @Override
// public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
// return new NewsDetailResponseBodyConverter<NewsDetailBean>(parser);
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
| import com.bean.simplenews.module.news.model.bean.NewsDetailBean;
import com.bean.simplenews.module.news.model.converter.NewsDetailConverterFactory;
import com.bean.simplenews.util.LogUtils;
import java.util.Hashtable;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit; | package com.bean.simplenews.module.news.model;
public class NewsDetailHelper {
private Retrofit retrofit;
private NewsDetailService service;
private Hashtable<String,Call<NewsDetailBean>> callMap; //Hashtable是线程安全的
private static NewsDetailHelper instance;
private NewsDetailHelper(){
retrofit=new Retrofit.Builder()
.baseUrl("http://c.m.163.com/nc/article/") | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsDetailBean.java
// public class NewsDetailBean implements Serializable {
//
// private String title;
// private String body;
// private List<Image> img; //图片列表
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getBody() {
// return body;
// }
// public void setBody(String body) {
// this.body = body;
// }
// public List<Image> getImg() {
// return img;
// }
// public void setImg(List<Image> imgList) {
// this.img = imgList;
// }
//
// public class Image {
// private String ref;
// private String src;
//
// public String getRef() {
// return ref;
// }
// public void setRef(String ref) {
// this.ref = ref;
// }
// public String getSrc() {
// return src;
// }
// public void setSrc(String src) {
// this.src = src;
// }
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsDetailConverterFactory.java
// public class NewsDetailConverterFactory extends Converter.Factory{
//
// private JsonParser parser;
//
// public static NewsDetailConverterFactory create() {
// return new NewsDetailConverterFactory();
// }
//
// private NewsDetailConverterFactory() {
// parser = new JsonParser();
// }
//
// @Override
// public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
// return new NewsDetailResponseBodyConverter<NewsDetailBean>(parser);
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/model/NewsDetailHelper.java
import com.bean.simplenews.module.news.model.bean.NewsDetailBean;
import com.bean.simplenews.module.news.model.converter.NewsDetailConverterFactory;
import com.bean.simplenews.util.LogUtils;
import java.util.Hashtable;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
package com.bean.simplenews.module.news.model;
public class NewsDetailHelper {
private Retrofit retrofit;
private NewsDetailService service;
private Hashtable<String,Call<NewsDetailBean>> callMap; //Hashtable是线程安全的
private static NewsDetailHelper instance;
private NewsDetailHelper(){
retrofit=new Retrofit.Builder()
.baseUrl("http://c.m.163.com/nc/article/") | .addConverterFactory(NewsDetailConverterFactory.create()) |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsDetailConverterFactory.java | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsDetailBean.java
// public class NewsDetailBean implements Serializable {
//
// private String title;
// private String body;
// private List<Image> img; //图片列表
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getBody() {
// return body;
// }
// public void setBody(String body) {
// this.body = body;
// }
// public List<Image> getImg() {
// return img;
// }
// public void setImg(List<Image> imgList) {
// this.img = imgList;
// }
//
// public class Image {
// private String ref;
// private String src;
//
// public String getRef() {
// return ref;
// }
// public void setRef(String ref) {
// this.ref = ref;
// }
// public String getSrc() {
// return src;
// }
// public void setSrc(String src) {
// this.src = src;
// }
// }
// }
| import com.bean.simplenews.module.news.model.bean.NewsDetailBean;
import com.google.gson.JsonParser;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit; | package com.bean.simplenews.module.news.model.converter;
public class NewsDetailConverterFactory extends Converter.Factory{
private JsonParser parser;
public static NewsDetailConverterFactory create() {
return new NewsDetailConverterFactory();
}
private NewsDetailConverterFactory() {
parser = new JsonParser();
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsDetailBean.java
// public class NewsDetailBean implements Serializable {
//
// private String title;
// private String body;
// private List<Image> img; //图片列表
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getBody() {
// return body;
// }
// public void setBody(String body) {
// this.body = body;
// }
// public List<Image> getImg() {
// return img;
// }
// public void setImg(List<Image> imgList) {
// this.img = imgList;
// }
//
// public class Image {
// private String ref;
// private String src;
//
// public String getRef() {
// return ref;
// }
// public void setRef(String ref) {
// this.ref = ref;
// }
// public String getSrc() {
// return src;
// }
// public void setSrc(String src) {
// this.src = src;
// }
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsDetailConverterFactory.java
import com.bean.simplenews.module.news.model.bean.NewsDetailBean;
import com.google.gson.JsonParser;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
package com.bean.simplenews.module.news.model.converter;
public class NewsDetailConverterFactory extends Converter.Factory{
private JsonParser parser;
public static NewsDetailConverterFactory create() {
return new NewsDetailConverterFactory();
}
private NewsDetailConverterFactory() {
parser = new JsonParser();
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { | return new NewsDetailResponseBodyConverter<NewsDetailBean>(parser); |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsListConverterFactory.java | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
| import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.LogUtils;
import com.google.gson.JsonParser;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit; | package com.bean.simplenews.module.news.model.converter;
public final class NewsListConverterFactory extends Converter.Factory{
private JsonParser parser;
public static NewsListConverterFactory create() { | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsListConverterFactory.java
import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.LogUtils;
import com.google.gson.JsonParser;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
package com.bean.simplenews.module.news.model.converter;
public final class NewsListConverterFactory extends Converter.Factory{
private JsonParser parser;
public static NewsListConverterFactory create() { | LogUtils.e("fuck","factory created"); |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsListConverterFactory.java | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
| import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.LogUtils;
import com.google.gson.JsonParser;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit; | package com.bean.simplenews.module.news.model.converter;
public final class NewsListConverterFactory extends Converter.Factory{
private JsonParser parser;
public static NewsListConverterFactory create() {
LogUtils.e("fuck","factory created");
return new NewsListConverterFactory();
}
private NewsListConverterFactory() {
parser=new JsonParser();
}
/*这个方法每一次http请求都被调用,返回一个新建的Converter对象,因此每一个http线程都持有一个Converter对象,
*彼此不会发生冲突。
*/
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsListConverterFactory.java
import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.LogUtils;
import com.google.gson.JsonParser;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
package com.bean.simplenews.module.news.model.converter;
public final class NewsListConverterFactory extends Converter.Factory{
private JsonParser parser;
public static NewsListConverterFactory create() {
LogUtils.e("fuck","factory created");
return new NewsListConverterFactory();
}
private NewsListConverterFactory() {
parser=new JsonParser();
}
/*这个方法每一次http请求都被调用,返回一个新建的Converter对象,因此每一个http线程都持有一个Converter对象,
*彼此不会发生冲突。
*/
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { | return new NewsListResponseBodyConverter<List<NewsBean>>(parser); |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsDetailResponseBodyConverter.java | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsDetailBean.java
// public class NewsDetailBean implements Serializable {
//
// private String title;
// private String body;
// private List<Image> img; //图片列表
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getBody() {
// return body;
// }
// public void setBody(String body) {
// this.body = body;
// }
// public List<Image> getImg() {
// return img;
// }
// public void setImg(List<Image> imgList) {
// this.img = imgList;
// }
//
// public class Image {
// private String ref;
// private String src;
//
// public String getRef() {
// return ref;
// }
// public void setRef(String ref) {
// this.ref = ref;
// }
// public String getSrc() {
// return src;
// }
// public void setSrc(String src) {
// this.src = src;
// }
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/JsonUtils.java
// public class JsonUtils {
//
// private static Gson mGson = new Gson();
//
// /**
// * 将对象准换为json字符串
// * @param object
// * @param <T>
// * @return
// */
// public static <T> String serialize(T object) {
// return mGson.toJson(object);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json对象转换为实体对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// * @throws JsonSyntaxException
// */
// public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param type
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Type type) throws JsonSyntaxException {
// return mGson.fromJson(json, type);
// }
//
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
| import com.bean.simplenews.module.news.model.bean.NewsDetailBean;
import com.bean.simplenews.util.JsonUtils;
import com.bean.simplenews.util.LogUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Converter; | package com.bean.simplenews.module.news.model.converter;
public class NewsDetailResponseBodyConverter<T> implements Converter<ResponseBody,T> {
private JsonParser parser;
NewsDetailResponseBodyConverter(JsonParser jsonPaser) {
parser = jsonPaser;
}
@Override
public T convert(ResponseBody body) throws IOException { | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsDetailBean.java
// public class NewsDetailBean implements Serializable {
//
// private String title;
// private String body;
// private List<Image> img; //图片列表
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getBody() {
// return body;
// }
// public void setBody(String body) {
// this.body = body;
// }
// public List<Image> getImg() {
// return img;
// }
// public void setImg(List<Image> imgList) {
// this.img = imgList;
// }
//
// public class Image {
// private String ref;
// private String src;
//
// public String getRef() {
// return ref;
// }
// public void setRef(String ref) {
// this.ref = ref;
// }
// public String getSrc() {
// return src;
// }
// public void setSrc(String src) {
// this.src = src;
// }
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/JsonUtils.java
// public class JsonUtils {
//
// private static Gson mGson = new Gson();
//
// /**
// * 将对象准换为json字符串
// * @param object
// * @param <T>
// * @return
// */
// public static <T> String serialize(T object) {
// return mGson.toJson(object);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json对象转换为实体对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// * @throws JsonSyntaxException
// */
// public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param type
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Type type) throws JsonSyntaxException {
// return mGson.fromJson(json, type);
// }
//
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsDetailResponseBodyConverter.java
import com.bean.simplenews.module.news.model.bean.NewsDetailBean;
import com.bean.simplenews.util.JsonUtils;
import com.bean.simplenews.util.LogUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Converter;
package com.bean.simplenews.module.news.model.converter;
public class NewsDetailResponseBodyConverter<T> implements Converter<ResponseBody,T> {
private JsonParser parser;
NewsDetailResponseBodyConverter(JsonParser jsonPaser) {
parser = jsonPaser;
}
@Override
public T convert(ResponseBody body) throws IOException { | NewsDetailBean newsDetailBean; |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsDetailResponseBodyConverter.java | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsDetailBean.java
// public class NewsDetailBean implements Serializable {
//
// private String title;
// private String body;
// private List<Image> img; //图片列表
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getBody() {
// return body;
// }
// public void setBody(String body) {
// this.body = body;
// }
// public List<Image> getImg() {
// return img;
// }
// public void setImg(List<Image> imgList) {
// this.img = imgList;
// }
//
// public class Image {
// private String ref;
// private String src;
//
// public String getRef() {
// return ref;
// }
// public void setRef(String ref) {
// this.ref = ref;
// }
// public String getSrc() {
// return src;
// }
// public void setSrc(String src) {
// this.src = src;
// }
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/JsonUtils.java
// public class JsonUtils {
//
// private static Gson mGson = new Gson();
//
// /**
// * 将对象准换为json字符串
// * @param object
// * @param <T>
// * @return
// */
// public static <T> String serialize(T object) {
// return mGson.toJson(object);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json对象转换为实体对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// * @throws JsonSyntaxException
// */
// public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param type
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Type type) throws JsonSyntaxException {
// return mGson.fromJson(json, type);
// }
//
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
| import com.bean.simplenews.module.news.model.bean.NewsDetailBean;
import com.bean.simplenews.util.JsonUtils;
import com.bean.simplenews.util.LogUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Converter; | package com.bean.simplenews.module.news.model.converter;
public class NewsDetailResponseBodyConverter<T> implements Converter<ResponseBody,T> {
private JsonParser parser;
NewsDetailResponseBodyConverter(JsonParser jsonPaser) {
parser = jsonPaser;
}
@Override
public T convert(ResponseBody body) throws IOException {
NewsDetailBean newsDetailBean;
String value = body.string();
int indexA = value.indexOf('"'); int indexB = value.indexOf('"',5);
String docId = value.substring(indexA+1,indexB);
JsonObject jsonObj = parser.parse(value).getAsJsonObject();
JsonElement jsonElement = jsonObj.get(docId);
if(jsonElement == null) {
return null;
} | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsDetailBean.java
// public class NewsDetailBean implements Serializable {
//
// private String title;
// private String body;
// private List<Image> img; //图片列表
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getBody() {
// return body;
// }
// public void setBody(String body) {
// this.body = body;
// }
// public List<Image> getImg() {
// return img;
// }
// public void setImg(List<Image> imgList) {
// this.img = imgList;
// }
//
// public class Image {
// private String ref;
// private String src;
//
// public String getRef() {
// return ref;
// }
// public void setRef(String ref) {
// this.ref = ref;
// }
// public String getSrc() {
// return src;
// }
// public void setSrc(String src) {
// this.src = src;
// }
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/JsonUtils.java
// public class JsonUtils {
//
// private static Gson mGson = new Gson();
//
// /**
// * 将对象准换为json字符串
// * @param object
// * @param <T>
// * @return
// */
// public static <T> String serialize(T object) {
// return mGson.toJson(object);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json对象转换为实体对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// * @throws JsonSyntaxException
// */
// public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param type
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Type type) throws JsonSyntaxException {
// return mGson.fromJson(json, type);
// }
//
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsDetailResponseBodyConverter.java
import com.bean.simplenews.module.news.model.bean.NewsDetailBean;
import com.bean.simplenews.util.JsonUtils;
import com.bean.simplenews.util.LogUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Converter;
package com.bean.simplenews.module.news.model.converter;
public class NewsDetailResponseBodyConverter<T> implements Converter<ResponseBody,T> {
private JsonParser parser;
NewsDetailResponseBodyConverter(JsonParser jsonPaser) {
parser = jsonPaser;
}
@Override
public T convert(ResponseBody body) throws IOException {
NewsDetailBean newsDetailBean;
String value = body.string();
int indexA = value.indexOf('"'); int indexB = value.indexOf('"',5);
String docId = value.substring(indexA+1,indexB);
JsonObject jsonObj = parser.parse(value).getAsJsonObject();
JsonElement jsonElement = jsonObj.get(docId);
if(jsonElement == null) {
return null;
} | newsDetailBean = JsonUtils.deserialize(jsonElement.getAsJsonObject(), NewsDetailBean.class); |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/common/base/BaseActivity.java | // Path: app/src/main/java/com/bean/simplenews/common/Constants.java
// public class Constants {
// public static boolean DEBUG = true;
// public static boolean NIGHT = false;
// public static final String TYPE = "TYPE";
// public static final String NEWS = "NEWS";
// public static final int NEWS_TYPE_TOP = 0;
// public static final int NEWS_TYPE_NBA = 1;
// public static final int NEWS_TYPE_TEC = 2;
// public static final int NEWS_TYPE_FIN = 3;
// public static final int NEWS_TYPE_CARS = 4;
// public static final int NEWS_TYPE_JOKES = 5;
// public static final String prefix =
// "<style type=\"text/css\">body{font-size:100%;text-align:justify;color:#424242;padding:10px;}p{font-weight:500;font-size:0.78em;line-height:1.5;}p strong{font-weight:600}h3{font-size:1.4em}</style><body>";
// public static final String suffix = "</body>";
// }
//
// Path: app/src/main/java/com/bean/simplenews/common/mvp/MVPView.java
// public interface MVPView {
//
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/ToastUtils.java
// public class ToastUtils {
//
// public static void makeToast(Context context, String msg){
// Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
// }
//
// }
| import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import com.bean.simplenews.R;
import com.bean.simplenews.common.Constants;
import com.bean.simplenews.common.mvp.MVPView;
import com.bean.simplenews.util.LogUtils;
import com.bean.simplenews.util.ToastUtils;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask; | package com.bean.simplenews.common.base;
public class BaseActivity<P extends BasePresenter> extends AppCompatActivity{
private P Presenter;
private boolean isExit=false;
private boolean isDoubleToExit=false;
@Override
protected void onDestroy() {
if(Presenter!=null){
Presenter.onDestroy();
Presenter=null;
}
super.onDestroy();
}
@Override
public void onBackPressed() {
if(!isDoubleToExit){
super.onBackPressed();
}else if (!isExit) {
isExit=true; | // Path: app/src/main/java/com/bean/simplenews/common/Constants.java
// public class Constants {
// public static boolean DEBUG = true;
// public static boolean NIGHT = false;
// public static final String TYPE = "TYPE";
// public static final String NEWS = "NEWS";
// public static final int NEWS_TYPE_TOP = 0;
// public static final int NEWS_TYPE_NBA = 1;
// public static final int NEWS_TYPE_TEC = 2;
// public static final int NEWS_TYPE_FIN = 3;
// public static final int NEWS_TYPE_CARS = 4;
// public static final int NEWS_TYPE_JOKES = 5;
// public static final String prefix =
// "<style type=\"text/css\">body{font-size:100%;text-align:justify;color:#424242;padding:10px;}p{font-weight:500;font-size:0.78em;line-height:1.5;}p strong{font-weight:600}h3{font-size:1.4em}</style><body>";
// public static final String suffix = "</body>";
// }
//
// Path: app/src/main/java/com/bean/simplenews/common/mvp/MVPView.java
// public interface MVPView {
//
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/ToastUtils.java
// public class ToastUtils {
//
// public static void makeToast(Context context, String msg){
// Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
// }
//
// }
// Path: app/src/main/java/com/bean/simplenews/common/base/BaseActivity.java
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import com.bean.simplenews.R;
import com.bean.simplenews.common.Constants;
import com.bean.simplenews.common.mvp.MVPView;
import com.bean.simplenews.util.LogUtils;
import com.bean.simplenews.util.ToastUtils;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;
package com.bean.simplenews.common.base;
public class BaseActivity<P extends BasePresenter> extends AppCompatActivity{
private P Presenter;
private boolean isExit=false;
private boolean isDoubleToExit=false;
@Override
protected void onDestroy() {
if(Presenter!=null){
Presenter.onDestroy();
Presenter=null;
}
super.onDestroy();
}
@Override
public void onBackPressed() {
if(!isDoubleToExit){
super.onBackPressed();
}else if (!isExit) {
isExit=true; | ToastUtils.makeToast(this,getString(R.string.exit_message)); |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/common/base/BaseActivity.java | // Path: app/src/main/java/com/bean/simplenews/common/Constants.java
// public class Constants {
// public static boolean DEBUG = true;
// public static boolean NIGHT = false;
// public static final String TYPE = "TYPE";
// public static final String NEWS = "NEWS";
// public static final int NEWS_TYPE_TOP = 0;
// public static final int NEWS_TYPE_NBA = 1;
// public static final int NEWS_TYPE_TEC = 2;
// public static final int NEWS_TYPE_FIN = 3;
// public static final int NEWS_TYPE_CARS = 4;
// public static final int NEWS_TYPE_JOKES = 5;
// public static final String prefix =
// "<style type=\"text/css\">body{font-size:100%;text-align:justify;color:#424242;padding:10px;}p{font-weight:500;font-size:0.78em;line-height:1.5;}p strong{font-weight:600}h3{font-size:1.4em}</style><body>";
// public static final String suffix = "</body>";
// }
//
// Path: app/src/main/java/com/bean/simplenews/common/mvp/MVPView.java
// public interface MVPView {
//
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/ToastUtils.java
// public class ToastUtils {
//
// public static void makeToast(Context context, String msg){
// Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
// }
//
// }
| import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import com.bean.simplenews.R;
import com.bean.simplenews.common.Constants;
import com.bean.simplenews.common.mvp.MVPView;
import com.bean.simplenews.util.LogUtils;
import com.bean.simplenews.util.ToastUtils;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask; | Presenter=null;
}
super.onDestroy();
}
@Override
public void onBackPressed() {
if(!isDoubleToExit){
super.onBackPressed();
}else if (!isExit) {
isExit=true;
ToastUtils.makeToast(this,getString(R.string.exit_message));
new Timer().schedule(new TimerTask() {
@Override
public void run() {
isExit = false;
} }, 2000);
} else {
finish();
System.exit(0);
}
}
protected void setDoubleToExit(boolean bool){
isDoubleToExit=bool;
}
// this method must be called in every activity
protected boolean initPresenter(P presenter){
if(presenter==null){ | // Path: app/src/main/java/com/bean/simplenews/common/Constants.java
// public class Constants {
// public static boolean DEBUG = true;
// public static boolean NIGHT = false;
// public static final String TYPE = "TYPE";
// public static final String NEWS = "NEWS";
// public static final int NEWS_TYPE_TOP = 0;
// public static final int NEWS_TYPE_NBA = 1;
// public static final int NEWS_TYPE_TEC = 2;
// public static final int NEWS_TYPE_FIN = 3;
// public static final int NEWS_TYPE_CARS = 4;
// public static final int NEWS_TYPE_JOKES = 5;
// public static final String prefix =
// "<style type=\"text/css\">body{font-size:100%;text-align:justify;color:#424242;padding:10px;}p{font-weight:500;font-size:0.78em;line-height:1.5;}p strong{font-weight:600}h3{font-size:1.4em}</style><body>";
// public static final String suffix = "</body>";
// }
//
// Path: app/src/main/java/com/bean/simplenews/common/mvp/MVPView.java
// public interface MVPView {
//
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/ToastUtils.java
// public class ToastUtils {
//
// public static void makeToast(Context context, String msg){
// Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
// }
//
// }
// Path: app/src/main/java/com/bean/simplenews/common/base/BaseActivity.java
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import com.bean.simplenews.R;
import com.bean.simplenews.common.Constants;
import com.bean.simplenews.common.mvp.MVPView;
import com.bean.simplenews.util.LogUtils;
import com.bean.simplenews.util.ToastUtils;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;
Presenter=null;
}
super.onDestroy();
}
@Override
public void onBackPressed() {
if(!isDoubleToExit){
super.onBackPressed();
}else if (!isExit) {
isExit=true;
ToastUtils.makeToast(this,getString(R.string.exit_message));
new Timer().schedule(new TimerTask() {
@Override
public void run() {
isExit = false;
} }, 2000);
} else {
finish();
System.exit(0);
}
}
protected void setDoubleToExit(boolean bool){
isDoubleToExit=bool;
}
// this method must be called in every activity
protected boolean initPresenter(P presenter){
if(presenter==null){ | LogUtils.e("BaseActivity","presenter is null"); |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsListResponseBodyConverter.java | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/JsonUtils.java
// public class JsonUtils {
//
// private static Gson mGson = new Gson();
//
// /**
// * 将对象准换为json字符串
// * @param object
// * @param <T>
// * @return
// */
// public static <T> String serialize(T object) {
// return mGson.toJson(object);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json对象转换为实体对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// * @throws JsonSyntaxException
// */
// public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param type
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Type type) throws JsonSyntaxException {
// return mGson.fromJson(json, type);
// }
//
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
| import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.JsonUtils;
import com.bean.simplenews.util.LogUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Converter; | package com.bean.simplenews.module.news.model.converter;
final class NewsListResponseBodyConverter<T> implements Converter<ResponseBody,T> {
private JsonParser parser;
NewsListResponseBodyConverter(JsonParser jsonParser){
parser=jsonParser;
}
@Override public T convert(ResponseBody body) throws IOException {
| // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/JsonUtils.java
// public class JsonUtils {
//
// private static Gson mGson = new Gson();
//
// /**
// * 将对象准换为json字符串
// * @param object
// * @param <T>
// * @return
// */
// public static <T> String serialize(T object) {
// return mGson.toJson(object);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json对象转换为实体对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// * @throws JsonSyntaxException
// */
// public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param type
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Type type) throws JsonSyntaxException {
// return mGson.fromJson(json, type);
// }
//
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsListResponseBodyConverter.java
import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.JsonUtils;
import com.bean.simplenews.util.LogUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Converter;
package com.bean.simplenews.module.news.model.converter;
final class NewsListResponseBodyConverter<T> implements Converter<ResponseBody,T> {
private JsonParser parser;
NewsListResponseBodyConverter(JsonParser jsonParser){
parser=jsonParser;
}
@Override public T convert(ResponseBody body) throws IOException {
| List<NewsBean> beans = new ArrayList<>(); |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsListResponseBodyConverter.java | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/JsonUtils.java
// public class JsonUtils {
//
// private static Gson mGson = new Gson();
//
// /**
// * 将对象准换为json字符串
// * @param object
// * @param <T>
// * @return
// */
// public static <T> String serialize(T object) {
// return mGson.toJson(object);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json对象转换为实体对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// * @throws JsonSyntaxException
// */
// public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param type
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Type type) throws JsonSyntaxException {
// return mGson.fromJson(json, type);
// }
//
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
| import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.JsonUtils;
import com.bean.simplenews.util.LogUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Converter; | package com.bean.simplenews.module.news.model.converter;
final class NewsListResponseBodyConverter<T> implements Converter<ResponseBody,T> {
private JsonParser parser;
NewsListResponseBodyConverter(JsonParser jsonParser){
parser=jsonParser;
}
@Override public T convert(ResponseBody body) throws IOException {
List<NewsBean> beans = new ArrayList<>();
String value = body.string();
int indexA = value.indexOf('"'); int indexB = value.indexOf('"',5);
String typeId = value.substring(indexA+1,indexB);
JsonObject jsonObj = parser.parse(value).getAsJsonObject();
JsonElement jsonElement = jsonObj.get(typeId);
if(jsonElement == null) { | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/JsonUtils.java
// public class JsonUtils {
//
// private static Gson mGson = new Gson();
//
// /**
// * 将对象准换为json字符串
// * @param object
// * @param <T>
// * @return
// */
// public static <T> String serialize(T object) {
// return mGson.toJson(object);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json对象转换为实体对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// * @throws JsonSyntaxException
// */
// public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param type
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Type type) throws JsonSyntaxException {
// return mGson.fromJson(json, type);
// }
//
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsListResponseBodyConverter.java
import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.JsonUtils;
import com.bean.simplenews.util.LogUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Converter;
package com.bean.simplenews.module.news.model.converter;
final class NewsListResponseBodyConverter<T> implements Converter<ResponseBody,T> {
private JsonParser parser;
NewsListResponseBodyConverter(JsonParser jsonParser){
parser=jsonParser;
}
@Override public T convert(ResponseBody body) throws IOException {
List<NewsBean> beans = new ArrayList<>();
String value = body.string();
int indexA = value.indexOf('"'); int indexB = value.indexOf('"',5);
String typeId = value.substring(indexA+1,indexB);
JsonObject jsonObj = parser.parse(value).getAsJsonObject();
JsonElement jsonElement = jsonObj.get(typeId);
if(jsonElement == null) { | LogUtils.e("fuck","jsonElement is null"); |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsListResponseBodyConverter.java | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/JsonUtils.java
// public class JsonUtils {
//
// private static Gson mGson = new Gson();
//
// /**
// * 将对象准换为json字符串
// * @param object
// * @param <T>
// * @return
// */
// public static <T> String serialize(T object) {
// return mGson.toJson(object);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json对象转换为实体对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// * @throws JsonSyntaxException
// */
// public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param type
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Type type) throws JsonSyntaxException {
// return mGson.fromJson(json, type);
// }
//
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
| import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.JsonUtils;
import com.bean.simplenews.util.LogUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Converter; | package com.bean.simplenews.module.news.model.converter;
final class NewsListResponseBodyConverter<T> implements Converter<ResponseBody,T> {
private JsonParser parser;
NewsListResponseBodyConverter(JsonParser jsonParser){
parser=jsonParser;
}
@Override public T convert(ResponseBody body) throws IOException {
List<NewsBean> beans = new ArrayList<>();
String value = body.string();
int indexA = value.indexOf('"'); int indexB = value.indexOf('"',5);
String typeId = value.substring(indexA+1,indexB);
JsonObject jsonObj = parser.parse(value).getAsJsonObject();
JsonElement jsonElement = jsonObj.get(typeId);
if(jsonElement == null) {
LogUtils.e("fuck","jsonElement is null");
return null;
}
JsonArray jsonArray = jsonElement.getAsJsonArray();
int arraySize = jsonArray.size();
if (arraySize > 1){
for (int i =0; i < arraySize; i++) {
JsonObject jo = jsonArray.get(i).getAsJsonObject();
if (jo.has("skipType") && "special".equals(jo.get("skipType").getAsString())) { // 除去专题
continue;
}
if (jo.has("imgextra") && !jo.has("hasCover")){ // 除去图集,但保留页头
continue;
} | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/JsonUtils.java
// public class JsonUtils {
//
// private static Gson mGson = new Gson();
//
// /**
// * 将对象准换为json字符串
// * @param object
// * @param <T>
// * @return
// */
// public static <T> String serialize(T object) {
// return mGson.toJson(object);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json对象转换为实体对象
// * @param json
// * @param clz
// * @param <T>
// * @return
// * @throws JsonSyntaxException
// */
// public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException {
// return mGson.fromJson(json, clz);
// }
//
// /**
// * 将json字符串转换为对象
// * @param json
// * @param type
// * @param <T>
// * @return
// */
// public static <T> T deserialize(String json, Type type) throws JsonSyntaxException {
// return mGson.fromJson(json, type);
// }
//
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/model/converter/NewsListResponseBodyConverter.java
import com.bean.simplenews.module.news.model.bean.NewsBean;
import com.bean.simplenews.util.JsonUtils;
import com.bean.simplenews.util.LogUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Converter;
package com.bean.simplenews.module.news.model.converter;
final class NewsListResponseBodyConverter<T> implements Converter<ResponseBody,T> {
private JsonParser parser;
NewsListResponseBodyConverter(JsonParser jsonParser){
parser=jsonParser;
}
@Override public T convert(ResponseBody body) throws IOException {
List<NewsBean> beans = new ArrayList<>();
String value = body.string();
int indexA = value.indexOf('"'); int indexB = value.indexOf('"',5);
String typeId = value.substring(indexA+1,indexB);
JsonObject jsonObj = parser.parse(value).getAsJsonObject();
JsonElement jsonElement = jsonObj.get(typeId);
if(jsonElement == null) {
LogUtils.e("fuck","jsonElement is null");
return null;
}
JsonArray jsonArray = jsonElement.getAsJsonArray();
int arraySize = jsonArray.size();
if (arraySize > 1){
for (int i =0; i < arraySize; i++) {
JsonObject jo = jsonArray.get(i).getAsJsonObject();
if (jo.has("skipType") && "special".equals(jo.get("skipType").getAsString())) { // 除去专题
continue;
}
if (jo.has("imgextra") && !jo.has("hasCover")){ // 除去图集,但保留页头
continue;
} | NewsBean news = JsonUtils.deserialize(jo, NewsBean.class); |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/model/NewsDetailService.java | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsDetailBean.java
// public class NewsDetailBean implements Serializable {
//
// private String title;
// private String body;
// private List<Image> img; //图片列表
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getBody() {
// return body;
// }
// public void setBody(String body) {
// this.body = body;
// }
// public List<Image> getImg() {
// return img;
// }
// public void setImg(List<Image> imgList) {
// this.img = imgList;
// }
//
// public class Image {
// private String ref;
// private String src;
//
// public String getRef() {
// return ref;
// }
// public void setRef(String ref) {
// this.ref = ref;
// }
// public String getSrc() {
// return src;
// }
// public void setSrc(String src) {
// this.src = src;
// }
// }
// }
| import com.bean.simplenews.module.news.model.bean.NewsDetailBean;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path; | package com.bean.simplenews.module.news.model;
public interface NewsDetailService {
//http://c.m.163.com/nc/article/{docId}/full.html
@GET("{docId}/full.html") | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsDetailBean.java
// public class NewsDetailBean implements Serializable {
//
// private String title;
// private String body;
// private List<Image> img; //图片列表
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getBody() {
// return body;
// }
// public void setBody(String body) {
// this.body = body;
// }
// public List<Image> getImg() {
// return img;
// }
// public void setImg(List<Image> imgList) {
// this.img = imgList;
// }
//
// public class Image {
// private String ref;
// private String src;
//
// public String getRef() {
// return ref;
// }
// public void setRef(String ref) {
// this.ref = ref;
// }
// public String getSrc() {
// return src;
// }
// public void setSrc(String src) {
// this.src = src;
// }
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/model/NewsDetailService.java
import com.bean.simplenews.module.news.model.bean.NewsDetailBean;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
package com.bean.simplenews.module.news.model;
public interface NewsDetailService {
//http://c.m.163.com/nc/article/{docId}/full.html
@GET("{docId}/full.html") | Call<NewsDetailBean> loadNewsDetail(@Path("docId") String id); |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/model/NewsListService.java | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
| import com.bean.simplenews.module.news.model.bean.NewsBean;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path; | package com.bean.simplenews.module.news.model;
public interface NewsListService {
// http://c.m.163.com/nc/article/headline/T1348647909107/40-20.html
@GET("{category}/{id}/{pageIndex}-20.html") | // Path: app/src/main/java/com/bean/simplenews/module/news/model/bean/NewsBean.java
// public class NewsBean implements Serializable {
//
// private String docid;
// private String title;
// private String imgsrc; //图片地址
// private String ptime; //时间
// private String replyCount;
//
// public String getDocid() {
// return docid;
// }
// public void setDocid(String docid) {
// this.docid = docid;
// }
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getImgsrc() {
// return imgsrc;
// }
// public void setImgsrc(String imgsrc) {
// this.imgsrc = imgsrc;
// }
// public String getPtime() {
// return ptime.substring(5, 10);
// }
// public void setPtime(String ptime) {
// this.ptime = ptime;
// }
// public String getReplyCount() {
// return replyCount;
// }
// public void setReplyCount(String replyCount) {
// this.replyCount = replyCount;
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/model/NewsListService.java
import com.bean.simplenews.module.news.model.bean.NewsBean;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
package com.bean.simplenews.module.news.model;
public interface NewsListService {
// http://c.m.163.com/nc/article/headline/T1348647909107/40-20.html
@GET("{category}/{id}/{pageIndex}-20.html") | Call<List<NewsBean>> loadNews(@Path("category") String category, |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/widget/NewsFragment.java | // Path: app/src/main/java/com/bean/simplenews/common/Constants.java
// public class Constants {
// public static boolean DEBUG = true;
// public static boolean NIGHT = false;
// public static final String TYPE = "TYPE";
// public static final String NEWS = "NEWS";
// public static final int NEWS_TYPE_TOP = 0;
// public static final int NEWS_TYPE_NBA = 1;
// public static final int NEWS_TYPE_TEC = 2;
// public static final int NEWS_TYPE_FIN = 3;
// public static final int NEWS_TYPE_CARS = 4;
// public static final int NEWS_TYPE_JOKES = 5;
// public static final String prefix =
// "<style type=\"text/css\">body{font-size:100%;text-align:justify;color:#424242;padding:10px;}p{font-weight:500;font-size:0.78em;line-height:1.5;}p strong{font-weight:600}h3{font-size:1.4em}</style><body>";
// public static final String suffix = "</body>";
// }
//
// Path: app/src/main/java/com/bean/simplenews/common/adapter/BaseFragmentPagerAdapter.java
// public class BaseFragmentPagerAdapter extends FragmentPagerAdapter{
//
// private final List<Fragment> mFragments = new ArrayList<>();
// private final List<String> mFragmentTitles = new ArrayList<>();
//
// public BaseFragmentPagerAdapter(FragmentManager fm) {
// super(fm);
// }
//
// public void addFragment(Fragment fragment, String title) {
// mFragments.add(fragment);
// mFragmentTitles.add(title);
// }
//
// @Override
// public Fragment getItem(int position) {
// return mFragments.get(position);
// }
//
// @Override
// public int getCount() {
// return mFragments.size();
// }
//
// @Override
// public CharSequence getPageTitle(int position) {
// return mFragmentTitles.get(position);
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bean.simplenews.R;
import com.bean.simplenews.common.Constants;
import com.bean.simplenews.common.adapter.BaseFragmentPagerAdapter;
import com.bean.simplenews.util.LogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder; | package com.bean.simplenews.module.news.widget;
public class NewsFragment extends Fragment {
@BindView(R.id.tab_layout)
TabLayout mTabLayout;
@BindView(R.id.viewpager)
ViewPager mViewPager;
private Unbinder unbinder;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_news, null);
unbinder=ButterKnife.bind(this, view);
| // Path: app/src/main/java/com/bean/simplenews/common/Constants.java
// public class Constants {
// public static boolean DEBUG = true;
// public static boolean NIGHT = false;
// public static final String TYPE = "TYPE";
// public static final String NEWS = "NEWS";
// public static final int NEWS_TYPE_TOP = 0;
// public static final int NEWS_TYPE_NBA = 1;
// public static final int NEWS_TYPE_TEC = 2;
// public static final int NEWS_TYPE_FIN = 3;
// public static final int NEWS_TYPE_CARS = 4;
// public static final int NEWS_TYPE_JOKES = 5;
// public static final String prefix =
// "<style type=\"text/css\">body{font-size:100%;text-align:justify;color:#424242;padding:10px;}p{font-weight:500;font-size:0.78em;line-height:1.5;}p strong{font-weight:600}h3{font-size:1.4em}</style><body>";
// public static final String suffix = "</body>";
// }
//
// Path: app/src/main/java/com/bean/simplenews/common/adapter/BaseFragmentPagerAdapter.java
// public class BaseFragmentPagerAdapter extends FragmentPagerAdapter{
//
// private final List<Fragment> mFragments = new ArrayList<>();
// private final List<String> mFragmentTitles = new ArrayList<>();
//
// public BaseFragmentPagerAdapter(FragmentManager fm) {
// super(fm);
// }
//
// public void addFragment(Fragment fragment, String title) {
// mFragments.add(fragment);
// mFragmentTitles.add(title);
// }
//
// @Override
// public Fragment getItem(int position) {
// return mFragments.get(position);
// }
//
// @Override
// public int getCount() {
// return mFragments.size();
// }
//
// @Override
// public CharSequence getPageTitle(int position) {
// return mFragmentTitles.get(position);
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/widget/NewsFragment.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bean.simplenews.R;
import com.bean.simplenews.common.Constants;
import com.bean.simplenews.common.adapter.BaseFragmentPagerAdapter;
import com.bean.simplenews.util.LogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
package com.bean.simplenews.module.news.widget;
public class NewsFragment extends Fragment {
@BindView(R.id.tab_layout)
TabLayout mTabLayout;
@BindView(R.id.viewpager)
ViewPager mViewPager;
private Unbinder unbinder;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_news, null);
unbinder=ButterKnife.bind(this, view);
| BaseFragmentPagerAdapter adapter = new BaseFragmentPagerAdapter(getChildFragmentManager()); |
binzhihao/Reader | app/src/main/java/com/bean/simplenews/module/news/widget/NewsFragment.java | // Path: app/src/main/java/com/bean/simplenews/common/Constants.java
// public class Constants {
// public static boolean DEBUG = true;
// public static boolean NIGHT = false;
// public static final String TYPE = "TYPE";
// public static final String NEWS = "NEWS";
// public static final int NEWS_TYPE_TOP = 0;
// public static final int NEWS_TYPE_NBA = 1;
// public static final int NEWS_TYPE_TEC = 2;
// public static final int NEWS_TYPE_FIN = 3;
// public static final int NEWS_TYPE_CARS = 4;
// public static final int NEWS_TYPE_JOKES = 5;
// public static final String prefix =
// "<style type=\"text/css\">body{font-size:100%;text-align:justify;color:#424242;padding:10px;}p{font-weight:500;font-size:0.78em;line-height:1.5;}p strong{font-weight:600}h3{font-size:1.4em}</style><body>";
// public static final String suffix = "</body>";
// }
//
// Path: app/src/main/java/com/bean/simplenews/common/adapter/BaseFragmentPagerAdapter.java
// public class BaseFragmentPagerAdapter extends FragmentPagerAdapter{
//
// private final List<Fragment> mFragments = new ArrayList<>();
// private final List<String> mFragmentTitles = new ArrayList<>();
//
// public BaseFragmentPagerAdapter(FragmentManager fm) {
// super(fm);
// }
//
// public void addFragment(Fragment fragment, String title) {
// mFragments.add(fragment);
// mFragmentTitles.add(title);
// }
//
// @Override
// public Fragment getItem(int position) {
// return mFragments.get(position);
// }
//
// @Override
// public int getCount() {
// return mFragments.size();
// }
//
// @Override
// public CharSequence getPageTitle(int position) {
// return mFragmentTitles.get(position);
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bean.simplenews.R;
import com.bean.simplenews.common.Constants;
import com.bean.simplenews.common.adapter.BaseFragmentPagerAdapter;
import com.bean.simplenews.util.LogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder; | package com.bean.simplenews.module.news.widget;
public class NewsFragment extends Fragment {
@BindView(R.id.tab_layout)
TabLayout mTabLayout;
@BindView(R.id.viewpager)
ViewPager mViewPager;
private Unbinder unbinder;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_news, null);
unbinder=ButterKnife.bind(this, view);
BaseFragmentPagerAdapter adapter = new BaseFragmentPagerAdapter(getChildFragmentManager()); | // Path: app/src/main/java/com/bean/simplenews/common/Constants.java
// public class Constants {
// public static boolean DEBUG = true;
// public static boolean NIGHT = false;
// public static final String TYPE = "TYPE";
// public static final String NEWS = "NEWS";
// public static final int NEWS_TYPE_TOP = 0;
// public static final int NEWS_TYPE_NBA = 1;
// public static final int NEWS_TYPE_TEC = 2;
// public static final int NEWS_TYPE_FIN = 3;
// public static final int NEWS_TYPE_CARS = 4;
// public static final int NEWS_TYPE_JOKES = 5;
// public static final String prefix =
// "<style type=\"text/css\">body{font-size:100%;text-align:justify;color:#424242;padding:10px;}p{font-weight:500;font-size:0.78em;line-height:1.5;}p strong{font-weight:600}h3{font-size:1.4em}</style><body>";
// public static final String suffix = "</body>";
// }
//
// Path: app/src/main/java/com/bean/simplenews/common/adapter/BaseFragmentPagerAdapter.java
// public class BaseFragmentPagerAdapter extends FragmentPagerAdapter{
//
// private final List<Fragment> mFragments = new ArrayList<>();
// private final List<String> mFragmentTitles = new ArrayList<>();
//
// public BaseFragmentPagerAdapter(FragmentManager fm) {
// super(fm);
// }
//
// public void addFragment(Fragment fragment, String title) {
// mFragments.add(fragment);
// mFragmentTitles.add(title);
// }
//
// @Override
// public Fragment getItem(int position) {
// return mFragments.get(position);
// }
//
// @Override
// public int getCount() {
// return mFragments.size();
// }
//
// @Override
// public CharSequence getPageTitle(int position) {
// return mFragmentTitles.get(position);
// }
// }
//
// Path: app/src/main/java/com/bean/simplenews/util/LogUtils.java
// public class LogUtils {
//
// public static void v(String tag, String message) {
// if(Constants.DEBUG) {
// Log.v(tag, message);
// }
// }
//
// public static void d(String tag, String message) {
// if(Constants.DEBUG) {
// Log.d(tag, message);
// }
// }
//
// public static void i(String tag, String message) {
// if(Constants.DEBUG) {
// Log.i(tag, message);
// }
// }
//
// public static void w(String tag, String message) {
// if(Constants.DEBUG) {
// Log.w(tag, message);
// }
// }
//
// public static void e(String tag, String message) {
// if(Constants.DEBUG) {
// Log.e(tag, message);
// }
// }
//
// public static void e(String tag, String message, Exception e) {
// if(Constants.DEBUG) {
// Log.e(tag, message, e);
// }
// }
// }
// Path: app/src/main/java/com/bean/simplenews/module/news/widget/NewsFragment.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bean.simplenews.R;
import com.bean.simplenews.common.Constants;
import com.bean.simplenews.common.adapter.BaseFragmentPagerAdapter;
import com.bean.simplenews.util.LogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
package com.bean.simplenews.module.news.widget;
public class NewsFragment extends Fragment {
@BindView(R.id.tab_layout)
TabLayout mTabLayout;
@BindView(R.id.viewpager)
ViewPager mViewPager;
private Unbinder unbinder;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_news, null);
unbinder=ButterKnife.bind(this, view);
BaseFragmentPagerAdapter adapter = new BaseFragmentPagerAdapter(getChildFragmentManager()); | adapter.addFragment(NewsListFragment.newInstance(Constants.NEWS_TYPE_TOP), getString(R.string.top)); |
GoogleCloudPlatform/bank-of-anthos | src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/LedgerWriterController.java | // Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
| import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.micrometer.core.instrument.binder.cache.GuavaCacheMetrics;
import io.micrometer.stackdriver.StackdriverMeterRegistry;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate; | *
* @return HTTP Status 200 if server is ready to receive requests.
*/
@GetMapping("/ready")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<String> readiness() {
return new ResponseEntity<String>(READINESS_CODE, HttpStatus.OK);
}
/**
* Submit a new transaction to the ledger.
*
* @param bearerToken HTTP request 'Authorization' header
* @param transaction transaction to submit
*
* @return HTTP Status 200 if transaction was successfully submitted
*/
@PostMapping(value = "/transactions", consumes = "application/json")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> addTransaction(
@RequestHeader("Authorization") String bearerToken,
@RequestBody Transaction transaction) {
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
bearerToken = bearerToken.split("Bearer ")[1];
}
try {
if (bearerToken == null) {
LOGGER.error("Transaction submission failed: "
+ "Authorization header null");
throw new IllegalArgumentException( | // Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/LedgerWriterController.java
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.micrometer.core.instrument.binder.cache.GuavaCacheMetrics;
import io.micrometer.stackdriver.StackdriverMeterRegistry;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
*
* @return HTTP Status 200 if server is ready to receive requests.
*/
@GetMapping("/ready")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<String> readiness() {
return new ResponseEntity<String>(READINESS_CODE, HttpStatus.OK);
}
/**
* Submit a new transaction to the ledger.
*
* @param bearerToken HTTP request 'Authorization' header
* @param transaction transaction to submit
*
* @return HTTP Status 200 if transaction was successfully submitted
*/
@PostMapping(value = "/transactions", consumes = "application/json")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> addTransaction(
@RequestHeader("Authorization") String bearerToken,
@RequestBody Transaction transaction) {
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
bearerToken = bearerToken.split("Bearer ")[1];
}
try {
if (bearerToken == null) {
LOGGER.error("Transaction submission failed: "
+ "Authorization header null");
throw new IllegalArgumentException( | EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL); |
GoogleCloudPlatform/bank-of-anthos | src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/LedgerWriterController.java | // Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
| import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.micrometer.core.instrument.binder.cache.GuavaCacheMetrics;
import io.micrometer.stackdriver.StackdriverMeterRegistry;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate; | }
/**
* Submit a new transaction to the ledger.
*
* @param bearerToken HTTP request 'Authorization' header
* @param transaction transaction to submit
*
* @return HTTP Status 200 if transaction was successfully submitted
*/
@PostMapping(value = "/transactions", consumes = "application/json")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> addTransaction(
@RequestHeader("Authorization") String bearerToken,
@RequestBody Transaction transaction) {
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
bearerToken = bearerToken.split("Bearer ")[1];
}
try {
if (bearerToken == null) {
LOGGER.error("Transaction submission failed: "
+ "Authorization header null");
throw new IllegalArgumentException(
EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL);
}
final DecodedJWT jwt = this.verifier.verify(bearerToken);
// Check against cache for duplicate transactions
if (this.cache.asMap().containsKey(transaction.getRequestUuid())) {
throw new IllegalStateException( | // Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/LedgerWriterController.java
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.micrometer.core.instrument.binder.cache.GuavaCacheMetrics;
import io.micrometer.stackdriver.StackdriverMeterRegistry;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
}
/**
* Submit a new transaction to the ledger.
*
* @param bearerToken HTTP request 'Authorization' header
* @param transaction transaction to submit
*
* @return HTTP Status 200 if transaction was successfully submitted
*/
@PostMapping(value = "/transactions", consumes = "application/json")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> addTransaction(
@RequestHeader("Authorization") String bearerToken,
@RequestBody Transaction transaction) {
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
bearerToken = bearerToken.split("Bearer ")[1];
}
try {
if (bearerToken == null) {
LOGGER.error("Transaction submission failed: "
+ "Authorization header null");
throw new IllegalArgumentException(
EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL);
}
final DecodedJWT jwt = this.verifier.verify(bearerToken);
// Check against cache for duplicate transactions
if (this.cache.asMap().containsKey(transaction.getRequestUuid())) {
throw new IllegalStateException( | EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION); |
GoogleCloudPlatform/bank-of-anthos | src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/LedgerWriterController.java | // Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
| import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.micrometer.core.instrument.binder.cache.GuavaCacheMetrics;
import io.micrometer.stackdriver.StackdriverMeterRegistry;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate; | @RequestBody Transaction transaction) {
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
bearerToken = bearerToken.split("Bearer ")[1];
}
try {
if (bearerToken == null) {
LOGGER.error("Transaction submission failed: "
+ "Authorization header null");
throw new IllegalArgumentException(
EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL);
}
final DecodedJWT jwt = this.verifier.verify(bearerToken);
// Check against cache for duplicate transactions
if (this.cache.asMap().containsKey(transaction.getRequestUuid())) {
throw new IllegalStateException(
EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION);
}
// validate transaction
transactionValidator.validateTransaction(localRoutingNum,
jwt.getClaim(JWT_ACCOUNT_KEY).asString(), transaction);
// Ensure sender balance can cover transaction.
if (transaction.getFromRoutingNum().equals(localRoutingNum)) {
int balance = getAvailableBalance(
bearerToken, transaction.getFromAccountNum());
if (balance < transaction.getAmount()) {
LOGGER.error("Transaction submission failed: "
+ "Insufficient balance");
throw new IllegalStateException( | // Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/LedgerWriterController.java
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.micrometer.core.instrument.binder.cache.GuavaCacheMetrics;
import io.micrometer.stackdriver.StackdriverMeterRegistry;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
@RequestBody Transaction transaction) {
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
bearerToken = bearerToken.split("Bearer ")[1];
}
try {
if (bearerToken == null) {
LOGGER.error("Transaction submission failed: "
+ "Authorization header null");
throw new IllegalArgumentException(
EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL);
}
final DecodedJWT jwt = this.verifier.verify(bearerToken);
// Check against cache for duplicate transactions
if (this.cache.asMap().containsKey(transaction.getRequestUuid())) {
throw new IllegalStateException(
EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION);
}
// validate transaction
transactionValidator.validateTransaction(localRoutingNum,
jwt.getClaim(JWT_ACCOUNT_KEY).asString(), transaction);
// Ensure sender balance can cover transaction.
if (transaction.getFromRoutingNum().equals(localRoutingNum)) {
int balance = getAvailableBalance(
bearerToken, transaction.getFromAccountNum());
if (balance < transaction.getAmount()) {
LOGGER.error("Transaction submission failed: "
+ "Insufficient balance");
throw new IllegalStateException( | EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE); |
GoogleCloudPlatform/bank-of-anthos | src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/LedgerMonolithController.java | // Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
| import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
import java.util.Deque;
import java.util.concurrent.ExecutionException;
import org.springframework.web.bind.annotation.PathVariable; | return new ResponseEntity<String>("Ledger reader not healthy",
HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<String>("ok", HttpStatus.OK);
}
// BEGIN LEDGER WRITER
/**
* Submit a new transaction to the ledger.
*
* @param bearerToken HTTP request 'Authorization' header
* @param transaction transaction to submit
*
* @return HTTP Status 200 if transaction was successfully submitted
*/
@PostMapping(value = "/transactions", consumes = "application/json")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> addTransaction(
@RequestHeader("Authorization") String bearerToken,
@RequestBody Transaction transaction) {
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
bearerToken = bearerToken.split("Bearer ")[1];
}
try {
if (bearerToken == null) {
LOGGER.error("Transaction submission failed: "
+ "Authorization header null");
throw new IllegalArgumentException( | // Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
// Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/LedgerMonolithController.java
import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
import java.util.Deque;
import java.util.concurrent.ExecutionException;
import org.springframework.web.bind.annotation.PathVariable;
return new ResponseEntity<String>("Ledger reader not healthy",
HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<String>("ok", HttpStatus.OK);
}
// BEGIN LEDGER WRITER
/**
* Submit a new transaction to the ledger.
*
* @param bearerToken HTTP request 'Authorization' header
* @param transaction transaction to submit
*
* @return HTTP Status 200 if transaction was successfully submitted
*/
@PostMapping(value = "/transactions", consumes = "application/json")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> addTransaction(
@RequestHeader("Authorization") String bearerToken,
@RequestBody Transaction transaction) {
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
bearerToken = bearerToken.split("Bearer ")[1];
}
try {
if (bearerToken == null) {
LOGGER.error("Transaction submission failed: "
+ "Authorization header null");
throw new IllegalArgumentException( | EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL); |
GoogleCloudPlatform/bank-of-anthos | src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/LedgerMonolithController.java | // Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
| import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
import java.util.Deque;
import java.util.concurrent.ExecutionException;
import org.springframework.web.bind.annotation.PathVariable; | // BEGIN LEDGER WRITER
/**
* Submit a new transaction to the ledger.
*
* @param bearerToken HTTP request 'Authorization' header
* @param transaction transaction to submit
*
* @return HTTP Status 200 if transaction was successfully submitted
*/
@PostMapping(value = "/transactions", consumes = "application/json")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> addTransaction(
@RequestHeader("Authorization") String bearerToken,
@RequestBody Transaction transaction) {
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
bearerToken = bearerToken.split("Bearer ")[1];
}
try {
if (bearerToken == null) {
LOGGER.error("Transaction submission failed: "
+ "Authorization header null");
throw new IllegalArgumentException(
EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL);
}
final DecodedJWT jwt = this.verifier.verify(bearerToken);
// Check against cache for duplicate transactions
if (this.ledgerWriterCache.asMap().containsKey(transaction.getRequestUuid())) {
throw new IllegalStateException( | // Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
// Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/LedgerMonolithController.java
import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
import java.util.Deque;
import java.util.concurrent.ExecutionException;
import org.springframework.web.bind.annotation.PathVariable;
// BEGIN LEDGER WRITER
/**
* Submit a new transaction to the ledger.
*
* @param bearerToken HTTP request 'Authorization' header
* @param transaction transaction to submit
*
* @return HTTP Status 200 if transaction was successfully submitted
*/
@PostMapping(value = "/transactions", consumes = "application/json")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> addTransaction(
@RequestHeader("Authorization") String bearerToken,
@RequestBody Transaction transaction) {
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
bearerToken = bearerToken.split("Bearer ")[1];
}
try {
if (bearerToken == null) {
LOGGER.error("Transaction submission failed: "
+ "Authorization header null");
throw new IllegalArgumentException(
EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL);
}
final DecodedJWT jwt = this.verifier.verify(bearerToken);
// Check against cache for duplicate transactions
if (this.ledgerWriterCache.asMap().containsKey(transaction.getRequestUuid())) {
throw new IllegalStateException( | EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION); |
GoogleCloudPlatform/bank-of-anthos | src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/LedgerMonolithController.java | // Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
| import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
import java.util.Deque;
import java.util.concurrent.ExecutionException;
import org.springframework.web.bind.annotation.PathVariable; | @RequestHeader("Authorization") String bearerToken,
@RequestBody Transaction transaction) {
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
bearerToken = bearerToken.split("Bearer ")[1];
}
try {
if (bearerToken == null) {
LOGGER.error("Transaction submission failed: "
+ "Authorization header null");
throw new IllegalArgumentException(
EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL);
}
final DecodedJWT jwt = this.verifier.verify(bearerToken);
// Check against cache for duplicate transactions
if (this.ledgerWriterCache.asMap().containsKey(transaction.getRequestUuid())) {
throw new IllegalStateException(
EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION);
}
// validate transaction
transactionValidator.validateTransaction(localRoutingNum,
jwt.getClaim(JWT_ACCOUNT_KEY).asString(), transaction);
// Ensure sender balance can cover transaction.
if (transaction.getFromRoutingNum().equals(localRoutingNum)) {
Long balance = getAvailableBalance(transaction.getFromAccountNum());
if (balance < transaction.getAmount()) {
LOGGER.error("Transaction submission failed: "
+ "Insufficient balance");
throw new IllegalStateException( | // Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
// Path: src/ledgermonolith/src/main/java/anthos/samples/bankofanthos/ledgermonolith/LedgerMonolithController.java
import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgermonolith.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
import java.util.Deque;
import java.util.concurrent.ExecutionException;
import org.springframework.web.bind.annotation.PathVariable;
@RequestHeader("Authorization") String bearerToken,
@RequestBody Transaction transaction) {
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
bearerToken = bearerToken.split("Bearer ")[1];
}
try {
if (bearerToken == null) {
LOGGER.error("Transaction submission failed: "
+ "Authorization header null");
throw new IllegalArgumentException(
EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL);
}
final DecodedJWT jwt = this.verifier.verify(bearerToken);
// Check against cache for duplicate transactions
if (this.ledgerWriterCache.asMap().containsKey(transaction.getRequestUuid())) {
throw new IllegalStateException(
EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION);
}
// validate transaction
transactionValidator.validateTransaction(localRoutingNum,
jwt.getClaim(JWT_ACCOUNT_KEY).asString(), transaction);
// Ensure sender balance can cover transaction.
if (transaction.getFromRoutingNum().equals(localRoutingNum)) {
Long balance = getAvailableBalance(transaction.getFromAccountNum());
if (balance < transaction.getAmount()) {
LOGGER.error("Transaction submission failed: "
+ "Insufficient balance");
throw new IllegalStateException( | EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE); |
GoogleCloudPlatform/bank-of-anthos | src/ledgerwriter/src/test/java/anthos/samples/bankofanthos/ledgerwriter/LedgerWriterControllerTest.java | // Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
| import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.lang.Nullable;
import io.micrometer.stackdriver.StackdriverConfig;
import io.micrometer.stackdriver.StackdriverMeterRegistry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.mockito.Mock;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException; | // Then
assertNotNull(actualResult);
assertEquals(ledgerWriterController.READINESS_CODE,
actualResult.getBody());
assertEquals(HttpStatus.CREATED, actualResult.getStatusCode());
}
@Test
@DisplayName("Given the transaction is internal and the transaction amount > sender balance, " +
"return HTTP Status 400")
void addTransactionFailWhenWhenAmountLargerThanBalance(TestInfo testInfo) {
// Given
LedgerWriterController spyLedgerWriterController =
spy(ledgerWriterController);
when(transaction.getFromRoutingNum()).thenReturn(LOCAL_ROUTING_NUM);
when(transaction.getFromAccountNum()).thenReturn(AUTHED_ACCOUNT_NUM);
when(transaction.getAmount()).thenReturn(LARGER_THAN_SENDER_BALANCE);
when(transaction.getRequestUuid()).thenReturn(testInfo.getDisplayName());
doReturn(SENDER_BALANCE).when(
spyLedgerWriterController).getAvailableBalance(
TOKEN, AUTHED_ACCOUNT_NUM);
// When
final ResponseEntity actualResult =
spyLedgerWriterController.addTransaction(
BEARER_TOKEN, transaction);
// Then
assertNotNull(actualResult);
assertEquals( | // Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
// Path: src/ledgerwriter/src/test/java/anthos/samples/bankofanthos/ledgerwriter/LedgerWriterControllerTest.java
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.lang.Nullable;
import io.micrometer.stackdriver.StackdriverConfig;
import io.micrometer.stackdriver.StackdriverMeterRegistry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.mockito.Mock;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
// Then
assertNotNull(actualResult);
assertEquals(ledgerWriterController.READINESS_CODE,
actualResult.getBody());
assertEquals(HttpStatus.CREATED, actualResult.getStatusCode());
}
@Test
@DisplayName("Given the transaction is internal and the transaction amount > sender balance, " +
"return HTTP Status 400")
void addTransactionFailWhenWhenAmountLargerThanBalance(TestInfo testInfo) {
// Given
LedgerWriterController spyLedgerWriterController =
spy(ledgerWriterController);
when(transaction.getFromRoutingNum()).thenReturn(LOCAL_ROUTING_NUM);
when(transaction.getFromAccountNum()).thenReturn(AUTHED_ACCOUNT_NUM);
when(transaction.getAmount()).thenReturn(LARGER_THAN_SENDER_BALANCE);
when(transaction.getRequestUuid()).thenReturn(testInfo.getDisplayName());
doReturn(SENDER_BALANCE).when(
spyLedgerWriterController).getAvailableBalance(
TOKEN, AUTHED_ACCOUNT_NUM);
// When
final ResponseEntity actualResult =
spyLedgerWriterController.addTransaction(
BEARER_TOKEN, transaction);
// Then
assertNotNull(actualResult);
assertEquals( | EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE, |
GoogleCloudPlatform/bank-of-anthos | src/ledgerwriter/src/test/java/anthos/samples/bankofanthos/ledgerwriter/LedgerWriterControllerTest.java | // Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
| import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.lang.Nullable;
import io.micrometer.stackdriver.StackdriverConfig;
import io.micrometer.stackdriver.StackdriverMeterRegistry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.mockito.Mock;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException; | void addTransactionWhenIllegalArgumentExceptionThrown() {
// Given
when(claim.asString()).thenReturn(AUTHED_ACCOUNT_NUM);
doThrow(new IllegalArgumentException(EXCEPTION_MESSAGE)).
when(transactionValidator).validateTransaction(
LOCAL_ROUTING_NUM, AUTHED_ACCOUNT_NUM, transaction);
// When
final ResponseEntity actualResult =
ledgerWriterController.addTransaction(
BEARER_TOKEN, transaction);
// Then
assertNotNull(actualResult);
assertEquals(EXCEPTION_MESSAGE,
actualResult.getBody());
assertEquals(HttpStatus.BAD_REQUEST, actualResult.getStatusCode());
}
@Test
@DisplayName("Given HTTP request 'Authorization' header is null, " +
"return HTTP Status 400")
void addTransactionWhenBearerTokenNull() {
// When
final ResponseEntity actualResult =
ledgerWriterController.addTransaction(
null, transaction);
// Then
assertNotNull(actualResult); | // Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
// Path: src/ledgerwriter/src/test/java/anthos/samples/bankofanthos/ledgerwriter/LedgerWriterControllerTest.java
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.lang.Nullable;
import io.micrometer.stackdriver.StackdriverConfig;
import io.micrometer.stackdriver.StackdriverMeterRegistry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.mockito.Mock;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
void addTransactionWhenIllegalArgumentExceptionThrown() {
// Given
when(claim.asString()).thenReturn(AUTHED_ACCOUNT_NUM);
doThrow(new IllegalArgumentException(EXCEPTION_MESSAGE)).
when(transactionValidator).validateTransaction(
LOCAL_ROUTING_NUM, AUTHED_ACCOUNT_NUM, transaction);
// When
final ResponseEntity actualResult =
ledgerWriterController.addTransaction(
BEARER_TOKEN, transaction);
// Then
assertNotNull(actualResult);
assertEquals(EXCEPTION_MESSAGE,
actualResult.getBody());
assertEquals(HttpStatus.BAD_REQUEST, actualResult.getStatusCode());
}
@Test
@DisplayName("Given HTTP request 'Authorization' header is null, " +
"return HTTP Status 400")
void addTransactionWhenBearerTokenNull() {
// When
final ResponseEntity actualResult =
ledgerWriterController.addTransaction(
null, transaction);
// Then
assertNotNull(actualResult); | assertEquals(EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL, |
GoogleCloudPlatform/bank-of-anthos | src/ledgerwriter/src/test/java/anthos/samples/bankofanthos/ledgerwriter/LedgerWriterControllerTest.java | // Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
| import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.lang.Nullable;
import io.micrometer.stackdriver.StackdriverConfig;
import io.micrometer.stackdriver.StackdriverMeterRegistry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.mockito.Mock;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException; | @DisplayName("When duplicate UUID transactions are sent, " +
"second one is rejected with HTTP status 400")
void addTransactionWhenDuplicateUuidExceptionThrown(TestInfo testInfo) {
// Given
LedgerWriterController spyLedgerWriterController =
spy(ledgerWriterController);
when(transaction.getFromRoutingNum()).thenReturn(LOCAL_ROUTING_NUM);
when(transaction.getFromRoutingNum()).thenReturn(AUTHED_ACCOUNT_NUM);
when(transaction.getAmount()).thenReturn(SMALLER_THAN_SENDER_BALANCE);
when(transaction.getRequestUuid()).thenReturn(testInfo.getDisplayName());
doReturn(SENDER_BALANCE).when(
spyLedgerWriterController).getAvailableBalance(
TOKEN, AUTHED_ACCOUNT_NUM);
// When
final ResponseEntity originalResult =
spyLedgerWriterController.addTransaction(
BEARER_TOKEN, transaction);
final ResponseEntity duplicateResult =
spyLedgerWriterController.addTransaction(
BEARER_TOKEN, transaction);
// Then
assertNotNull(originalResult);
assertEquals(ledgerWriterController.READINESS_CODE,
originalResult.getBody());
assertEquals(HttpStatus.CREATED, originalResult.getStatusCode());
assertNotNull(duplicateResult);
assertEquals( | // Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION =
// "duplicate transaction uuid";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE =
// "insufficient balance";
//
// Path: src/ledgerwriter/src/main/java/anthos/samples/bankofanthos/ledgerwriter/ExceptionMessages.java
// public static final String
// EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL =
// "HTTP request 'Authorization' header is null";
// Path: src/ledgerwriter/src/test/java/anthos/samples/bankofanthos/ledgerwriter/LedgerWriterControllerTest.java
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_INSUFFICIENT_BALANCE;
import static anthos.samples.bankofanthos.ledgerwriter.ExceptionMessages.EXCEPTION_MESSAGE_WHEN_AUTHORIZATION_HEADER_NULL;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.lang.Nullable;
import io.micrometer.stackdriver.StackdriverConfig;
import io.micrometer.stackdriver.StackdriverMeterRegistry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.mockito.Mock;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
@DisplayName("When duplicate UUID transactions are sent, " +
"second one is rejected with HTTP status 400")
void addTransactionWhenDuplicateUuidExceptionThrown(TestInfo testInfo) {
// Given
LedgerWriterController spyLedgerWriterController =
spy(ledgerWriterController);
when(transaction.getFromRoutingNum()).thenReturn(LOCAL_ROUTING_NUM);
when(transaction.getFromRoutingNum()).thenReturn(AUTHED_ACCOUNT_NUM);
when(transaction.getAmount()).thenReturn(SMALLER_THAN_SENDER_BALANCE);
when(transaction.getRequestUuid()).thenReturn(testInfo.getDisplayName());
doReturn(SENDER_BALANCE).when(
spyLedgerWriterController).getAvailableBalance(
TOKEN, AUTHED_ACCOUNT_NUM);
// When
final ResponseEntity originalResult =
spyLedgerWriterController.addTransaction(
BEARER_TOKEN, transaction);
final ResponseEntity duplicateResult =
spyLedgerWriterController.addTransaction(
BEARER_TOKEN, transaction);
// Then
assertNotNull(originalResult);
assertEquals(ledgerWriterController.READINESS_CODE,
originalResult.getBody());
assertEquals(HttpStatus.CREATED, originalResult.getStatusCode());
assertNotNull(duplicateResult);
assertEquals( | EXCEPTION_MESSAGE_DUPLICATE_TRANSACTION, |
obazoud/elasticsearch-river-git | src/main/java/com/bazoud/elasticsearch/river/git/flow/FetchRepositoryFunction.java | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/TrackingRefUpdateToRef.java
// public class TrackingRefUpdateToRef extends MyFunction<TrackingRefUpdate, Ref> {
// private Repository repository;
//
// public TrackingRefUpdateToRef(Repository repository) {
// this.repository = repository;
// }
//
// @Override
// public Ref doApply(TrackingRefUpdate input) throws Throwable {
// return repository.getRef(input.getLocalName());
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/jgit/LoggingProgressMonitor.java
// public class LoggingProgressMonitor implements ProgressMonitor {
// private ESLogger logger;
//
// public LoggingProgressMonitor(ESLogger logger) {
// this.logger = logger;
// }
//
// @Override
// public void start(int totalTasks) {
// }
//
// @Override
// public void beginTask(String title, int totalWork) {
// logger.info(title);
// }
//
// @Override
// public void update(int completed) {
// }
//
// @Override
// public void endTask() {
// }
//
// @Override
// public boolean isCancelled() {
// return false;
// }
// }
| import java.util.Collection;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.FetchResult;
import org.eclipse.jgit.transport.TrackingRefUpdate;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.flow.functions.TrackingRefUpdateToRef;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.bazoud.elasticsearch.river.git.jgit.LoggingProgressMonitor;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import static org.eclipse.jgit.lib.RefUpdate.Result.NO_CHANGE; | package com.bazoud.elasticsearch.river.git.flow;
/**
* @author Olivier Bazoud
*/
public class FetchRepositoryFunction extends MyFunction<Context, Context> {
private static ESLogger logger = Loggers.getLogger(FetchRepositoryFunction.class);
@Override
public Context doApply(Context context) throws Throwable {
final Repository repository = new FileRepositoryBuilder()
.setGitDir(context.getProjectPath())
// scan environment GIT_* variables
.readEnvironment()
.findGitDir()
.setMustExist(true)
.build();
context.setRepository(repository);
logger.info("Fetching '{}' repository at path: '{}'", context.getName(), context.getProjectPath());
Git git = new Git(repository);
FetchResult fetchResult = git.fetch() | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/TrackingRefUpdateToRef.java
// public class TrackingRefUpdateToRef extends MyFunction<TrackingRefUpdate, Ref> {
// private Repository repository;
//
// public TrackingRefUpdateToRef(Repository repository) {
// this.repository = repository;
// }
//
// @Override
// public Ref doApply(TrackingRefUpdate input) throws Throwable {
// return repository.getRef(input.getLocalName());
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/jgit/LoggingProgressMonitor.java
// public class LoggingProgressMonitor implements ProgressMonitor {
// private ESLogger logger;
//
// public LoggingProgressMonitor(ESLogger logger) {
// this.logger = logger;
// }
//
// @Override
// public void start(int totalTasks) {
// }
//
// @Override
// public void beginTask(String title, int totalWork) {
// logger.info(title);
// }
//
// @Override
// public void update(int completed) {
// }
//
// @Override
// public void endTask() {
// }
//
// @Override
// public boolean isCancelled() {
// return false;
// }
// }
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/FetchRepositoryFunction.java
import java.util.Collection;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.FetchResult;
import org.eclipse.jgit.transport.TrackingRefUpdate;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.flow.functions.TrackingRefUpdateToRef;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.bazoud.elasticsearch.river.git.jgit.LoggingProgressMonitor;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import static org.eclipse.jgit.lib.RefUpdate.Result.NO_CHANGE;
package com.bazoud.elasticsearch.river.git.flow;
/**
* @author Olivier Bazoud
*/
public class FetchRepositoryFunction extends MyFunction<Context, Context> {
private static ESLogger logger = Loggers.getLogger(FetchRepositoryFunction.class);
@Override
public Context doApply(Context context) throws Throwable {
final Repository repository = new FileRepositoryBuilder()
.setGitDir(context.getProjectPath())
// scan environment GIT_* variables
.readEnvironment()
.findGitDir()
.setMustExist(true)
.build();
context.setRepository(repository);
logger.info("Fetching '{}' repository at path: '{}'", context.getName(), context.getProjectPath());
Git git = new Git(repository);
FetchResult fetchResult = git.fetch() | .setProgressMonitor(new LoggingProgressMonitor(logger)) |
obazoud/elasticsearch-river-git | src/main/java/com/bazoud/elasticsearch/river/git/flow/FetchRepositoryFunction.java | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/TrackingRefUpdateToRef.java
// public class TrackingRefUpdateToRef extends MyFunction<TrackingRefUpdate, Ref> {
// private Repository repository;
//
// public TrackingRefUpdateToRef(Repository repository) {
// this.repository = repository;
// }
//
// @Override
// public Ref doApply(TrackingRefUpdate input) throws Throwable {
// return repository.getRef(input.getLocalName());
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/jgit/LoggingProgressMonitor.java
// public class LoggingProgressMonitor implements ProgressMonitor {
// private ESLogger logger;
//
// public LoggingProgressMonitor(ESLogger logger) {
// this.logger = logger;
// }
//
// @Override
// public void start(int totalTasks) {
// }
//
// @Override
// public void beginTask(String title, int totalWork) {
// logger.info(title);
// }
//
// @Override
// public void update(int completed) {
// }
//
// @Override
// public void endTask() {
// }
//
// @Override
// public boolean isCancelled() {
// return false;
// }
// }
| import java.util.Collection;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.FetchResult;
import org.eclipse.jgit.transport.TrackingRefUpdate;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.flow.functions.TrackingRefUpdateToRef;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.bazoud.elasticsearch.river.git.jgit.LoggingProgressMonitor;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import static org.eclipse.jgit.lib.RefUpdate.Result.NO_CHANGE; | package com.bazoud.elasticsearch.river.git.flow;
/**
* @author Olivier Bazoud
*/
public class FetchRepositoryFunction extends MyFunction<Context, Context> {
private static ESLogger logger = Loggers.getLogger(FetchRepositoryFunction.class);
@Override
public Context doApply(Context context) throws Throwable {
final Repository repository = new FileRepositoryBuilder()
.setGitDir(context.getProjectPath())
// scan environment GIT_* variables
.readEnvironment()
.findGitDir()
.setMustExist(true)
.build();
context.setRepository(repository);
logger.info("Fetching '{}' repository at path: '{}'", context.getName(), context.getProjectPath());
Git git = new Git(repository);
FetchResult fetchResult = git.fetch()
.setProgressMonitor(new LoggingProgressMonitor(logger))
.call();
Collection<Ref> refs = FluentIterable
.from(fetchResult.getTrackingRefUpdates())
.filter(Predicates.not(new Predicate<TrackingRefUpdate>() {
@Override
public boolean apply(TrackingRefUpdate input) {
return NO_CHANGE.equals(input.getResult());
}
})) | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/TrackingRefUpdateToRef.java
// public class TrackingRefUpdateToRef extends MyFunction<TrackingRefUpdate, Ref> {
// private Repository repository;
//
// public TrackingRefUpdateToRef(Repository repository) {
// this.repository = repository;
// }
//
// @Override
// public Ref doApply(TrackingRefUpdate input) throws Throwable {
// return repository.getRef(input.getLocalName());
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/jgit/LoggingProgressMonitor.java
// public class LoggingProgressMonitor implements ProgressMonitor {
// private ESLogger logger;
//
// public LoggingProgressMonitor(ESLogger logger) {
// this.logger = logger;
// }
//
// @Override
// public void start(int totalTasks) {
// }
//
// @Override
// public void beginTask(String title, int totalWork) {
// logger.info(title);
// }
//
// @Override
// public void update(int completed) {
// }
//
// @Override
// public void endTask() {
// }
//
// @Override
// public boolean isCancelled() {
// return false;
// }
// }
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/FetchRepositoryFunction.java
import java.util.Collection;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.FetchResult;
import org.eclipse.jgit.transport.TrackingRefUpdate;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.flow.functions.TrackingRefUpdateToRef;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.bazoud.elasticsearch.river.git.jgit.LoggingProgressMonitor;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import static org.eclipse.jgit.lib.RefUpdate.Result.NO_CHANGE;
package com.bazoud.elasticsearch.river.git.flow;
/**
* @author Olivier Bazoud
*/
public class FetchRepositoryFunction extends MyFunction<Context, Context> {
private static ESLogger logger = Loggers.getLogger(FetchRepositoryFunction.class);
@Override
public Context doApply(Context context) throws Throwable {
final Repository repository = new FileRepositoryBuilder()
.setGitDir(context.getProjectPath())
// scan environment GIT_* variables
.readEnvironment()
.findGitDir()
.setMustExist(true)
.build();
context.setRepository(repository);
logger.info("Fetching '{}' repository at path: '{}'", context.getName(), context.getProjectPath());
Git git = new Git(repository);
FetchResult fetchResult = git.fetch()
.setProgressMonitor(new LoggingProgressMonitor(logger))
.call();
Collection<Ref> refs = FluentIterable
.from(fetchResult.getTrackingRefUpdates())
.filter(Predicates.not(new Predicate<TrackingRefUpdate>() {
@Override
public boolean apply(TrackingRefUpdate input) {
return NO_CHANGE.equals(input.getResult());
}
})) | .transform(new TrackingRefUpdateToRef(repository)) |
obazoud/elasticsearch-river-git | src/test/java/com/bazoud/elasticsearch/river/git/GitRiverTest.java | // Path: src/main/java/com/bazoud/elasticsearch/plugin/river/git/GitRiverPlugin.java
// public static final String RIVER_TYPE = "git";
| import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.AdminClient;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchAdminClient;
import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchClient;
import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchIndex;
import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchNode;
import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
import static com.bazoud.elasticsearch.plugin.river.git.GitRiverPlugin.RIVER_TYPE;
import static java.lang.Thread.currentThread;
import static java.lang.Thread.sleep;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; | gitRepository = currentThread().getContextClassLoader()
.getResource("git_tests_junit")
.toURI()
.toString();
}
@Test
@ElasticsearchIndex(indexName = RIVER_KEYWORD)
public void test00CreateIndex() {
// Checks if the index has been created
IndicesExistsResponse existResponse = adminClient.indices()
.prepareExists(RIVER_KEYWORD)
.execute().actionGet();
Assert.assertTrue("Index must exist", existResponse.isExists());
}
@Test
@ElasticsearchIndex(indexName = RIVER_KEYWORD)
public void test10IndexingFromRevision() throws IOException {
// Index a new document
Map<String, Object> json = new HashMap<String, Object>();
json.put("name", "git_repo_tests");
json.put("uri", gitRepository);
json.put("working_dir", "./target/river-workingdir_" + UUID.randomUUID().toString());
json.put("issue_regex", "#(\\d*)");
json.put("indexing_diff", false);
XContentBuilder builder = jsonBuilder()
.startObject() | // Path: src/main/java/com/bazoud/elasticsearch/plugin/river/git/GitRiverPlugin.java
// public static final String RIVER_TYPE = "git";
// Path: src/test/java/com/bazoud/elasticsearch/river/git/GitRiverTest.java
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.AdminClient;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchAdminClient;
import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchClient;
import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchIndex;
import com.github.tlrx.elasticsearch.test.annotations.ElasticsearchNode;
import com.github.tlrx.elasticsearch.test.support.junit.runners.ElasticsearchRunner;
import static com.bazoud.elasticsearch.plugin.river.git.GitRiverPlugin.RIVER_TYPE;
import static java.lang.Thread.currentThread;
import static java.lang.Thread.sleep;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
gitRepository = currentThread().getContextClassLoader()
.getResource("git_tests_junit")
.toURI()
.toString();
}
@Test
@ElasticsearchIndex(indexName = RIVER_KEYWORD)
public void test00CreateIndex() {
// Checks if the index has been created
IndicesExistsResponse existResponse = adminClient.indices()
.prepareExists(RIVER_KEYWORD)
.execute().actionGet();
Assert.assertTrue("Index must exist", existResponse.isExists());
}
@Test
@ElasticsearchIndex(indexName = RIVER_KEYWORD)
public void test10IndexingFromRevision() throws IOException {
// Index a new document
Map<String, Object> json = new HashMap<String, Object>();
json.put("name", "git_repo_tests");
json.put("uri", gitRepository);
json.put("working_dir", "./target/river-workingdir_" + UUID.randomUUID().toString());
json.put("issue_regex", "#(\\d*)");
json.put("indexing_diff", false);
XContentBuilder builder = jsonBuilder()
.startObject() | .field("type", RIVER_TYPE) |
obazoud/elasticsearch-river-git | src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/RevCommitToIndexFile.java | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/IndexFile.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class IndexFile implements Id {
// private String id;
// private String commit;
// private String project;
// private String ref;
// private String path;
// private String name;
// private String extension;
// private String content;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
| import java.io.File;
import java.io.IOException;
import org.eclipse.jgit.errors.LargeObjectException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.beans.IndexFile;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.google.common.io.Files;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.FILE; | package com.bazoud.elasticsearch.river.git.flow.functions;
/**
* @author Olivier Bazoud
*/
public class RevCommitToIndexFile extends MyFunction<RevCommit, IndexFile> {
private static ESLogger logger = Loggers.getLogger(RevCommitToIndexFile.class); | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/IndexFile.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class IndexFile implements Id {
// private String id;
// private String commit;
// private String project;
// private String ref;
// private String path;
// private String name;
// private String extension;
// private String content;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/RevCommitToIndexFile.java
import java.io.File;
import java.io.IOException;
import org.eclipse.jgit.errors.LargeObjectException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.beans.IndexFile;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.google.common.io.Files;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.FILE;
package com.bazoud.elasticsearch.river.git.flow.functions;
/**
* @author Olivier Bazoud
*/
public class RevCommitToIndexFile extends MyFunction<RevCommit, IndexFile> {
private static ESLogger logger = Loggers.getLogger(RevCommitToIndexFile.class); | private Context context; |
obazoud/elasticsearch-river-git | src/main/java/com/bazoud/elasticsearch/river/git/flow/TagIndexFunction.java | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/TagToIndexTag.java
// public class TagToIndexTag extends MyFunction<Map.Entry<String, Ref>, IndexTag> {
// private static ESLogger logger = Loggers.getLogger(TagToIndexTag.class);
// private Context context;
// private final RevWalk walk;
//
// public TagToIndexTag(Context context, RevWalk walk) {
// this.context = context;
// this.walk = walk;
// }
//
// @Override
// public IndexTag doApply(Map.Entry<String, Ref> tag) throws Throwable {
// RevCommit revCommit = walk.parseCommit(tag.getValue().getObjectId());
// String id = String.format("%s|%s|%s", TAG.name().toLowerCase(), context.getName(), revCommit.name());
// return IndexTag.indexTag()
// .id(id)
// .tag(tag.getKey())
// .ref(tag.getValue().getName())
// .sha1(revCommit.name())
// .build();
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/visitors/BulkVisitor.java
// public class BulkVisitor<T extends Id> implements Visitor<T> {
// private static ESLogger logger = Loggers.getLogger(BulkVisitor.class);
//
// private BulkRequestBuilder bulk;
// private Context context;
// private String type;
//
// public BulkVisitor(Context context, String type) {
// this.context = context;
// this.type = type;
// }
//
// @Override
// public void before() {
// this.bulk = context.getClient().prepareBulk();
// }
//
// @Override
// public void visit(Id input) {
// try {
// bulk.add(indexRequest(context.getRiverName())
// .type(type)
// .id(input.getId())
// .source(toJson(input)));
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// }
//
// @Override
// public void after() {
// logger.info("Executing bulk {} actions", bulk.numberOfActions());
// if (bulk.numberOfActions() > 0) {
// BulkResponse response = bulk.execute().actionGet();
// logger.info("Bulk actions tooks {} ms", response.getTookInMillis());
// if (response.hasFailures()) {
// logger.warn("failed to execute bulk: {}", response.buildFailureMessage());
// }
// } else {
// logger.info("Sorry nothing to do");
// }
// }
//
// public String toJson(Object object) throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.writeValueAsString(object);
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/Visitors.java
// public final class Visitors {
// private Visitors() {
// }
//
// public static <T> void visit(Iterable<T> iterable, Visitor<T> visitor) throws Exception {
// visitor.before();
// for (T current : iterable) {
// visitor.visit(current);
// }
// visitor.after();
//
// }
// }
| import org.eclipse.jgit.revwalk.RevWalk;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.flow.functions.TagToIndexTag;
import com.bazoud.elasticsearch.river.git.flow.visitors.BulkVisitor;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.bazoud.elasticsearch.river.git.guava.Visitors;
import com.google.common.collect.FluentIterable;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.TAG; | package com.bazoud.elasticsearch.river.git.flow;
/**
* @author Olivier Bazoud
*/
public class TagIndexFunction extends MyFunction<Context, Context> {
@Override
public Context doApply(Context context) throws Throwable {
RevWalk walk = new RevWalk(context.getRepository());
| // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/TagToIndexTag.java
// public class TagToIndexTag extends MyFunction<Map.Entry<String, Ref>, IndexTag> {
// private static ESLogger logger = Loggers.getLogger(TagToIndexTag.class);
// private Context context;
// private final RevWalk walk;
//
// public TagToIndexTag(Context context, RevWalk walk) {
// this.context = context;
// this.walk = walk;
// }
//
// @Override
// public IndexTag doApply(Map.Entry<String, Ref> tag) throws Throwable {
// RevCommit revCommit = walk.parseCommit(tag.getValue().getObjectId());
// String id = String.format("%s|%s|%s", TAG.name().toLowerCase(), context.getName(), revCommit.name());
// return IndexTag.indexTag()
// .id(id)
// .tag(tag.getKey())
// .ref(tag.getValue().getName())
// .sha1(revCommit.name())
// .build();
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/visitors/BulkVisitor.java
// public class BulkVisitor<T extends Id> implements Visitor<T> {
// private static ESLogger logger = Loggers.getLogger(BulkVisitor.class);
//
// private BulkRequestBuilder bulk;
// private Context context;
// private String type;
//
// public BulkVisitor(Context context, String type) {
// this.context = context;
// this.type = type;
// }
//
// @Override
// public void before() {
// this.bulk = context.getClient().prepareBulk();
// }
//
// @Override
// public void visit(Id input) {
// try {
// bulk.add(indexRequest(context.getRiverName())
// .type(type)
// .id(input.getId())
// .source(toJson(input)));
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// }
//
// @Override
// public void after() {
// logger.info("Executing bulk {} actions", bulk.numberOfActions());
// if (bulk.numberOfActions() > 0) {
// BulkResponse response = bulk.execute().actionGet();
// logger.info("Bulk actions tooks {} ms", response.getTookInMillis());
// if (response.hasFailures()) {
// logger.warn("failed to execute bulk: {}", response.buildFailureMessage());
// }
// } else {
// logger.info("Sorry nothing to do");
// }
// }
//
// public String toJson(Object object) throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.writeValueAsString(object);
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/Visitors.java
// public final class Visitors {
// private Visitors() {
// }
//
// public static <T> void visit(Iterable<T> iterable, Visitor<T> visitor) throws Exception {
// visitor.before();
// for (T current : iterable) {
// visitor.visit(current);
// }
// visitor.after();
//
// }
// }
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/TagIndexFunction.java
import org.eclipse.jgit.revwalk.RevWalk;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.flow.functions.TagToIndexTag;
import com.bazoud.elasticsearch.river.git.flow.visitors.BulkVisitor;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.bazoud.elasticsearch.river.git.guava.Visitors;
import com.google.common.collect.FluentIterable;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.TAG;
package com.bazoud.elasticsearch.river.git.flow;
/**
* @author Olivier Bazoud
*/
public class TagIndexFunction extends MyFunction<Context, Context> {
@Override
public Context doApply(Context context) throws Throwable {
RevWalk walk = new RevWalk(context.getRepository());
| Visitors.visit( |
obazoud/elasticsearch-river-git | src/main/java/com/bazoud/elasticsearch/river/git/flow/TagIndexFunction.java | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/TagToIndexTag.java
// public class TagToIndexTag extends MyFunction<Map.Entry<String, Ref>, IndexTag> {
// private static ESLogger logger = Loggers.getLogger(TagToIndexTag.class);
// private Context context;
// private final RevWalk walk;
//
// public TagToIndexTag(Context context, RevWalk walk) {
// this.context = context;
// this.walk = walk;
// }
//
// @Override
// public IndexTag doApply(Map.Entry<String, Ref> tag) throws Throwable {
// RevCommit revCommit = walk.parseCommit(tag.getValue().getObjectId());
// String id = String.format("%s|%s|%s", TAG.name().toLowerCase(), context.getName(), revCommit.name());
// return IndexTag.indexTag()
// .id(id)
// .tag(tag.getKey())
// .ref(tag.getValue().getName())
// .sha1(revCommit.name())
// .build();
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/visitors/BulkVisitor.java
// public class BulkVisitor<T extends Id> implements Visitor<T> {
// private static ESLogger logger = Loggers.getLogger(BulkVisitor.class);
//
// private BulkRequestBuilder bulk;
// private Context context;
// private String type;
//
// public BulkVisitor(Context context, String type) {
// this.context = context;
// this.type = type;
// }
//
// @Override
// public void before() {
// this.bulk = context.getClient().prepareBulk();
// }
//
// @Override
// public void visit(Id input) {
// try {
// bulk.add(indexRequest(context.getRiverName())
// .type(type)
// .id(input.getId())
// .source(toJson(input)));
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// }
//
// @Override
// public void after() {
// logger.info("Executing bulk {} actions", bulk.numberOfActions());
// if (bulk.numberOfActions() > 0) {
// BulkResponse response = bulk.execute().actionGet();
// logger.info("Bulk actions tooks {} ms", response.getTookInMillis());
// if (response.hasFailures()) {
// logger.warn("failed to execute bulk: {}", response.buildFailureMessage());
// }
// } else {
// logger.info("Sorry nothing to do");
// }
// }
//
// public String toJson(Object object) throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.writeValueAsString(object);
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/Visitors.java
// public final class Visitors {
// private Visitors() {
// }
//
// public static <T> void visit(Iterable<T> iterable, Visitor<T> visitor) throws Exception {
// visitor.before();
// for (T current : iterable) {
// visitor.visit(current);
// }
// visitor.after();
//
// }
// }
| import org.eclipse.jgit.revwalk.RevWalk;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.flow.functions.TagToIndexTag;
import com.bazoud.elasticsearch.river.git.flow.visitors.BulkVisitor;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.bazoud.elasticsearch.river.git.guava.Visitors;
import com.google.common.collect.FluentIterable;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.TAG; | package com.bazoud.elasticsearch.river.git.flow;
/**
* @author Olivier Bazoud
*/
public class TagIndexFunction extends MyFunction<Context, Context> {
@Override
public Context doApply(Context context) throws Throwable {
RevWalk walk = new RevWalk(context.getRepository());
Visitors.visit(
FluentIterable
.from(context.getRepository().getTags().entrySet()) | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/TagToIndexTag.java
// public class TagToIndexTag extends MyFunction<Map.Entry<String, Ref>, IndexTag> {
// private static ESLogger logger = Loggers.getLogger(TagToIndexTag.class);
// private Context context;
// private final RevWalk walk;
//
// public TagToIndexTag(Context context, RevWalk walk) {
// this.context = context;
// this.walk = walk;
// }
//
// @Override
// public IndexTag doApply(Map.Entry<String, Ref> tag) throws Throwable {
// RevCommit revCommit = walk.parseCommit(tag.getValue().getObjectId());
// String id = String.format("%s|%s|%s", TAG.name().toLowerCase(), context.getName(), revCommit.name());
// return IndexTag.indexTag()
// .id(id)
// .tag(tag.getKey())
// .ref(tag.getValue().getName())
// .sha1(revCommit.name())
// .build();
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/visitors/BulkVisitor.java
// public class BulkVisitor<T extends Id> implements Visitor<T> {
// private static ESLogger logger = Loggers.getLogger(BulkVisitor.class);
//
// private BulkRequestBuilder bulk;
// private Context context;
// private String type;
//
// public BulkVisitor(Context context, String type) {
// this.context = context;
// this.type = type;
// }
//
// @Override
// public void before() {
// this.bulk = context.getClient().prepareBulk();
// }
//
// @Override
// public void visit(Id input) {
// try {
// bulk.add(indexRequest(context.getRiverName())
// .type(type)
// .id(input.getId())
// .source(toJson(input)));
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// }
//
// @Override
// public void after() {
// logger.info("Executing bulk {} actions", bulk.numberOfActions());
// if (bulk.numberOfActions() > 0) {
// BulkResponse response = bulk.execute().actionGet();
// logger.info("Bulk actions tooks {} ms", response.getTookInMillis());
// if (response.hasFailures()) {
// logger.warn("failed to execute bulk: {}", response.buildFailureMessage());
// }
// } else {
// logger.info("Sorry nothing to do");
// }
// }
//
// public String toJson(Object object) throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.writeValueAsString(object);
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/Visitors.java
// public final class Visitors {
// private Visitors() {
// }
//
// public static <T> void visit(Iterable<T> iterable, Visitor<T> visitor) throws Exception {
// visitor.before();
// for (T current : iterable) {
// visitor.visit(current);
// }
// visitor.after();
//
// }
// }
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/TagIndexFunction.java
import org.eclipse.jgit.revwalk.RevWalk;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.flow.functions.TagToIndexTag;
import com.bazoud.elasticsearch.river.git.flow.visitors.BulkVisitor;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.bazoud.elasticsearch.river.git.guava.Visitors;
import com.google.common.collect.FluentIterable;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.TAG;
package com.bazoud.elasticsearch.river.git.flow;
/**
* @author Olivier Bazoud
*/
public class TagIndexFunction extends MyFunction<Context, Context> {
@Override
public Context doApply(Context context) throws Throwable {
RevWalk walk = new RevWalk(context.getRepository());
Visitors.visit(
FluentIterable
.from(context.getRepository().getTags().entrySet()) | .transform(new TagToIndexTag(context, walk)), |
obazoud/elasticsearch-river-git | src/main/java/com/bazoud/elasticsearch/river/git/flow/TagIndexFunction.java | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/TagToIndexTag.java
// public class TagToIndexTag extends MyFunction<Map.Entry<String, Ref>, IndexTag> {
// private static ESLogger logger = Loggers.getLogger(TagToIndexTag.class);
// private Context context;
// private final RevWalk walk;
//
// public TagToIndexTag(Context context, RevWalk walk) {
// this.context = context;
// this.walk = walk;
// }
//
// @Override
// public IndexTag doApply(Map.Entry<String, Ref> tag) throws Throwable {
// RevCommit revCommit = walk.parseCommit(tag.getValue().getObjectId());
// String id = String.format("%s|%s|%s", TAG.name().toLowerCase(), context.getName(), revCommit.name());
// return IndexTag.indexTag()
// .id(id)
// .tag(tag.getKey())
// .ref(tag.getValue().getName())
// .sha1(revCommit.name())
// .build();
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/visitors/BulkVisitor.java
// public class BulkVisitor<T extends Id> implements Visitor<T> {
// private static ESLogger logger = Loggers.getLogger(BulkVisitor.class);
//
// private BulkRequestBuilder bulk;
// private Context context;
// private String type;
//
// public BulkVisitor(Context context, String type) {
// this.context = context;
// this.type = type;
// }
//
// @Override
// public void before() {
// this.bulk = context.getClient().prepareBulk();
// }
//
// @Override
// public void visit(Id input) {
// try {
// bulk.add(indexRequest(context.getRiverName())
// .type(type)
// .id(input.getId())
// .source(toJson(input)));
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// }
//
// @Override
// public void after() {
// logger.info("Executing bulk {} actions", bulk.numberOfActions());
// if (bulk.numberOfActions() > 0) {
// BulkResponse response = bulk.execute().actionGet();
// logger.info("Bulk actions tooks {} ms", response.getTookInMillis());
// if (response.hasFailures()) {
// logger.warn("failed to execute bulk: {}", response.buildFailureMessage());
// }
// } else {
// logger.info("Sorry nothing to do");
// }
// }
//
// public String toJson(Object object) throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.writeValueAsString(object);
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/Visitors.java
// public final class Visitors {
// private Visitors() {
// }
//
// public static <T> void visit(Iterable<T> iterable, Visitor<T> visitor) throws Exception {
// visitor.before();
// for (T current : iterable) {
// visitor.visit(current);
// }
// visitor.after();
//
// }
// }
| import org.eclipse.jgit.revwalk.RevWalk;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.flow.functions.TagToIndexTag;
import com.bazoud.elasticsearch.river.git.flow.visitors.BulkVisitor;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.bazoud.elasticsearch.river.git.guava.Visitors;
import com.google.common.collect.FluentIterable;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.TAG; | package com.bazoud.elasticsearch.river.git.flow;
/**
* @author Olivier Bazoud
*/
public class TagIndexFunction extends MyFunction<Context, Context> {
@Override
public Context doApply(Context context) throws Throwable {
RevWalk walk = new RevWalk(context.getRepository());
Visitors.visit(
FluentIterable
.from(context.getRepository().getTags().entrySet())
.transform(new TagToIndexTag(context, walk)), | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/TagToIndexTag.java
// public class TagToIndexTag extends MyFunction<Map.Entry<String, Ref>, IndexTag> {
// private static ESLogger logger = Loggers.getLogger(TagToIndexTag.class);
// private Context context;
// private final RevWalk walk;
//
// public TagToIndexTag(Context context, RevWalk walk) {
// this.context = context;
// this.walk = walk;
// }
//
// @Override
// public IndexTag doApply(Map.Entry<String, Ref> tag) throws Throwable {
// RevCommit revCommit = walk.parseCommit(tag.getValue().getObjectId());
// String id = String.format("%s|%s|%s", TAG.name().toLowerCase(), context.getName(), revCommit.name());
// return IndexTag.indexTag()
// .id(id)
// .tag(tag.getKey())
// .ref(tag.getValue().getName())
// .sha1(revCommit.name())
// .build();
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/visitors/BulkVisitor.java
// public class BulkVisitor<T extends Id> implements Visitor<T> {
// private static ESLogger logger = Loggers.getLogger(BulkVisitor.class);
//
// private BulkRequestBuilder bulk;
// private Context context;
// private String type;
//
// public BulkVisitor(Context context, String type) {
// this.context = context;
// this.type = type;
// }
//
// @Override
// public void before() {
// this.bulk = context.getClient().prepareBulk();
// }
//
// @Override
// public void visit(Id input) {
// try {
// bulk.add(indexRequest(context.getRiverName())
// .type(type)
// .id(input.getId())
// .source(toJson(input)));
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// }
//
// @Override
// public void after() {
// logger.info("Executing bulk {} actions", bulk.numberOfActions());
// if (bulk.numberOfActions() > 0) {
// BulkResponse response = bulk.execute().actionGet();
// logger.info("Bulk actions tooks {} ms", response.getTookInMillis());
// if (response.hasFailures()) {
// logger.warn("failed to execute bulk: {}", response.buildFailureMessage());
// }
// } else {
// logger.info("Sorry nothing to do");
// }
// }
//
// public String toJson(Object object) throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.writeValueAsString(object);
// }
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/Visitors.java
// public final class Visitors {
// private Visitors() {
// }
//
// public static <T> void visit(Iterable<T> iterable, Visitor<T> visitor) throws Exception {
// visitor.before();
// for (T current : iterable) {
// visitor.visit(current);
// }
// visitor.after();
//
// }
// }
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/TagIndexFunction.java
import org.eclipse.jgit.revwalk.RevWalk;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.flow.functions.TagToIndexTag;
import com.bazoud.elasticsearch.river.git.flow.visitors.BulkVisitor;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.bazoud.elasticsearch.river.git.guava.Visitors;
import com.google.common.collect.FluentIterable;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.TAG;
package com.bazoud.elasticsearch.river.git.flow;
/**
* @author Olivier Bazoud
*/
public class TagIndexFunction extends MyFunction<Context, Context> {
@Override
public Context doApply(Context context) throws Throwable {
RevWalk walk = new RevWalk(context.getRepository());
Visitors.visit(
FluentIterable
.from(context.getRepository().getTags().entrySet())
.transform(new TagToIndexTag(context, walk)), | new BulkVisitor(context, TAG.name().toLowerCase()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.