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 |
|---|---|---|---|---|---|---|
jVoid/jVoid | src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java | // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java
// public interface InstrumentationProvider {
//
// boolean matches(CtClass ctClass);
//
// List<ClassHandler> getClassHandlers(CtClass ctClass);
//
// List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod);
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationProvider.java
// public class AppInstrumentationProvider implements InstrumentationProvider {
//
// private AppClassHandler appClassHandler;
// private MethodInstrumenter trackerMethodInstrumenter;
// private JVoidConfiguration jvoidConfiguration;
//
// @Inject
// public AppInstrumentationProvider(AppClassHandler appClassHandler,
// TrackerMethodInstrumenter trackerMethodInstrumenter, JVoidConfiguration jvoidConfiguration) {
// super();
// this.appClassHandler = appClassHandler;
// this.trackerMethodInstrumenter = trackerMethodInstrumenter;
// this.jvoidConfiguration = jvoidConfiguration;
// }
//
// @Override
// public boolean matches(CtClass ctClass) {
// JVoidConfiguration config = jvoidConfiguration;
// boolean matches = ctClass.getName().startsWith(config.basePackage());
// if (jvoidConfiguration.heuristicExcludeGroovyCallSite()) {
// matches = matches && !AppHeuristicHelper.isGroovyCallSite(ctClass);
// }
// return matches;
// }
//
// @Override
// public List<ClassHandler> getClassHandlers(CtClass ctClass) {
// return Collections.<ClassHandler> singletonList(appClassHandler);
// }
//
// @Override
// public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) {
// return Collections.singletonList(trackerMethodInstrumenter);
// }
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/junit4/JUnitInstrumentationProvider.java
// public class JUnitInstrumentationProvider implements InstrumentationProvider {
//
// private Map<String, MethodInstrumenter> instrumenterMap;
//
// @Inject
// public JUnitInstrumentationProvider(JUnitRunNotifierMethodInstrumenter junitRunNotifierMethodInstrumenter,
// RunChildMethodInstrumenter runChildMethodInstrumenter) {
// this.instrumenterMap = new HashMap<>();
// this.instrumenterMap.put("org.junit.runner.notification.RunNotifier", junitRunNotifierMethodInstrumenter);
// this.instrumenterMap.put("org.junit.runners.BlockJUnit4ClassRunner", runChildMethodInstrumenter);
// // Let's be friends with Spring ;)
// this.instrumenterMap.put("org.springframework.test.context.junit4.SpringJUnit4ClassRunner", runChildMethodInstrumenter);
// }
//
// @Override
// public boolean matches(CtClass ctClass) {
// return instrumenterMap.containsKey(ctClass.getName());
// }
//
// @Override
// public List<ClassHandler> getClassHandlers(CtClass ctClass) {
// return Collections.emptyList();
// }
//
// @Override
// public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) {
// return Collections.singletonList(instrumenterMap.get(ctMethod.getDeclaringClass().getName()));
// }
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/spock/SpockInstrumentationProvider.java
// public class SpockInstrumentationProvider implements InstrumentationProvider {
//
// private MethodInstrumenter runFeatureMethodInstrumenter;
//
// @Inject
// public SpockInstrumentationProvider(RunFeatureMethodInstrumenter runFeatureMethodInstrumenter) {
// this.runFeatureMethodInstrumenter = runFeatureMethodInstrumenter;
// }
//
// @Override
// public boolean matches(CtClass ctClass) {
// return ctClass.getName().contains("org.spockframework.runtime.BaseSpecRunner");
// }
//
// @Override
// public List<ClassHandler> getClassHandlers(CtClass ctClass) {
// return Collections.emptyList();
// }
//
// @Override
// public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) {
// if (ctMethod.getName().equals("runFeature")) {
// return Collections.singletonList(runFeatureMethodInstrumenter);
// }
// return Collections.emptyList();
// }
//
// }
| import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.jvoid.instrumentation.provider.api.InstrumentationProvider;
import io.jvoid.instrumentation.provider.app.AppInstrumentationProvider;
import io.jvoid.instrumentation.provider.junit4.JUnitInstrumentationProvider;
import io.jvoid.instrumentation.provider.spock.SpockInstrumentationProvider;
import javassist.CtClass; | package io.jvoid.instrumentation.provider;
/**
* Catalog of all the instrumentation providers that the JVoid agent will apply
* at runtime for classes instrumentation.
*
*/
@Singleton
public class ProviderCatalog {
private List<InstrumentationProvider> registeredProviders = new ArrayList<>();
// This is still "hardcoded" providers. Make it discover the providers in
// the classpath automatically
@Inject
public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider,
SpockInstrumentationProvider spockInstrumentationProvider, | // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java
// public interface InstrumentationProvider {
//
// boolean matches(CtClass ctClass);
//
// List<ClassHandler> getClassHandlers(CtClass ctClass);
//
// List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod);
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationProvider.java
// public class AppInstrumentationProvider implements InstrumentationProvider {
//
// private AppClassHandler appClassHandler;
// private MethodInstrumenter trackerMethodInstrumenter;
// private JVoidConfiguration jvoidConfiguration;
//
// @Inject
// public AppInstrumentationProvider(AppClassHandler appClassHandler,
// TrackerMethodInstrumenter trackerMethodInstrumenter, JVoidConfiguration jvoidConfiguration) {
// super();
// this.appClassHandler = appClassHandler;
// this.trackerMethodInstrumenter = trackerMethodInstrumenter;
// this.jvoidConfiguration = jvoidConfiguration;
// }
//
// @Override
// public boolean matches(CtClass ctClass) {
// JVoidConfiguration config = jvoidConfiguration;
// boolean matches = ctClass.getName().startsWith(config.basePackage());
// if (jvoidConfiguration.heuristicExcludeGroovyCallSite()) {
// matches = matches && !AppHeuristicHelper.isGroovyCallSite(ctClass);
// }
// return matches;
// }
//
// @Override
// public List<ClassHandler> getClassHandlers(CtClass ctClass) {
// return Collections.<ClassHandler> singletonList(appClassHandler);
// }
//
// @Override
// public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) {
// return Collections.singletonList(trackerMethodInstrumenter);
// }
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/junit4/JUnitInstrumentationProvider.java
// public class JUnitInstrumentationProvider implements InstrumentationProvider {
//
// private Map<String, MethodInstrumenter> instrumenterMap;
//
// @Inject
// public JUnitInstrumentationProvider(JUnitRunNotifierMethodInstrumenter junitRunNotifierMethodInstrumenter,
// RunChildMethodInstrumenter runChildMethodInstrumenter) {
// this.instrumenterMap = new HashMap<>();
// this.instrumenterMap.put("org.junit.runner.notification.RunNotifier", junitRunNotifierMethodInstrumenter);
// this.instrumenterMap.put("org.junit.runners.BlockJUnit4ClassRunner", runChildMethodInstrumenter);
// // Let's be friends with Spring ;)
// this.instrumenterMap.put("org.springframework.test.context.junit4.SpringJUnit4ClassRunner", runChildMethodInstrumenter);
// }
//
// @Override
// public boolean matches(CtClass ctClass) {
// return instrumenterMap.containsKey(ctClass.getName());
// }
//
// @Override
// public List<ClassHandler> getClassHandlers(CtClass ctClass) {
// return Collections.emptyList();
// }
//
// @Override
// public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) {
// return Collections.singletonList(instrumenterMap.get(ctMethod.getDeclaringClass().getName()));
// }
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/spock/SpockInstrumentationProvider.java
// public class SpockInstrumentationProvider implements InstrumentationProvider {
//
// private MethodInstrumenter runFeatureMethodInstrumenter;
//
// @Inject
// public SpockInstrumentationProvider(RunFeatureMethodInstrumenter runFeatureMethodInstrumenter) {
// this.runFeatureMethodInstrumenter = runFeatureMethodInstrumenter;
// }
//
// @Override
// public boolean matches(CtClass ctClass) {
// return ctClass.getName().contains("org.spockframework.runtime.BaseSpecRunner");
// }
//
// @Override
// public List<ClassHandler> getClassHandlers(CtClass ctClass) {
// return Collections.emptyList();
// }
//
// @Override
// public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) {
// if (ctMethod.getName().equals("runFeature")) {
// return Collections.singletonList(runFeatureMethodInstrumenter);
// }
// return Collections.emptyList();
// }
//
// }
// Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.jvoid.instrumentation.provider.api.InstrumentationProvider;
import io.jvoid.instrumentation.provider.app.AppInstrumentationProvider;
import io.jvoid.instrumentation.provider.junit4.JUnitInstrumentationProvider;
import io.jvoid.instrumentation.provider.spock.SpockInstrumentationProvider;
import javassist.CtClass;
package io.jvoid.instrumentation.provider;
/**
* Catalog of all the instrumentation providers that the JVoid agent will apply
* at runtime for classes instrumentation.
*
*/
@Singleton
public class ProviderCatalog {
private List<InstrumentationProvider> registeredProviders = new ArrayList<>();
// This is still "hardcoded" providers. Make it discover the providers in
// the classpath automatically
@Inject
public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider,
SpockInstrumentationProvider spockInstrumentationProvider, | JUnitInstrumentationProvider junitInstrumentationProvider) { |
jVoid/jVoid | src/main/java/io/jvoid/instrumentation/provider/junit4/JUnitRunNotifierMethodInstrumenter.java | // Path: src/main/java/io/jvoid/instrumentation/JVoidInstrumentationHelperHolder.java
// @Singleton
// public class JVoidInstrumentationHelperHolder {
//
// private JVoidInstrumentationHelper helper;
//
// private static final JVoidInstrumentationHelperHolder instance = new JVoidInstrumentationHelperHolder();
//
// public static JVoidInstrumentationHelperHolder getInstance() {
// return instance;
// }
//
// public JVoidInstrumentationHelper get() {
// return helper;
// }
//
// public void set(JVoidInstrumentationHelper helper) {
// this.helper = helper;
// }
//
// public static String helperGetterRef() {
// return JVoidInstrumentationHelperHolder.class.getName() + ".getInstance().get()";
// }
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java
// public interface MethodInstrumenter {
//
// void instrument(CtMethod ctMethod) throws CannotCompileException;
//
// boolean shouldInstrument(CtMethod ctMethod);
//
// }
| import java.util.HashMap;
import java.util.Map;
import io.jvoid.instrumentation.JVoidInstrumentationHelperHolder;
import io.jvoid.instrumentation.provider.api.MethodInstrumenter;
import javassist.CannotCompileException;
import javassist.CtMethod; | package io.jvoid.instrumentation.provider.junit4;
/**
* Method instrumenter for the JUnit 4 {@code RunNotifier}. It enables the tracking
* of the status of the test, and the cooperation with the JUnit lifecycle.
* Note: this is used indirectly by the Spock instrumentation provider as well.
*
*/
public class JUnitRunNotifierMethodInstrumenter implements MethodInstrumenter {
private final static Map<String, String> detectTestStatusMap = new HashMap<>();
static {
detectTestStatusMap.put("fireTestFailure", ".detectTestStatusFailure();");
detectTestStatusMap.put("fireTestAssumptionFailed", ".detectTestStatusFailure();");
detectTestStatusMap.put("fireTestIgnored", ".detectTestStatusSkip();");
detectTestStatusMap.put("fireTestFinished", ".detectTestStatusComplete();");
}
@Override
public void instrument(CtMethod ctMethod) throws CannotCompileException {
String methodName = ctMethod.getName();
if (detectTestStatusMap.containsKey(methodName)) {
StringBuilder sb = new StringBuilder(1024); | // Path: src/main/java/io/jvoid/instrumentation/JVoidInstrumentationHelperHolder.java
// @Singleton
// public class JVoidInstrumentationHelperHolder {
//
// private JVoidInstrumentationHelper helper;
//
// private static final JVoidInstrumentationHelperHolder instance = new JVoidInstrumentationHelperHolder();
//
// public static JVoidInstrumentationHelperHolder getInstance() {
// return instance;
// }
//
// public JVoidInstrumentationHelper get() {
// return helper;
// }
//
// public void set(JVoidInstrumentationHelper helper) {
// this.helper = helper;
// }
//
// public static String helperGetterRef() {
// return JVoidInstrumentationHelperHolder.class.getName() + ".getInstance().get()";
// }
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java
// public interface MethodInstrumenter {
//
// void instrument(CtMethod ctMethod) throws CannotCompileException;
//
// boolean shouldInstrument(CtMethod ctMethod);
//
// }
// Path: src/main/java/io/jvoid/instrumentation/provider/junit4/JUnitRunNotifierMethodInstrumenter.java
import java.util.HashMap;
import java.util.Map;
import io.jvoid.instrumentation.JVoidInstrumentationHelperHolder;
import io.jvoid.instrumentation.provider.api.MethodInstrumenter;
import javassist.CannotCompileException;
import javassist.CtMethod;
package io.jvoid.instrumentation.provider.junit4;
/**
* Method instrumenter for the JUnit 4 {@code RunNotifier}. It enables the tracking
* of the status of the test, and the cooperation with the JUnit lifecycle.
* Note: this is used indirectly by the Spock instrumentation provider as well.
*
*/
public class JUnitRunNotifierMethodInstrumenter implements MethodInstrumenter {
private final static Map<String, String> detectTestStatusMap = new HashMap<>();
static {
detectTestStatusMap.put("fireTestFailure", ".detectTestStatusFailure();");
detectTestStatusMap.put("fireTestAssumptionFailed", ".detectTestStatusFailure();");
detectTestStatusMap.put("fireTestIgnored", ".detectTestStatusSkip();");
detectTestStatusMap.put("fireTestFinished", ".detectTestStatusComplete();");
}
@Override
public void instrument(CtMethod ctMethod) throws CannotCompileException {
String methodName = ctMethod.getName();
if (detectTestStatusMap.containsKey(methodName)) {
StringBuilder sb = new StringBuilder(1024); | sb.append(JVoidInstrumentationHelperHolder.helperGetterRef() + |
jVoid/jVoid | src/main/java/io/jvoid/metadata/checksum/AbstractCtBehaviorChecksummer.java | // Path: src/main/java/io/jvoid/bytecode/JavassistUtils.java
// public class JavassistUtils {
//
// private JavassistUtils() {
// super();
// }
//
// /**
// * This is basically the InstructionPrinter.getMethodBytecode but with a
// * CtBehaviour parameter instead of a CtMethod
// *
// * @param behavior
// * @return
// */
// public static String getBehaviourBytecode(CtBehavior behavior) {
// MethodInfo info = behavior.getMethodInfo2();
// CodeAttribute code = info.getCodeAttribute();
// if (code == null) {
// return "";
// }
//
// ConstPool pool = info.getConstPool();
// StringBuilder sb = new StringBuilder(1024);
//
// CodeIterator iterator = code.iterator();
// while (iterator.hasNext()) {
// int pos;
// try {
// pos = iterator.next();
// } catch (BadBytecode e) {
// throw new JVoidIntrumentationException("BadBytecoode", e);
// }
//
// sb.append(pos + ": " + InstructionPrinter.instructionString(iterator, pos, pool) + "\n");
// }
// return sb.toString();
// }
// }
//
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java
// public interface JVoidConfiguration {
//
// String dbUrl();
//
// String dbUsername();
//
// String dbPassword();
//
// String basePackage();
//
// String excludes();
//
// String includes();
//
// Boolean heuristicExcludeCglib();
//
// Boolean heuristicExcludeJacoco();
//
// Boolean heuristicExcludeGroovyCallSite();
//
// }
| import com.google.inject.Inject;
import io.jvoid.bytecode.JavassistUtils;
import io.jvoid.configuration.JVoidConfiguration;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.NotFoundException;
import lombok.extern.slf4j.Slf4j; | package io.jvoid.metadata.checksum;
/**
*
*/
@Slf4j
abstract class AbstractCtBehaviorChecksummer<S extends CtBehavior> extends AbstractChecksummer<S> {
@Inject | // Path: src/main/java/io/jvoid/bytecode/JavassistUtils.java
// public class JavassistUtils {
//
// private JavassistUtils() {
// super();
// }
//
// /**
// * This is basically the InstructionPrinter.getMethodBytecode but with a
// * CtBehaviour parameter instead of a CtMethod
// *
// * @param behavior
// * @return
// */
// public static String getBehaviourBytecode(CtBehavior behavior) {
// MethodInfo info = behavior.getMethodInfo2();
// CodeAttribute code = info.getCodeAttribute();
// if (code == null) {
// return "";
// }
//
// ConstPool pool = info.getConstPool();
// StringBuilder sb = new StringBuilder(1024);
//
// CodeIterator iterator = code.iterator();
// while (iterator.hasNext()) {
// int pos;
// try {
// pos = iterator.next();
// } catch (BadBytecode e) {
// throw new JVoidIntrumentationException("BadBytecoode", e);
// }
//
// sb.append(pos + ": " + InstructionPrinter.instructionString(iterator, pos, pool) + "\n");
// }
// return sb.toString();
// }
// }
//
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java
// public interface JVoidConfiguration {
//
// String dbUrl();
//
// String dbUsername();
//
// String dbPassword();
//
// String basePackage();
//
// String excludes();
//
// String includes();
//
// Boolean heuristicExcludeCglib();
//
// Boolean heuristicExcludeJacoco();
//
// Boolean heuristicExcludeGroovyCallSite();
//
// }
// Path: src/main/java/io/jvoid/metadata/checksum/AbstractCtBehaviorChecksummer.java
import com.google.inject.Inject;
import io.jvoid.bytecode.JavassistUtils;
import io.jvoid.configuration.JVoidConfiguration;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.NotFoundException;
import lombok.extern.slf4j.Slf4j;
package io.jvoid.metadata.checksum;
/**
*
*/
@Slf4j
abstract class AbstractCtBehaviorChecksummer<S extends CtBehavior> extends AbstractChecksummer<S> {
@Inject | public AbstractCtBehaviorChecksummer(JVoidConfiguration jVoidConfiguration) { |
jVoid/jVoid | src/main/java/io/jvoid/metadata/checksum/AbstractCtBehaviorChecksummer.java | // Path: src/main/java/io/jvoid/bytecode/JavassistUtils.java
// public class JavassistUtils {
//
// private JavassistUtils() {
// super();
// }
//
// /**
// * This is basically the InstructionPrinter.getMethodBytecode but with a
// * CtBehaviour parameter instead of a CtMethod
// *
// * @param behavior
// * @return
// */
// public static String getBehaviourBytecode(CtBehavior behavior) {
// MethodInfo info = behavior.getMethodInfo2();
// CodeAttribute code = info.getCodeAttribute();
// if (code == null) {
// return "";
// }
//
// ConstPool pool = info.getConstPool();
// StringBuilder sb = new StringBuilder(1024);
//
// CodeIterator iterator = code.iterator();
// while (iterator.hasNext()) {
// int pos;
// try {
// pos = iterator.next();
// } catch (BadBytecode e) {
// throw new JVoidIntrumentationException("BadBytecoode", e);
// }
//
// sb.append(pos + ": " + InstructionPrinter.instructionString(iterator, pos, pool) + "\n");
// }
// return sb.toString();
// }
// }
//
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java
// public interface JVoidConfiguration {
//
// String dbUrl();
//
// String dbUsername();
//
// String dbPassword();
//
// String basePackage();
//
// String excludes();
//
// String includes();
//
// Boolean heuristicExcludeCglib();
//
// Boolean heuristicExcludeJacoco();
//
// Boolean heuristicExcludeGroovyCallSite();
//
// }
| import com.google.inject.Inject;
import io.jvoid.bytecode.JavassistUtils;
import io.jvoid.configuration.JVoidConfiguration;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.NotFoundException;
import lombok.extern.slf4j.Slf4j; | package io.jvoid.metadata.checksum;
/**
*
*/
@Slf4j
abstract class AbstractCtBehaviorChecksummer<S extends CtBehavior> extends AbstractChecksummer<S> {
@Inject
public AbstractCtBehaviorChecksummer(JVoidConfiguration jVoidConfiguration) {
super(jVoidConfiguration);
}
@Override
public String checksum(S behavior) {
StringBuilder data = new StringBuilder(1024);
data.append(behavior.getLongName());
try {
for (CtClass exceptionTypes : behavior.getExceptionTypes()) {
data.append(exceptionTypes.getName());
}
} catch (NotFoundException e) {
log.trace("CtClass not found when adding parameter types to behaviour checksum", e);
}
for (Object[] parameterAnnotations : behavior.getAvailableParameterAnnotations()) {
for (Object annotation : parameterAnnotations) {
data.append(annotation.toString());
}
}
| // Path: src/main/java/io/jvoid/bytecode/JavassistUtils.java
// public class JavassistUtils {
//
// private JavassistUtils() {
// super();
// }
//
// /**
// * This is basically the InstructionPrinter.getMethodBytecode but with a
// * CtBehaviour parameter instead of a CtMethod
// *
// * @param behavior
// * @return
// */
// public static String getBehaviourBytecode(CtBehavior behavior) {
// MethodInfo info = behavior.getMethodInfo2();
// CodeAttribute code = info.getCodeAttribute();
// if (code == null) {
// return "";
// }
//
// ConstPool pool = info.getConstPool();
// StringBuilder sb = new StringBuilder(1024);
//
// CodeIterator iterator = code.iterator();
// while (iterator.hasNext()) {
// int pos;
// try {
// pos = iterator.next();
// } catch (BadBytecode e) {
// throw new JVoidIntrumentationException("BadBytecoode", e);
// }
//
// sb.append(pos + ": " + InstructionPrinter.instructionString(iterator, pos, pool) + "\n");
// }
// return sb.toString();
// }
// }
//
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java
// public interface JVoidConfiguration {
//
// String dbUrl();
//
// String dbUsername();
//
// String dbPassword();
//
// String basePackage();
//
// String excludes();
//
// String includes();
//
// Boolean heuristicExcludeCglib();
//
// Boolean heuristicExcludeJacoco();
//
// Boolean heuristicExcludeGroovyCallSite();
//
// }
// Path: src/main/java/io/jvoid/metadata/checksum/AbstractCtBehaviorChecksummer.java
import com.google.inject.Inject;
import io.jvoid.bytecode.JavassistUtils;
import io.jvoid.configuration.JVoidConfiguration;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.NotFoundException;
import lombok.extern.slf4j.Slf4j;
package io.jvoid.metadata.checksum;
/**
*
*/
@Slf4j
abstract class AbstractCtBehaviorChecksummer<S extends CtBehavior> extends AbstractChecksummer<S> {
@Inject
public AbstractCtBehaviorChecksummer(JVoidConfiguration jVoidConfiguration) {
super(jVoidConfiguration);
}
@Override
public String checksum(S behavior) {
StringBuilder data = new StringBuilder(1024);
data.append(behavior.getLongName());
try {
for (CtClass exceptionTypes : behavior.getExceptionTypes()) {
data.append(exceptionTypes.getName());
}
} catch (NotFoundException e) {
log.trace("CtClass not found when adding parameter types to behaviour checksum", e);
}
for (Object[] parameterAnnotations : behavior.getAvailableParameterAnnotations()) {
for (Object annotation : parameterAnnotations) {
data.append(annotation.toString());
}
}
| data.append(JavassistUtils.getBehaviourBytecode(behavior)); |
jVoid/jVoid | src/main/java/io/jvoid/bytecode/JavassistUtils.java | // Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java
// public class JVoidIntrumentationException extends RuntimeException {
//
// private static final long serialVersionUID = 1;
//
// public JVoidIntrumentationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public JVoidIntrumentationException(String cause) {
// super(cause);
// }
//
// }
| import io.jvoid.exceptions.JVoidIntrumentationException;
import javassist.CtBehavior;
import javassist.bytecode.BadBytecode;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.CodeIterator;
import javassist.bytecode.ConstPool;
import javassist.bytecode.InstructionPrinter;
import javassist.bytecode.MethodInfo; | package io.jvoid.bytecode;
/**
* Some helper methods that complements Javassist functionalities.
*
*/
public class JavassistUtils {
private JavassistUtils() {
super();
}
/**
* This is basically the InstructionPrinter.getMethodBytecode but with a
* CtBehaviour parameter instead of a CtMethod
*
* @param behavior
* @return
*/
public static String getBehaviourBytecode(CtBehavior behavior) {
MethodInfo info = behavior.getMethodInfo2();
CodeAttribute code = info.getCodeAttribute();
if (code == null) {
return "";
}
ConstPool pool = info.getConstPool();
StringBuilder sb = new StringBuilder(1024);
CodeIterator iterator = code.iterator();
while (iterator.hasNext()) {
int pos;
try {
pos = iterator.next();
} catch (BadBytecode e) { | // Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java
// public class JVoidIntrumentationException extends RuntimeException {
//
// private static final long serialVersionUID = 1;
//
// public JVoidIntrumentationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public JVoidIntrumentationException(String cause) {
// super(cause);
// }
//
// }
// Path: src/main/java/io/jvoid/bytecode/JavassistUtils.java
import io.jvoid.exceptions.JVoidIntrumentationException;
import javassist.CtBehavior;
import javassist.bytecode.BadBytecode;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.CodeIterator;
import javassist.bytecode.ConstPool;
import javassist.bytecode.InstructionPrinter;
import javassist.bytecode.MethodInfo;
package io.jvoid.bytecode;
/**
* Some helper methods that complements Javassist functionalities.
*
*/
public class JavassistUtils {
private JavassistUtils() {
super();
}
/**
* This is basically the InstructionPrinter.getMethodBytecode but with a
* CtBehaviour parameter instead of a CtMethod
*
* @param behavior
* @return
*/
public static String getBehaviourBytecode(CtBehavior behavior) {
MethodInfo info = behavior.getMethodInfo2();
CodeAttribute code = info.getCodeAttribute();
if (code == null) {
return "";
}
ConstPool pool = info.getConstPool();
StringBuilder sb = new StringBuilder(1024);
CodeIterator iterator = code.iterator();
while (iterator.hasNext()) {
int pos;
try {
pos = iterator.next();
} catch (BadBytecode e) { | throw new JVoidIntrumentationException("BadBytecoode", e); |
jVoid/jVoid | src/main/java/io/jvoid/execution/JVoidExecutionContext.java | // Path: src/main/java/io/jvoid/metadata/model/JExecution.java
// @Data
// public class JExecution implements JEntity<Long> {
//
// private Long id;
// private Long timestamp;
//
// }
//
// Path: src/main/java/io/jvoid/metadata/model/JTest.java
// @Data
// public class JTest implements JEntity<Long> {
//
// public static final String RUN_STATUS_RUN = "RUN";
// public static final String RUN_STATUS_RUNNING = "RUNNING";
// public static final String RUN_STATUS_SKIPPED = "SKIPPED";
// public static final String RUN_STATUS_FAILED = "FAILED";
//
// private Long id;
// private Long executionId;
// private String identifier;
// private String runStatus = RUN_STATUS_RUNNING;
//
// }
//
// Path: src/main/java/io/jvoid/metadata/repositories/ExecutionsRepository.java
// @Singleton
// public class ExecutionsRepository extends AbstractRepository<JExecution, Long> {
//
// private ResultSetHandler<JExecution> objectHandler = new BeanHandler<>(JExecution.class);
//
// @Inject
// public ExecutionsRepository(MetadataDatabase database) {
// super(database);
// }
//
// @Override
// public JExecution findById(Long id) {
// return query("SELECT * FROM executions WHERE id = ?", objectHandler, id);
// }
//
// @Override
// public JExecution add(JExecution execution) {
// assertNull(execution.getId());
// long id = executeInsert("INSERT INTO executions (timestamp) VALUES (?)", execution.getTimestamp());
// execution.setId(id);
// return execution;
// }
//
// }
| import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.jvoid.metadata.model.JExecution;
import io.jvoid.metadata.model.JTest;
import io.jvoid.metadata.repositories.ExecutionsRepository; | package io.jvoid.execution;
/**
* The {@code JVoidExecutionContext} keeps track of a current JVoid execution
* or session, that is defined basically by an execution of the tests of the project.
* It keeps track of the current execution ID and of various runtime parameters like
* the current running test.
*
*/
@Singleton
public class JVoidExecutionContext {
| // Path: src/main/java/io/jvoid/metadata/model/JExecution.java
// @Data
// public class JExecution implements JEntity<Long> {
//
// private Long id;
// private Long timestamp;
//
// }
//
// Path: src/main/java/io/jvoid/metadata/model/JTest.java
// @Data
// public class JTest implements JEntity<Long> {
//
// public static final String RUN_STATUS_RUN = "RUN";
// public static final String RUN_STATUS_RUNNING = "RUNNING";
// public static final String RUN_STATUS_SKIPPED = "SKIPPED";
// public static final String RUN_STATUS_FAILED = "FAILED";
//
// private Long id;
// private Long executionId;
// private String identifier;
// private String runStatus = RUN_STATUS_RUNNING;
//
// }
//
// Path: src/main/java/io/jvoid/metadata/repositories/ExecutionsRepository.java
// @Singleton
// public class ExecutionsRepository extends AbstractRepository<JExecution, Long> {
//
// private ResultSetHandler<JExecution> objectHandler = new BeanHandler<>(JExecution.class);
//
// @Inject
// public ExecutionsRepository(MetadataDatabase database) {
// super(database);
// }
//
// @Override
// public JExecution findById(Long id) {
// return query("SELECT * FROM executions WHERE id = ?", objectHandler, id);
// }
//
// @Override
// public JExecution add(JExecution execution) {
// assertNull(execution.getId());
// long id = executeInsert("INSERT INTO executions (timestamp) VALUES (?)", execution.getTimestamp());
// execution.setId(id);
// return execution;
// }
//
// }
// Path: src/main/java/io/jvoid/execution/JVoidExecutionContext.java
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.jvoid.metadata.model.JExecution;
import io.jvoid.metadata.model.JTest;
import io.jvoid.metadata.repositories.ExecutionsRepository;
package io.jvoid.execution;
/**
* The {@code JVoidExecutionContext} keeps track of a current JVoid execution
* or session, that is defined basically by an execution of the tests of the project.
* It keeps track of the current execution ID and of various runtime parameters like
* the current running test.
*
*/
@Singleton
public class JVoidExecutionContext {
| private ExecutionsRepository executionsRepository; |
jVoid/jVoid | src/main/java/io/jvoid/execution/JVoidExecutionContext.java | // Path: src/main/java/io/jvoid/metadata/model/JExecution.java
// @Data
// public class JExecution implements JEntity<Long> {
//
// private Long id;
// private Long timestamp;
//
// }
//
// Path: src/main/java/io/jvoid/metadata/model/JTest.java
// @Data
// public class JTest implements JEntity<Long> {
//
// public static final String RUN_STATUS_RUN = "RUN";
// public static final String RUN_STATUS_RUNNING = "RUNNING";
// public static final String RUN_STATUS_SKIPPED = "SKIPPED";
// public static final String RUN_STATUS_FAILED = "FAILED";
//
// private Long id;
// private Long executionId;
// private String identifier;
// private String runStatus = RUN_STATUS_RUNNING;
//
// }
//
// Path: src/main/java/io/jvoid/metadata/repositories/ExecutionsRepository.java
// @Singleton
// public class ExecutionsRepository extends AbstractRepository<JExecution, Long> {
//
// private ResultSetHandler<JExecution> objectHandler = new BeanHandler<>(JExecution.class);
//
// @Inject
// public ExecutionsRepository(MetadataDatabase database) {
// super(database);
// }
//
// @Override
// public JExecution findById(Long id) {
// return query("SELECT * FROM executions WHERE id = ?", objectHandler, id);
// }
//
// @Override
// public JExecution add(JExecution execution) {
// assertNull(execution.getId());
// long id = executeInsert("INSERT INTO executions (timestamp) VALUES (?)", execution.getTimestamp());
// execution.setId(id);
// return execution;
// }
//
// }
| import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.jvoid.metadata.model.JExecution;
import io.jvoid.metadata.model.JTest;
import io.jvoid.metadata.repositories.ExecutionsRepository; | package io.jvoid.execution;
/**
* The {@code JVoidExecutionContext} keeps track of a current JVoid execution
* or session, that is defined basically by an execution of the tests of the project.
* It keeps track of the current execution ID and of various runtime parameters like
* the current running test.
*
*/
@Singleton
public class JVoidExecutionContext {
private ExecutionsRepository executionsRepository;
| // Path: src/main/java/io/jvoid/metadata/model/JExecution.java
// @Data
// public class JExecution implements JEntity<Long> {
//
// private Long id;
// private Long timestamp;
//
// }
//
// Path: src/main/java/io/jvoid/metadata/model/JTest.java
// @Data
// public class JTest implements JEntity<Long> {
//
// public static final String RUN_STATUS_RUN = "RUN";
// public static final String RUN_STATUS_RUNNING = "RUNNING";
// public static final String RUN_STATUS_SKIPPED = "SKIPPED";
// public static final String RUN_STATUS_FAILED = "FAILED";
//
// private Long id;
// private Long executionId;
// private String identifier;
// private String runStatus = RUN_STATUS_RUNNING;
//
// }
//
// Path: src/main/java/io/jvoid/metadata/repositories/ExecutionsRepository.java
// @Singleton
// public class ExecutionsRepository extends AbstractRepository<JExecution, Long> {
//
// private ResultSetHandler<JExecution> objectHandler = new BeanHandler<>(JExecution.class);
//
// @Inject
// public ExecutionsRepository(MetadataDatabase database) {
// super(database);
// }
//
// @Override
// public JExecution findById(Long id) {
// return query("SELECT * FROM executions WHERE id = ?", objectHandler, id);
// }
//
// @Override
// public JExecution add(JExecution execution) {
// assertNull(execution.getId());
// long id = executeInsert("INSERT INTO executions (timestamp) VALUES (?)", execution.getTimestamp());
// execution.setId(id);
// return execution;
// }
//
// }
// Path: src/main/java/io/jvoid/execution/JVoidExecutionContext.java
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.jvoid.metadata.model.JExecution;
import io.jvoid.metadata.model.JTest;
import io.jvoid.metadata.repositories.ExecutionsRepository;
package io.jvoid.execution;
/**
* The {@code JVoidExecutionContext} keeps track of a current JVoid execution
* or session, that is defined basically by an execution of the tests of the project.
* It keeps track of the current execution ID and of various runtime parameters like
* the current running test.
*
*/
@Singleton
public class JVoidExecutionContext {
private ExecutionsRepository executionsRepository;
| private JExecution currentExecution; |
jVoid/jVoid | src/main/java/io/jvoid/execution/JVoidExecutionContext.java | // Path: src/main/java/io/jvoid/metadata/model/JExecution.java
// @Data
// public class JExecution implements JEntity<Long> {
//
// private Long id;
// private Long timestamp;
//
// }
//
// Path: src/main/java/io/jvoid/metadata/model/JTest.java
// @Data
// public class JTest implements JEntity<Long> {
//
// public static final String RUN_STATUS_RUN = "RUN";
// public static final String RUN_STATUS_RUNNING = "RUNNING";
// public static final String RUN_STATUS_SKIPPED = "SKIPPED";
// public static final String RUN_STATUS_FAILED = "FAILED";
//
// private Long id;
// private Long executionId;
// private String identifier;
// private String runStatus = RUN_STATUS_RUNNING;
//
// }
//
// Path: src/main/java/io/jvoid/metadata/repositories/ExecutionsRepository.java
// @Singleton
// public class ExecutionsRepository extends AbstractRepository<JExecution, Long> {
//
// private ResultSetHandler<JExecution> objectHandler = new BeanHandler<>(JExecution.class);
//
// @Inject
// public ExecutionsRepository(MetadataDatabase database) {
// super(database);
// }
//
// @Override
// public JExecution findById(Long id) {
// return query("SELECT * FROM executions WHERE id = ?", objectHandler, id);
// }
//
// @Override
// public JExecution add(JExecution execution) {
// assertNull(execution.getId());
// long id = executeInsert("INSERT INTO executions (timestamp) VALUES (?)", execution.getTimestamp());
// execution.setId(id);
// return execution;
// }
//
// }
| import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.jvoid.metadata.model.JExecution;
import io.jvoid.metadata.model.JTest;
import io.jvoid.metadata.repositories.ExecutionsRepository; | package io.jvoid.execution;
/**
* The {@code JVoidExecutionContext} keeps track of a current JVoid execution
* or session, that is defined basically by an execution of the tests of the project.
* It keeps track of the current execution ID and of various runtime parameters like
* the current running test.
*
*/
@Singleton
public class JVoidExecutionContext {
private ExecutionsRepository executionsRepository;
private JExecution currentExecution;
| // Path: src/main/java/io/jvoid/metadata/model/JExecution.java
// @Data
// public class JExecution implements JEntity<Long> {
//
// private Long id;
// private Long timestamp;
//
// }
//
// Path: src/main/java/io/jvoid/metadata/model/JTest.java
// @Data
// public class JTest implements JEntity<Long> {
//
// public static final String RUN_STATUS_RUN = "RUN";
// public static final String RUN_STATUS_RUNNING = "RUNNING";
// public static final String RUN_STATUS_SKIPPED = "SKIPPED";
// public static final String RUN_STATUS_FAILED = "FAILED";
//
// private Long id;
// private Long executionId;
// private String identifier;
// private String runStatus = RUN_STATUS_RUNNING;
//
// }
//
// Path: src/main/java/io/jvoid/metadata/repositories/ExecutionsRepository.java
// @Singleton
// public class ExecutionsRepository extends AbstractRepository<JExecution, Long> {
//
// private ResultSetHandler<JExecution> objectHandler = new BeanHandler<>(JExecution.class);
//
// @Inject
// public ExecutionsRepository(MetadataDatabase database) {
// super(database);
// }
//
// @Override
// public JExecution findById(Long id) {
// return query("SELECT * FROM executions WHERE id = ?", objectHandler, id);
// }
//
// @Override
// public JExecution add(JExecution execution) {
// assertNull(execution.getId());
// long id = executeInsert("INSERT INTO executions (timestamp) VALUES (?)", execution.getTimestamp());
// execution.setId(id);
// return execution;
// }
//
// }
// Path: src/main/java/io/jvoid/execution/JVoidExecutionContext.java
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.jvoid.metadata.model.JExecution;
import io.jvoid.metadata.model.JTest;
import io.jvoid.metadata.repositories.ExecutionsRepository;
package io.jvoid.execution;
/**
* The {@code JVoidExecutionContext} keeps track of a current JVoid execution
* or session, that is defined basically by an execution of the tests of the project.
* It keeps track of the current execution ID and of various runtime parameters like
* the current running test.
*
*/
@Singleton
public class JVoidExecutionContext {
private ExecutionsRepository executionsRepository;
private JExecution currentExecution;
| private ThreadLocal<JTest> runningTestHolder = new ThreadLocal<>(); |
jVoid/jVoid | src/main/java/io/jvoid/instrumentation/provider/junit4/JUnitInstrumentationProvider.java | // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java
// public interface ClassHandler {
//
// void handleClass(CtClass ctClass) throws CannotCompileException;
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java
// public interface InstrumentationProvider {
//
// boolean matches(CtClass ctClass);
//
// List<ClassHandler> getClassHandlers(CtClass ctClass);
//
// List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod);
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java
// public interface MethodInstrumenter {
//
// void instrument(CtMethod ctMethod) throws CannotCompileException;
//
// boolean shouldInstrument(CtMethod ctMethod);
//
// }
| import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.inject.Inject;
import io.jvoid.instrumentation.provider.api.ClassHandler;
import io.jvoid.instrumentation.provider.api.InstrumentationProvider;
import io.jvoid.instrumentation.provider.api.MethodInstrumenter;
import javassist.CtClass;
import javassist.CtMethod; | package io.jvoid.instrumentation.provider.junit4;
/**
* JVoid instrumentation provider for JUnit 4. It will integrate with JUnit 4 test
* lifecycle, being able to track the status of the tests and skipping them in case
* their execution is not necessary because no changes have been made to the classes
* of the application.
*
*/
public class JUnitInstrumentationProvider implements InstrumentationProvider {
private Map<String, MethodInstrumenter> instrumenterMap;
@Inject
public JUnitInstrumentationProvider(JUnitRunNotifierMethodInstrumenter junitRunNotifierMethodInstrumenter,
RunChildMethodInstrumenter runChildMethodInstrumenter) {
this.instrumenterMap = new HashMap<>();
this.instrumenterMap.put("org.junit.runner.notification.RunNotifier", junitRunNotifierMethodInstrumenter);
this.instrumenterMap.put("org.junit.runners.BlockJUnit4ClassRunner", runChildMethodInstrumenter);
// Let's be friends with Spring ;)
this.instrumenterMap.put("org.springframework.test.context.junit4.SpringJUnit4ClassRunner", runChildMethodInstrumenter);
}
@Override
public boolean matches(CtClass ctClass) {
return instrumenterMap.containsKey(ctClass.getName());
}
@Override | // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java
// public interface ClassHandler {
//
// void handleClass(CtClass ctClass) throws CannotCompileException;
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java
// public interface InstrumentationProvider {
//
// boolean matches(CtClass ctClass);
//
// List<ClassHandler> getClassHandlers(CtClass ctClass);
//
// List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod);
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java
// public interface MethodInstrumenter {
//
// void instrument(CtMethod ctMethod) throws CannotCompileException;
//
// boolean shouldInstrument(CtMethod ctMethod);
//
// }
// Path: src/main/java/io/jvoid/instrumentation/provider/junit4/JUnitInstrumentationProvider.java
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.inject.Inject;
import io.jvoid.instrumentation.provider.api.ClassHandler;
import io.jvoid.instrumentation.provider.api.InstrumentationProvider;
import io.jvoid.instrumentation.provider.api.MethodInstrumenter;
import javassist.CtClass;
import javassist.CtMethod;
package io.jvoid.instrumentation.provider.junit4;
/**
* JVoid instrumentation provider for JUnit 4. It will integrate with JUnit 4 test
* lifecycle, being able to track the status of the tests and skipping them in case
* their execution is not necessary because no changes have been made to the classes
* of the application.
*
*/
public class JUnitInstrumentationProvider implements InstrumentationProvider {
private Map<String, MethodInstrumenter> instrumenterMap;
@Inject
public JUnitInstrumentationProvider(JUnitRunNotifierMethodInstrumenter junitRunNotifierMethodInstrumenter,
RunChildMethodInstrumenter runChildMethodInstrumenter) {
this.instrumenterMap = new HashMap<>();
this.instrumenterMap.put("org.junit.runner.notification.RunNotifier", junitRunNotifierMethodInstrumenter);
this.instrumenterMap.put("org.junit.runners.BlockJUnit4ClassRunner", runChildMethodInstrumenter);
// Let's be friends with Spring ;)
this.instrumenterMap.put("org.springframework.test.context.junit4.SpringJUnit4ClassRunner", runChildMethodInstrumenter);
}
@Override
public boolean matches(CtClass ctClass) {
return instrumenterMap.containsKey(ctClass.getName());
}
@Override | public List<ClassHandler> getClassHandlers(CtClass ctClass) { |
jVoid/jVoid | src/main/java/io/jvoid/database/MetadataDatabase.java | // Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java
// public interface JVoidConfiguration {
//
// String dbUrl();
//
// String dbUsername();
//
// String dbPassword();
//
// String basePackage();
//
// String excludes();
//
// String includes();
//
// Boolean heuristicExcludeCglib();
//
// Boolean heuristicExcludeJacoco();
//
// Boolean heuristicExcludeGroovyCallSite();
//
// }
//
// Path: src/main/java/io/jvoid/exceptions/JVoidDataAccessException.java
// public class JVoidDataAccessException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public JVoidDataAccessException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// public JVoidDataAccessException(Throwable cause) {
// super(cause);
// }
//
// }
| import java.sql.Connection;
import java.sql.SQLException;
import org.flywaydb.core.Flyway;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import io.jvoid.configuration.JVoidConfiguration;
import io.jvoid.exceptions.JVoidDataAccessException; | package io.jvoid.database;
/**
* This class manages the data-source for accessing the particular database used with JVoid.
*
*/
@Singleton
public class MetadataDatabase {
| // Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java
// public interface JVoidConfiguration {
//
// String dbUrl();
//
// String dbUsername();
//
// String dbPassword();
//
// String basePackage();
//
// String excludes();
//
// String includes();
//
// Boolean heuristicExcludeCglib();
//
// Boolean heuristicExcludeJacoco();
//
// Boolean heuristicExcludeGroovyCallSite();
//
// }
//
// Path: src/main/java/io/jvoid/exceptions/JVoidDataAccessException.java
// public class JVoidDataAccessException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public JVoidDataAccessException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// public JVoidDataAccessException(Throwable cause) {
// super(cause);
// }
//
// }
// Path: src/main/java/io/jvoid/database/MetadataDatabase.java
import java.sql.Connection;
import java.sql.SQLException;
import org.flywaydb.core.Flyway;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import io.jvoid.configuration.JVoidConfiguration;
import io.jvoid.exceptions.JVoidDataAccessException;
package io.jvoid.database;
/**
* This class manages the data-source for accessing the particular database used with JVoid.
*
*/
@Singleton
public class MetadataDatabase {
| private JVoidConfiguration configuration; |
jVoid/jVoid | src/main/java/io/jvoid/database/MetadataDatabase.java | // Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java
// public interface JVoidConfiguration {
//
// String dbUrl();
//
// String dbUsername();
//
// String dbPassword();
//
// String basePackage();
//
// String excludes();
//
// String includes();
//
// Boolean heuristicExcludeCglib();
//
// Boolean heuristicExcludeJacoco();
//
// Boolean heuristicExcludeGroovyCallSite();
//
// }
//
// Path: src/main/java/io/jvoid/exceptions/JVoidDataAccessException.java
// public class JVoidDataAccessException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public JVoidDataAccessException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// public JVoidDataAccessException(Throwable cause) {
// super(cause);
// }
//
// }
| import java.sql.Connection;
import java.sql.SQLException;
import org.flywaydb.core.Flyway;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import io.jvoid.configuration.JVoidConfiguration;
import io.jvoid.exceptions.JVoidDataAccessException; | initializeDatabase();
}
/**
*
*/
public void shutdown() {
if (ds != null) {
ds.close();
ds = null;
}
}
/**
*
*/
private void initializeDatabase() {
Flyway flyway = new Flyway();
flyway.setDataSource(ds);
flyway.migrate();
}
/**
*
* @return A connection from the pool
*/
public Connection getConnection() {
try {
return ds.getConnection();
} catch (SQLException e) { | // Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java
// public interface JVoidConfiguration {
//
// String dbUrl();
//
// String dbUsername();
//
// String dbPassword();
//
// String basePackage();
//
// String excludes();
//
// String includes();
//
// Boolean heuristicExcludeCglib();
//
// Boolean heuristicExcludeJacoco();
//
// Boolean heuristicExcludeGroovyCallSite();
//
// }
//
// Path: src/main/java/io/jvoid/exceptions/JVoidDataAccessException.java
// public class JVoidDataAccessException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public JVoidDataAccessException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// public JVoidDataAccessException(Throwable cause) {
// super(cause);
// }
//
// }
// Path: src/main/java/io/jvoid/database/MetadataDatabase.java
import java.sql.Connection;
import java.sql.SQLException;
import org.flywaydb.core.Flyway;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import io.jvoid.configuration.JVoidConfiguration;
import io.jvoid.exceptions.JVoidDataAccessException;
initializeDatabase();
}
/**
*
*/
public void shutdown() {
if (ds != null) {
ds.close();
ds = null;
}
}
/**
*
*/
private void initializeDatabase() {
Flyway flyway = new Flyway();
flyway.setDataSource(ds);
flyway.migrate();
}
/**
*
* @return A connection from the pool
*/
public Connection getConnection() {
try {
return ds.getConnection();
} catch (SQLException e) { | throw new JVoidDataAccessException(e); |
jVoid/jVoid | src/main/java/io/jvoid/instrumentation/provider/junit4/RunChildMethodInstrumenter.java | // Path: src/main/java/io/jvoid/instrumentation/JVoidInstrumentationHelperHolder.java
// @Singleton
// public class JVoidInstrumentationHelperHolder {
//
// private JVoidInstrumentationHelper helper;
//
// private static final JVoidInstrumentationHelperHolder instance = new JVoidInstrumentationHelperHolder();
//
// public static JVoidInstrumentationHelperHolder getInstance() {
// return instance;
// }
//
// public JVoidInstrumentationHelper get() {
// return helper;
// }
//
// public void set(JVoidInstrumentationHelper helper) {
// this.helper = helper;
// }
//
// public static String helperGetterRef() {
// return JVoidInstrumentationHelperHolder.class.getName() + ".getInstance().get()";
// }
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java
// public interface MethodInstrumenter {
//
// void instrument(CtMethod ctMethod) throws CannotCompileException;
//
// boolean shouldInstrument(CtMethod ctMethod);
//
// }
| import io.jvoid.instrumentation.JVoidInstrumentationHelperHolder;
import io.jvoid.instrumentation.provider.api.MethodInstrumenter;
import javassist.CannotCompileException;
import javassist.CtMethod; | package io.jvoid.instrumentation.provider.junit4;
/**
* Tracker method for JUnit 4 tests. It notifies JVoid that a test is going
* to be executed.
*
*/
public class RunChildMethodInstrumenter implements MethodInstrumenter {
@Override
public void instrument(CtMethod ctMethod) throws CannotCompileException {
if (ctMethod.getName().equals("runChild")) {
StringBuilder sb = new StringBuilder(1024);
sb.append("org.junit.runners.model.FrameworkMethod __jvoid_frameworkMethod = (org.junit.runners.model.FrameworkMethod) $1;");
sb.append("org.junit.runner.notification.RunNotifier __jvoid_notifier = (org.junit.runner.notification.RunNotifier) $2;");
sb.append("java.lang.reflect.Method __jvoid_javaMethod = __jvoid_frameworkMethod.getMethod();\n");
sb.append("String featureId = (__jvoid_javaMethod.getDeclaringClass().getName() + \"#\" + __jvoid_javaMethod.getName());\n"); | // Path: src/main/java/io/jvoid/instrumentation/JVoidInstrumentationHelperHolder.java
// @Singleton
// public class JVoidInstrumentationHelperHolder {
//
// private JVoidInstrumentationHelper helper;
//
// private static final JVoidInstrumentationHelperHolder instance = new JVoidInstrumentationHelperHolder();
//
// public static JVoidInstrumentationHelperHolder getInstance() {
// return instance;
// }
//
// public JVoidInstrumentationHelper get() {
// return helper;
// }
//
// public void set(JVoidInstrumentationHelper helper) {
// this.helper = helper;
// }
//
// public static String helperGetterRef() {
// return JVoidInstrumentationHelperHolder.class.getName() + ".getInstance().get()";
// }
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java
// public interface MethodInstrumenter {
//
// void instrument(CtMethod ctMethod) throws CannotCompileException;
//
// boolean shouldInstrument(CtMethod ctMethod);
//
// }
// Path: src/main/java/io/jvoid/instrumentation/provider/junit4/RunChildMethodInstrumenter.java
import io.jvoid.instrumentation.JVoidInstrumentationHelperHolder;
import io.jvoid.instrumentation.provider.api.MethodInstrumenter;
import javassist.CannotCompileException;
import javassist.CtMethod;
package io.jvoid.instrumentation.provider.junit4;
/**
* Tracker method for JUnit 4 tests. It notifies JVoid that a test is going
* to be executed.
*
*/
public class RunChildMethodInstrumenter implements MethodInstrumenter {
@Override
public void instrument(CtMethod ctMethod) throws CannotCompileException {
if (ctMethod.getName().equals("runChild")) {
StringBuilder sb = new StringBuilder(1024);
sb.append("org.junit.runners.model.FrameworkMethod __jvoid_frameworkMethod = (org.junit.runners.model.FrameworkMethod) $1;");
sb.append("org.junit.runner.notification.RunNotifier __jvoid_notifier = (org.junit.runner.notification.RunNotifier) $2;");
sb.append("java.lang.reflect.Method __jvoid_javaMethod = __jvoid_frameworkMethod.getMethod();\n");
sb.append("String featureId = (__jvoid_javaMethod.getDeclaringClass().getName() + \"#\" + __jvoid_javaMethod.getName());\n"); | sb.append(JVoidInstrumentationHelperHolder.helperGetterRef() + ".beginTest(featureId);\n"); |
jVoid/jVoid | src/test/java/io/jvoid/test/instrumentation/provider/app/AppHeuristicHelperTest.java | // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppHeuristicHelper.java
// public class AppHeuristicHelper {
//
// public static boolean isCGLIBProxy(CtClass ctClass) {
// String name = ctClass.getName();
// return name.contains("$$") || name.contains("CGLIB");
//
// }
// public static boolean isCGLIBProxy(CtMethod ctMethod) {
// String methodName = ctMethod.getLongName();
// return methodName.contains("$$") || methodName.contains("CGLIB");
// }
//
// public static boolean isGroovyCallSite(CtClass ctClass) {
// try {
// CtClass superclass = ctClass.getSuperclass();
// return superclass != null && superclass.getName().startsWith("org.codehaus.groovy.runtime.callsite");
// } catch (Exception e) {
// return false; // Being conservative here...
// }
// }
//
// public static boolean isJacocoField(CtField ctField) {
// String methodName = ctField.getName();
// return methodName.startsWith("$jacoco");
// }
//
// public static boolean isGeneratedField(CtField ctField) {
// String methodName = ctField.getName();
// return methodName.startsWith("$$");
// }
//
// public static boolean isJacocoMethod(CtMethod ctMethod) {
// String methodName = ctMethod.getLongName();
// return methodName.contains("$jacoco");
// }
//
// }
//
// Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java
// @UseModules({ JVoidModule.class })
// @RunWith(JVoidTestRunner.class)
// public abstract class AbstractJVoidTest {
//
// protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config";
//
// private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests?
//
// protected static final ClassPool classPool;
//
// @Inject
// protected MetadataDatabase metadataDatabase;
//
// @Inject
// protected JVoidInstrumentationHelper instrumentationHelper;
//
// @Inject
// protected ExecutionsRepository executionsRepository;
//
// @Inject
// protected JVoidExecutionContext jvoidExecutionContext;
//
// static {
// // See ClassPool JavaDoc for memory consumption issues
// ClassPool.doPruning = true;
// classPool = ClassPool.getDefault();
// }
//
// @Before
// public void setUp() throws Exception {
// // Make sure the database is initialized
// metadataDatabase.startup();
//
// // Makes sure that the database is clean, then restarts it to apply the migrations.
// // To be sure that each test runs in its own clean db environment.
// // TODO: Can this be more elegant?
// DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS");
// metadataDatabase.shutdown();
// metadataDatabase.startup();
//
// currentExecutionId.set(0L);
// }
//
// @After
// public void tearDown() {
// metadataDatabase.shutdown();
// JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper);
// }
//
// /*
// * Utility methods for current JExecution
// */
// protected Long getCurrentExecutionId() {
// return currentExecutionId.get();
// }
//
// protected synchronized JExecution setupCurrentExecution() {
// return setupCurrentExecution(null);
// }
//
// protected synchronized JExecution setupCurrentExecution(Long timestamp) {
// JExecution currentExecution = new JExecution();
// currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp);
// currentExecution = executionsRepository.add(currentExecution);
// currentExecutionId.set(currentExecution.getId());
// jvoidExecutionContext.setCurrentExecution(currentExecution);
// return currentExecution;
// }
// }
| import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.codehaus.groovy.runtime.callsite.CallSiteArray;
import org.junit.Test;
import io.jvoid.instrumentation.provider.app.AppHeuristicHelper;
import io.jvoid.test.AbstractJVoidTest;
import javassist.CtClass; | package io.jvoid.test.instrumentation.provider.app;
public class AppHeuristicHelperTest extends AbstractJVoidTest {
@Test
public void testHeuristicCglib() throws Exception {
CtClass cglibMock = classPool.get(ClassWithCglibMethods.class.getName()); | // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppHeuristicHelper.java
// public class AppHeuristicHelper {
//
// public static boolean isCGLIBProxy(CtClass ctClass) {
// String name = ctClass.getName();
// return name.contains("$$") || name.contains("CGLIB");
//
// }
// public static boolean isCGLIBProxy(CtMethod ctMethod) {
// String methodName = ctMethod.getLongName();
// return methodName.contains("$$") || methodName.contains("CGLIB");
// }
//
// public static boolean isGroovyCallSite(CtClass ctClass) {
// try {
// CtClass superclass = ctClass.getSuperclass();
// return superclass != null && superclass.getName().startsWith("org.codehaus.groovy.runtime.callsite");
// } catch (Exception e) {
// return false; // Being conservative here...
// }
// }
//
// public static boolean isJacocoField(CtField ctField) {
// String methodName = ctField.getName();
// return methodName.startsWith("$jacoco");
// }
//
// public static boolean isGeneratedField(CtField ctField) {
// String methodName = ctField.getName();
// return methodName.startsWith("$$");
// }
//
// public static boolean isJacocoMethod(CtMethod ctMethod) {
// String methodName = ctMethod.getLongName();
// return methodName.contains("$jacoco");
// }
//
// }
//
// Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java
// @UseModules({ JVoidModule.class })
// @RunWith(JVoidTestRunner.class)
// public abstract class AbstractJVoidTest {
//
// protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config";
//
// private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests?
//
// protected static final ClassPool classPool;
//
// @Inject
// protected MetadataDatabase metadataDatabase;
//
// @Inject
// protected JVoidInstrumentationHelper instrumentationHelper;
//
// @Inject
// protected ExecutionsRepository executionsRepository;
//
// @Inject
// protected JVoidExecutionContext jvoidExecutionContext;
//
// static {
// // See ClassPool JavaDoc for memory consumption issues
// ClassPool.doPruning = true;
// classPool = ClassPool.getDefault();
// }
//
// @Before
// public void setUp() throws Exception {
// // Make sure the database is initialized
// metadataDatabase.startup();
//
// // Makes sure that the database is clean, then restarts it to apply the migrations.
// // To be sure that each test runs in its own clean db environment.
// // TODO: Can this be more elegant?
// DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS");
// metadataDatabase.shutdown();
// metadataDatabase.startup();
//
// currentExecutionId.set(0L);
// }
//
// @After
// public void tearDown() {
// metadataDatabase.shutdown();
// JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper);
// }
//
// /*
// * Utility methods for current JExecution
// */
// protected Long getCurrentExecutionId() {
// return currentExecutionId.get();
// }
//
// protected synchronized JExecution setupCurrentExecution() {
// return setupCurrentExecution(null);
// }
//
// protected synchronized JExecution setupCurrentExecution(Long timestamp) {
// JExecution currentExecution = new JExecution();
// currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp);
// currentExecution = executionsRepository.add(currentExecution);
// currentExecutionId.set(currentExecution.getId());
// jvoidExecutionContext.setCurrentExecution(currentExecution);
// return currentExecution;
// }
// }
// Path: src/test/java/io/jvoid/test/instrumentation/provider/app/AppHeuristicHelperTest.java
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.codehaus.groovy.runtime.callsite.CallSiteArray;
import org.junit.Test;
import io.jvoid.instrumentation.provider.app.AppHeuristicHelper;
import io.jvoid.test.AbstractJVoidTest;
import javassist.CtClass;
package io.jvoid.test.instrumentation.provider.app;
public class AppHeuristicHelperTest extends AbstractJVoidTest {
@Test
public void testHeuristicCglib() throws Exception {
CtClass cglibMock = classPool.get(ClassWithCglibMethods.class.getName()); | assertTrue(AppHeuristicHelper.isCGLIBProxy(cglibMock.getDeclaredMethod("this$$ShouldBeCaught"))); |
jVoid/jVoid | src/test/java/io/jvoid/test/configuration/JVoidConfigurationServiceTest.java | // Path: src/main/java/io/jvoid/configuration/JVoidConfigurationService.java
// @Slf4j
// @Singleton
// public class JVoidConfigurationService {
//
// private JVoidPropertiesBasedConfigurationLoader loader;
//
// private JVoidConfigurationValidator validator;
//
// private JVoidConfiguration configuration;
//
// @Inject
// public JVoidConfigurationService(JVoidPropertiesBasedConfigurationLoader loader, JVoidConfigurationValidator validator) {
// this.loader = loader;
// this.validator = validator;
// }
//
// public synchronized void loadConfiguration(String parameterConfigurationPath) throws JVoidConfigurationException {
// if (configuration == null) {
// configuration = loader.load(parameterConfigurationPath);
// try {
// validator.validate(configuration);
// } catch (JVoidConfigurationException e) {
// log.error("Invalid configuration: " + e.getMessage(), e);
// throw e;
// }
// }
// }
//
// public JVoidConfiguration getConfiguration() throws JVoidConfigurationException {
// if (configuration == null) {
// loadConfiguration(null);
// }
// return configuration;
// }
//
// }
//
// Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java
// public class JVoidConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public JVoidConfigurationException(String message) {
// super(message);
// }
// public JVoidConfigurationException(String message, Throwable e) {
// super(message, e);
// }
//
// }
//
// Path: src/main/java/io/jvoid/guice/JVoidModule.java
// public class JVoidModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(JVoidConfiguration.class).toProvider(JVoidConfigurationProvider.class).in(Singleton.class);
// }
//
// }
//
// Path: src/test/java/io/jvoid/test/JVoidTestRunner.java
// @Slf4j
// public class JVoidTestRunner extends BlockJUnit4ClassRunner {
//
// private transient Injector injector;
//
// public JVoidTestRunner(Class<?> klass) throws InitializationError {
// super(klass);
// Class<?>[] moduleClasses = getModulesFor(klass);
// if (moduleClasses != null) {
// injector = createInjectorFor(moduleClasses);
// }
// }
//
// private Class<?>[] getModulesFor(final Class<?> klass) throws InitializationError {
// final UseModules annotation = klass.getAnnotation(UseModules.class);
// if (annotation == null) {
// log.info("No @UseModules annotation in unit test '{}'...", klass.getName());
// return null;
// }
// return annotation.value();
// }
//
// private Injector createInjectorFor(final Class<?>[] classes) throws InitializationError {
// final List<Module> modules = new ArrayList<>(classes.length);
// for (final Class<?> moduleClass : classes) {
// try {
// Module module = (Module) moduleClass.newInstance();
// modules.add(module);
// } catch (final ReflectiveOperationException exception) {
// throw new InitializationError(exception);
// }
// }
// return Guice.createInjector(modules);
// }
//
// @Override
// public final Object createTest() throws Exception {
// final Object theTest = super.createTest();
// injector.injectMembers(theTest);
// return theTest;
// }
// }
| import org.junit.Test;
import org.junit.runner.RunWith;
import com.google.inject.Inject;
import io.jvoid.configuration.JVoidConfigurationService;
import io.jvoid.exceptions.JVoidConfigurationException;
import io.jvoid.guice.JVoidModule;
import io.jvoid.test.JVoidTestRunner;
import io.jvoid.test.UseModules; | package io.jvoid.test.configuration;
@UseModules({ JVoidModule.class })
@RunWith(JVoidTestRunner.class)
public class JVoidConfigurationServiceTest {
@Inject | // Path: src/main/java/io/jvoid/configuration/JVoidConfigurationService.java
// @Slf4j
// @Singleton
// public class JVoidConfigurationService {
//
// private JVoidPropertiesBasedConfigurationLoader loader;
//
// private JVoidConfigurationValidator validator;
//
// private JVoidConfiguration configuration;
//
// @Inject
// public JVoidConfigurationService(JVoidPropertiesBasedConfigurationLoader loader, JVoidConfigurationValidator validator) {
// this.loader = loader;
// this.validator = validator;
// }
//
// public synchronized void loadConfiguration(String parameterConfigurationPath) throws JVoidConfigurationException {
// if (configuration == null) {
// configuration = loader.load(parameterConfigurationPath);
// try {
// validator.validate(configuration);
// } catch (JVoidConfigurationException e) {
// log.error("Invalid configuration: " + e.getMessage(), e);
// throw e;
// }
// }
// }
//
// public JVoidConfiguration getConfiguration() throws JVoidConfigurationException {
// if (configuration == null) {
// loadConfiguration(null);
// }
// return configuration;
// }
//
// }
//
// Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java
// public class JVoidConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public JVoidConfigurationException(String message) {
// super(message);
// }
// public JVoidConfigurationException(String message, Throwable e) {
// super(message, e);
// }
//
// }
//
// Path: src/main/java/io/jvoid/guice/JVoidModule.java
// public class JVoidModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(JVoidConfiguration.class).toProvider(JVoidConfigurationProvider.class).in(Singleton.class);
// }
//
// }
//
// Path: src/test/java/io/jvoid/test/JVoidTestRunner.java
// @Slf4j
// public class JVoidTestRunner extends BlockJUnit4ClassRunner {
//
// private transient Injector injector;
//
// public JVoidTestRunner(Class<?> klass) throws InitializationError {
// super(klass);
// Class<?>[] moduleClasses = getModulesFor(klass);
// if (moduleClasses != null) {
// injector = createInjectorFor(moduleClasses);
// }
// }
//
// private Class<?>[] getModulesFor(final Class<?> klass) throws InitializationError {
// final UseModules annotation = klass.getAnnotation(UseModules.class);
// if (annotation == null) {
// log.info("No @UseModules annotation in unit test '{}'...", klass.getName());
// return null;
// }
// return annotation.value();
// }
//
// private Injector createInjectorFor(final Class<?>[] classes) throws InitializationError {
// final List<Module> modules = new ArrayList<>(classes.length);
// for (final Class<?> moduleClass : classes) {
// try {
// Module module = (Module) moduleClass.newInstance();
// modules.add(module);
// } catch (final ReflectiveOperationException exception) {
// throw new InitializationError(exception);
// }
// }
// return Guice.createInjector(modules);
// }
//
// @Override
// public final Object createTest() throws Exception {
// final Object theTest = super.createTest();
// injector.injectMembers(theTest);
// return theTest;
// }
// }
// Path: src/test/java/io/jvoid/test/configuration/JVoidConfigurationServiceTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import com.google.inject.Inject;
import io.jvoid.configuration.JVoidConfigurationService;
import io.jvoid.exceptions.JVoidConfigurationException;
import io.jvoid.guice.JVoidModule;
import io.jvoid.test.JVoidTestRunner;
import io.jvoid.test.UseModules;
package io.jvoid.test.configuration;
@UseModules({ JVoidModule.class })
@RunWith(JVoidTestRunner.class)
public class JVoidConfigurationServiceTest {
@Inject | JVoidConfigurationService confService; |
jVoid/jVoid | src/test/java/io/jvoid/test/configuration/JVoidConfigurationServiceTest.java | // Path: src/main/java/io/jvoid/configuration/JVoidConfigurationService.java
// @Slf4j
// @Singleton
// public class JVoidConfigurationService {
//
// private JVoidPropertiesBasedConfigurationLoader loader;
//
// private JVoidConfigurationValidator validator;
//
// private JVoidConfiguration configuration;
//
// @Inject
// public JVoidConfigurationService(JVoidPropertiesBasedConfigurationLoader loader, JVoidConfigurationValidator validator) {
// this.loader = loader;
// this.validator = validator;
// }
//
// public synchronized void loadConfiguration(String parameterConfigurationPath) throws JVoidConfigurationException {
// if (configuration == null) {
// configuration = loader.load(parameterConfigurationPath);
// try {
// validator.validate(configuration);
// } catch (JVoidConfigurationException e) {
// log.error("Invalid configuration: " + e.getMessage(), e);
// throw e;
// }
// }
// }
//
// public JVoidConfiguration getConfiguration() throws JVoidConfigurationException {
// if (configuration == null) {
// loadConfiguration(null);
// }
// return configuration;
// }
//
// }
//
// Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java
// public class JVoidConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public JVoidConfigurationException(String message) {
// super(message);
// }
// public JVoidConfigurationException(String message, Throwable e) {
// super(message, e);
// }
//
// }
//
// Path: src/main/java/io/jvoid/guice/JVoidModule.java
// public class JVoidModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(JVoidConfiguration.class).toProvider(JVoidConfigurationProvider.class).in(Singleton.class);
// }
//
// }
//
// Path: src/test/java/io/jvoid/test/JVoidTestRunner.java
// @Slf4j
// public class JVoidTestRunner extends BlockJUnit4ClassRunner {
//
// private transient Injector injector;
//
// public JVoidTestRunner(Class<?> klass) throws InitializationError {
// super(klass);
// Class<?>[] moduleClasses = getModulesFor(klass);
// if (moduleClasses != null) {
// injector = createInjectorFor(moduleClasses);
// }
// }
//
// private Class<?>[] getModulesFor(final Class<?> klass) throws InitializationError {
// final UseModules annotation = klass.getAnnotation(UseModules.class);
// if (annotation == null) {
// log.info("No @UseModules annotation in unit test '{}'...", klass.getName());
// return null;
// }
// return annotation.value();
// }
//
// private Injector createInjectorFor(final Class<?>[] classes) throws InitializationError {
// final List<Module> modules = new ArrayList<>(classes.length);
// for (final Class<?> moduleClass : classes) {
// try {
// Module module = (Module) moduleClass.newInstance();
// modules.add(module);
// } catch (final ReflectiveOperationException exception) {
// throw new InitializationError(exception);
// }
// }
// return Guice.createInjector(modules);
// }
//
// @Override
// public final Object createTest() throws Exception {
// final Object theTest = super.createTest();
// injector.injectMembers(theTest);
// return theTest;
// }
// }
| import org.junit.Test;
import org.junit.runner.RunWith;
import com.google.inject.Inject;
import io.jvoid.configuration.JVoidConfigurationService;
import io.jvoid.exceptions.JVoidConfigurationException;
import io.jvoid.guice.JVoidModule;
import io.jvoid.test.JVoidTestRunner;
import io.jvoid.test.UseModules; | package io.jvoid.test.configuration;
@UseModules({ JVoidModule.class })
@RunWith(JVoidTestRunner.class)
public class JVoidConfigurationServiceTest {
@Inject
JVoidConfigurationService confService;
| // Path: src/main/java/io/jvoid/configuration/JVoidConfigurationService.java
// @Slf4j
// @Singleton
// public class JVoidConfigurationService {
//
// private JVoidPropertiesBasedConfigurationLoader loader;
//
// private JVoidConfigurationValidator validator;
//
// private JVoidConfiguration configuration;
//
// @Inject
// public JVoidConfigurationService(JVoidPropertiesBasedConfigurationLoader loader, JVoidConfigurationValidator validator) {
// this.loader = loader;
// this.validator = validator;
// }
//
// public synchronized void loadConfiguration(String parameterConfigurationPath) throws JVoidConfigurationException {
// if (configuration == null) {
// configuration = loader.load(parameterConfigurationPath);
// try {
// validator.validate(configuration);
// } catch (JVoidConfigurationException e) {
// log.error("Invalid configuration: " + e.getMessage(), e);
// throw e;
// }
// }
// }
//
// public JVoidConfiguration getConfiguration() throws JVoidConfigurationException {
// if (configuration == null) {
// loadConfiguration(null);
// }
// return configuration;
// }
//
// }
//
// Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java
// public class JVoidConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public JVoidConfigurationException(String message) {
// super(message);
// }
// public JVoidConfigurationException(String message, Throwable e) {
// super(message, e);
// }
//
// }
//
// Path: src/main/java/io/jvoid/guice/JVoidModule.java
// public class JVoidModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(JVoidConfiguration.class).toProvider(JVoidConfigurationProvider.class).in(Singleton.class);
// }
//
// }
//
// Path: src/test/java/io/jvoid/test/JVoidTestRunner.java
// @Slf4j
// public class JVoidTestRunner extends BlockJUnit4ClassRunner {
//
// private transient Injector injector;
//
// public JVoidTestRunner(Class<?> klass) throws InitializationError {
// super(klass);
// Class<?>[] moduleClasses = getModulesFor(klass);
// if (moduleClasses != null) {
// injector = createInjectorFor(moduleClasses);
// }
// }
//
// private Class<?>[] getModulesFor(final Class<?> klass) throws InitializationError {
// final UseModules annotation = klass.getAnnotation(UseModules.class);
// if (annotation == null) {
// log.info("No @UseModules annotation in unit test '{}'...", klass.getName());
// return null;
// }
// return annotation.value();
// }
//
// private Injector createInjectorFor(final Class<?>[] classes) throws InitializationError {
// final List<Module> modules = new ArrayList<>(classes.length);
// for (final Class<?> moduleClass : classes) {
// try {
// Module module = (Module) moduleClass.newInstance();
// modules.add(module);
// } catch (final ReflectiveOperationException exception) {
// throw new InitializationError(exception);
// }
// }
// return Guice.createInjector(modules);
// }
//
// @Override
// public final Object createTest() throws Exception {
// final Object theTest = super.createTest();
// injector.injectMembers(theTest);
// return theTest;
// }
// }
// Path: src/test/java/io/jvoid/test/configuration/JVoidConfigurationServiceTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import com.google.inject.Inject;
import io.jvoid.configuration.JVoidConfigurationService;
import io.jvoid.exceptions.JVoidConfigurationException;
import io.jvoid.guice.JVoidModule;
import io.jvoid.test.JVoidTestRunner;
import io.jvoid.test.UseModules;
package io.jvoid.test.configuration;
@UseModules({ JVoidModule.class })
@RunWith(JVoidTestRunner.class)
public class JVoidConfigurationServiceTest {
@Inject
JVoidConfigurationService confService;
| @Test(expected = JVoidConfigurationException.class) |
jVoid/jVoid | src/main/java/io/jvoid/guice/JVoidConfigurationProvider.java | // Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java
// public interface JVoidConfiguration {
//
// String dbUrl();
//
// String dbUsername();
//
// String dbPassword();
//
// String basePackage();
//
// String excludes();
//
// String includes();
//
// Boolean heuristicExcludeCglib();
//
// Boolean heuristicExcludeJacoco();
//
// Boolean heuristicExcludeGroovyCallSite();
//
// }
//
// Path: src/main/java/io/jvoid/configuration/JVoidConfigurationService.java
// @Slf4j
// @Singleton
// public class JVoidConfigurationService {
//
// private JVoidPropertiesBasedConfigurationLoader loader;
//
// private JVoidConfigurationValidator validator;
//
// private JVoidConfiguration configuration;
//
// @Inject
// public JVoidConfigurationService(JVoidPropertiesBasedConfigurationLoader loader, JVoidConfigurationValidator validator) {
// this.loader = loader;
// this.validator = validator;
// }
//
// public synchronized void loadConfiguration(String parameterConfigurationPath) throws JVoidConfigurationException {
// if (configuration == null) {
// configuration = loader.load(parameterConfigurationPath);
// try {
// validator.validate(configuration);
// } catch (JVoidConfigurationException e) {
// log.error("Invalid configuration: " + e.getMessage(), e);
// throw e;
// }
// }
// }
//
// public JVoidConfiguration getConfiguration() throws JVoidConfigurationException {
// if (configuration == null) {
// loadConfiguration(null);
// }
// return configuration;
// }
//
// }
//
// Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java
// public class JVoidConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public JVoidConfigurationException(String message) {
// super(message);
// }
// public JVoidConfigurationException(String message, Throwable e) {
// super(message, e);
// }
//
// }
| import com.google.inject.Inject;
import com.google.inject.Provider;
import io.jvoid.configuration.JVoidConfiguration;
import io.jvoid.configuration.JVoidConfigurationService;
import io.jvoid.exceptions.JVoidConfigurationException; | package io.jvoid.guice;
/**
* Guice provider for the current @{code JVoidConfiguration}
*
*/
public class JVoidConfigurationProvider implements Provider<JVoidConfiguration> {
private JVoidConfigurationService configurationService;
@Inject
public JVoidConfigurationProvider(JVoidConfigurationService configurationService) {
this.configurationService = configurationService;
}
@Override
public JVoidConfiguration get() {
try {
return configurationService.getConfiguration(); | // Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java
// public interface JVoidConfiguration {
//
// String dbUrl();
//
// String dbUsername();
//
// String dbPassword();
//
// String basePackage();
//
// String excludes();
//
// String includes();
//
// Boolean heuristicExcludeCglib();
//
// Boolean heuristicExcludeJacoco();
//
// Boolean heuristicExcludeGroovyCallSite();
//
// }
//
// Path: src/main/java/io/jvoid/configuration/JVoidConfigurationService.java
// @Slf4j
// @Singleton
// public class JVoidConfigurationService {
//
// private JVoidPropertiesBasedConfigurationLoader loader;
//
// private JVoidConfigurationValidator validator;
//
// private JVoidConfiguration configuration;
//
// @Inject
// public JVoidConfigurationService(JVoidPropertiesBasedConfigurationLoader loader, JVoidConfigurationValidator validator) {
// this.loader = loader;
// this.validator = validator;
// }
//
// public synchronized void loadConfiguration(String parameterConfigurationPath) throws JVoidConfigurationException {
// if (configuration == null) {
// configuration = loader.load(parameterConfigurationPath);
// try {
// validator.validate(configuration);
// } catch (JVoidConfigurationException e) {
// log.error("Invalid configuration: " + e.getMessage(), e);
// throw e;
// }
// }
// }
//
// public JVoidConfiguration getConfiguration() throws JVoidConfigurationException {
// if (configuration == null) {
// loadConfiguration(null);
// }
// return configuration;
// }
//
// }
//
// Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java
// public class JVoidConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public JVoidConfigurationException(String message) {
// super(message);
// }
// public JVoidConfigurationException(String message, Throwable e) {
// super(message, e);
// }
//
// }
// Path: src/main/java/io/jvoid/guice/JVoidConfigurationProvider.java
import com.google.inject.Inject;
import com.google.inject.Provider;
import io.jvoid.configuration.JVoidConfiguration;
import io.jvoid.configuration.JVoidConfigurationService;
import io.jvoid.exceptions.JVoidConfigurationException;
package io.jvoid.guice;
/**
* Guice provider for the current @{code JVoidConfiguration}
*
*/
public class JVoidConfigurationProvider implements Provider<JVoidConfiguration> {
private JVoidConfigurationService configurationService;
@Inject
public JVoidConfigurationProvider(JVoidConfigurationService configurationService) {
this.configurationService = configurationService;
}
@Override
public JVoidConfiguration get() {
try {
return configurationService.getConfiguration(); | } catch (JVoidConfigurationException e) { |
jVoid/jVoid | src/main/java/io/jvoid/metadata/repositories/MethodsRepository.java | // Path: src/main/java/io/jvoid/database/MetadataDatabase.java
// @Singleton
// public class MetadataDatabase {
//
// private JVoidConfiguration configuration;
//
// private HikariDataSource ds;
//
// /**
// *
// * @param configuration
// */
// @Inject
// public MetadataDatabase(JVoidConfiguration configuration) {
// this.configuration = configuration;
// }
//
// /**
// *
// */
// @Inject
// public void startup() {
// if (ds != null && !ds.isClosed()) {
// return;
// }
//
// HikariConfig config = new HikariConfig();
// config.setJdbcUrl(configuration.dbUrl());
// config.setUsername(configuration.dbUsername());
// config.setPassword(configuration.dbPassword());
// config.addDataSourceProperty("cachePrepStmts", "true");
// config.addDataSourceProperty("prepStmtCacheSize", "250");
// config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
//
// ds = new HikariDataSource(config);
//
// initializeDatabase();
// }
//
// /**
// *
// */
// public void shutdown() {
// if (ds != null) {
// ds.close();
// ds = null;
// }
// }
//
// /**
// *
// */
// private void initializeDatabase() {
// Flyway flyway = new Flyway();
// flyway.setDataSource(ds);
// flyway.migrate();
// }
//
// /**
// *
// * @return A connection from the pool
// */
// public Connection getConnection() {
// try {
// return ds.getConnection();
// } catch (SQLException e) {
// throw new JVoidDataAccessException(e);
// }
// }
// }
//
// Path: src/main/java/io/jvoid/metadata/model/JMethod.java
// @Data
// public class JMethod implements JEntity<Long>, ChecksumAware {
//
// private Long id;
// private Long executionId;
// private String identifier;
// private String checksum;
//
// }
| import java.util.Map;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanMapHandler;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.jvoid.database.MetadataDatabase;
import io.jvoid.metadata.model.JMethod; | package io.jvoid.metadata.repositories;
/**
*
*/
@Singleton
public class MethodsRepository extends AbstractRepository<JMethod, Long>
implements TestRelatedEntityRepository<JMethod, Long> {
private ResultSetHandler<JMethod> objectHandler = new BeanHandler<>(JMethod.class);
private ResultSetHandler<Map<String, JMethod>> identifierMapHandler = new BeanMapHandler<>(
JMethod.class, "identifier");
@Inject | // Path: src/main/java/io/jvoid/database/MetadataDatabase.java
// @Singleton
// public class MetadataDatabase {
//
// private JVoidConfiguration configuration;
//
// private HikariDataSource ds;
//
// /**
// *
// * @param configuration
// */
// @Inject
// public MetadataDatabase(JVoidConfiguration configuration) {
// this.configuration = configuration;
// }
//
// /**
// *
// */
// @Inject
// public void startup() {
// if (ds != null && !ds.isClosed()) {
// return;
// }
//
// HikariConfig config = new HikariConfig();
// config.setJdbcUrl(configuration.dbUrl());
// config.setUsername(configuration.dbUsername());
// config.setPassword(configuration.dbPassword());
// config.addDataSourceProperty("cachePrepStmts", "true");
// config.addDataSourceProperty("prepStmtCacheSize", "250");
// config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
//
// ds = new HikariDataSource(config);
//
// initializeDatabase();
// }
//
// /**
// *
// */
// public void shutdown() {
// if (ds != null) {
// ds.close();
// ds = null;
// }
// }
//
// /**
// *
// */
// private void initializeDatabase() {
// Flyway flyway = new Flyway();
// flyway.setDataSource(ds);
// flyway.migrate();
// }
//
// /**
// *
// * @return A connection from the pool
// */
// public Connection getConnection() {
// try {
// return ds.getConnection();
// } catch (SQLException e) {
// throw new JVoidDataAccessException(e);
// }
// }
// }
//
// Path: src/main/java/io/jvoid/metadata/model/JMethod.java
// @Data
// public class JMethod implements JEntity<Long>, ChecksumAware {
//
// private Long id;
// private Long executionId;
// private String identifier;
// private String checksum;
//
// }
// Path: src/main/java/io/jvoid/metadata/repositories/MethodsRepository.java
import java.util.Map;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanMapHandler;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.jvoid.database.MetadataDatabase;
import io.jvoid.metadata.model.JMethod;
package io.jvoid.metadata.repositories;
/**
*
*/
@Singleton
public class MethodsRepository extends AbstractRepository<JMethod, Long>
implements TestRelatedEntityRepository<JMethod, Long> {
private ResultSetHandler<JMethod> objectHandler = new BeanHandler<>(JMethod.class);
private ResultSetHandler<Map<String, JMethod>> identifierMapHandler = new BeanMapHandler<>(
JMethod.class, "identifier");
@Inject | public MethodsRepository(MetadataDatabase database) { |
jVoid/jVoid | src/test/java/io/jvoid/test/instrumentation/provider/spock/SpockInstrumentationProviderTest.java | // Path: src/main/java/io/jvoid/instrumentation/provider/spock/RunFeatureMethodInstrumenter.java
// public class RunFeatureMethodInstrumenter implements MethodInstrumenter {
//
// @Override
// public void instrument(CtMethod method) throws CannotCompileException {
// // Right now is only called for the runFeature method
// StringBuilder sb = new StringBuilder(1024);
// // Get the String identifier of the spec
// sb.append("String featureId = currentFeature.getFeatureMethod().getDescription().toString();\n");
// sb.append(JVoidInstrumentationHelperHolder.helperGetterRef() + ".beginTest(featureId);\n");
// sb.append("if (!" + JVoidInstrumentationHelperHolder.helperGetterRef() + ".wasTestRelatedCodeModified(featureId)) {\n");
// sb.append(" supervisor.featureSkipped(currentFeature); return;\n");
// sb.append("}\n");
// method.insertBefore(sb.toString());
// }
//
// @Override
// public boolean shouldInstrument(CtMethod ctMethod) {
// return true;
// }
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/spock/SpockInstrumentationProvider.java
// public class SpockInstrumentationProvider implements InstrumentationProvider {
//
// private MethodInstrumenter runFeatureMethodInstrumenter;
//
// @Inject
// public SpockInstrumentationProvider(RunFeatureMethodInstrumenter runFeatureMethodInstrumenter) {
// this.runFeatureMethodInstrumenter = runFeatureMethodInstrumenter;
// }
//
// @Override
// public boolean matches(CtClass ctClass) {
// return ctClass.getName().contains("org.spockframework.runtime.BaseSpecRunner");
// }
//
// @Override
// public List<ClassHandler> getClassHandlers(CtClass ctClass) {
// return Collections.emptyList();
// }
//
// @Override
// public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) {
// if (ctMethod.getName().equals("runFeature")) {
// return Collections.singletonList(runFeatureMethodInstrumenter);
// }
// return Collections.emptyList();
// }
//
// }
//
// Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java
// @UseModules({ JVoidModule.class })
// @RunWith(JVoidTestRunner.class)
// public abstract class AbstractJVoidTest {
//
// protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config";
//
// private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests?
//
// protected static final ClassPool classPool;
//
// @Inject
// protected MetadataDatabase metadataDatabase;
//
// @Inject
// protected JVoidInstrumentationHelper instrumentationHelper;
//
// @Inject
// protected ExecutionsRepository executionsRepository;
//
// @Inject
// protected JVoidExecutionContext jvoidExecutionContext;
//
// static {
// // See ClassPool JavaDoc for memory consumption issues
// ClassPool.doPruning = true;
// classPool = ClassPool.getDefault();
// }
//
// @Before
// public void setUp() throws Exception {
// // Make sure the database is initialized
// metadataDatabase.startup();
//
// // Makes sure that the database is clean, then restarts it to apply the migrations.
// // To be sure that each test runs in its own clean db environment.
// // TODO: Can this be more elegant?
// DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS");
// metadataDatabase.shutdown();
// metadataDatabase.startup();
//
// currentExecutionId.set(0L);
// }
//
// @After
// public void tearDown() {
// metadataDatabase.shutdown();
// JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper);
// }
//
// /*
// * Utility methods for current JExecution
// */
// protected Long getCurrentExecutionId() {
// return currentExecutionId.get();
// }
//
// protected synchronized JExecution setupCurrentExecution() {
// return setupCurrentExecution(null);
// }
//
// protected synchronized JExecution setupCurrentExecution(Long timestamp) {
// JExecution currentExecution = new JExecution();
// currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp);
// currentExecution = executionsRepository.add(currentExecution);
// currentExecutionId.set(currentExecution.getId());
// jvoidExecutionContext.setCurrentExecution(currentExecution);
// return currentExecution;
// }
// }
| import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.inject.Inject;
import io.jvoid.instrumentation.provider.spock.RunFeatureMethodInstrumenter;
import io.jvoid.instrumentation.provider.spock.SpockInstrumentationProvider;
import io.jvoid.test.AbstractJVoidTest;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException; | package io.jvoid.test.instrumentation.provider.spock;
public class SpockInstrumentationProviderTest extends AbstractJVoidTest {
@Inject | // Path: src/main/java/io/jvoid/instrumentation/provider/spock/RunFeatureMethodInstrumenter.java
// public class RunFeatureMethodInstrumenter implements MethodInstrumenter {
//
// @Override
// public void instrument(CtMethod method) throws CannotCompileException {
// // Right now is only called for the runFeature method
// StringBuilder sb = new StringBuilder(1024);
// // Get the String identifier of the spec
// sb.append("String featureId = currentFeature.getFeatureMethod().getDescription().toString();\n");
// sb.append(JVoidInstrumentationHelperHolder.helperGetterRef() + ".beginTest(featureId);\n");
// sb.append("if (!" + JVoidInstrumentationHelperHolder.helperGetterRef() + ".wasTestRelatedCodeModified(featureId)) {\n");
// sb.append(" supervisor.featureSkipped(currentFeature); return;\n");
// sb.append("}\n");
// method.insertBefore(sb.toString());
// }
//
// @Override
// public boolean shouldInstrument(CtMethod ctMethod) {
// return true;
// }
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/spock/SpockInstrumentationProvider.java
// public class SpockInstrumentationProvider implements InstrumentationProvider {
//
// private MethodInstrumenter runFeatureMethodInstrumenter;
//
// @Inject
// public SpockInstrumentationProvider(RunFeatureMethodInstrumenter runFeatureMethodInstrumenter) {
// this.runFeatureMethodInstrumenter = runFeatureMethodInstrumenter;
// }
//
// @Override
// public boolean matches(CtClass ctClass) {
// return ctClass.getName().contains("org.spockframework.runtime.BaseSpecRunner");
// }
//
// @Override
// public List<ClassHandler> getClassHandlers(CtClass ctClass) {
// return Collections.emptyList();
// }
//
// @Override
// public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) {
// if (ctMethod.getName().equals("runFeature")) {
// return Collections.singletonList(runFeatureMethodInstrumenter);
// }
// return Collections.emptyList();
// }
//
// }
//
// Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java
// @UseModules({ JVoidModule.class })
// @RunWith(JVoidTestRunner.class)
// public abstract class AbstractJVoidTest {
//
// protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config";
//
// private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests?
//
// protected static final ClassPool classPool;
//
// @Inject
// protected MetadataDatabase metadataDatabase;
//
// @Inject
// protected JVoidInstrumentationHelper instrumentationHelper;
//
// @Inject
// protected ExecutionsRepository executionsRepository;
//
// @Inject
// protected JVoidExecutionContext jvoidExecutionContext;
//
// static {
// // See ClassPool JavaDoc for memory consumption issues
// ClassPool.doPruning = true;
// classPool = ClassPool.getDefault();
// }
//
// @Before
// public void setUp() throws Exception {
// // Make sure the database is initialized
// metadataDatabase.startup();
//
// // Makes sure that the database is clean, then restarts it to apply the migrations.
// // To be sure that each test runs in its own clean db environment.
// // TODO: Can this be more elegant?
// DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS");
// metadataDatabase.shutdown();
// metadataDatabase.startup();
//
// currentExecutionId.set(0L);
// }
//
// @After
// public void tearDown() {
// metadataDatabase.shutdown();
// JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper);
// }
//
// /*
// * Utility methods for current JExecution
// */
// protected Long getCurrentExecutionId() {
// return currentExecutionId.get();
// }
//
// protected synchronized JExecution setupCurrentExecution() {
// return setupCurrentExecution(null);
// }
//
// protected synchronized JExecution setupCurrentExecution(Long timestamp) {
// JExecution currentExecution = new JExecution();
// currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp);
// currentExecution = executionsRepository.add(currentExecution);
// currentExecutionId.set(currentExecution.getId());
// jvoidExecutionContext.setCurrentExecution(currentExecution);
// return currentExecution;
// }
// }
// Path: src/test/java/io/jvoid/test/instrumentation/provider/spock/SpockInstrumentationProviderTest.java
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.inject.Inject;
import io.jvoid.instrumentation.provider.spock.RunFeatureMethodInstrumenter;
import io.jvoid.instrumentation.provider.spock.SpockInstrumentationProvider;
import io.jvoid.test.AbstractJVoidTest;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
package io.jvoid.test.instrumentation.provider.spock;
public class SpockInstrumentationProviderTest extends AbstractJVoidTest {
@Inject | private RunFeatureMethodInstrumenter runFeatureMethodInstrumenter; |
jVoid/jVoid | src/test/java/io/jvoid/test/instrumentation/provider/spock/SpockInstrumentationProviderTest.java | // Path: src/main/java/io/jvoid/instrumentation/provider/spock/RunFeatureMethodInstrumenter.java
// public class RunFeatureMethodInstrumenter implements MethodInstrumenter {
//
// @Override
// public void instrument(CtMethod method) throws CannotCompileException {
// // Right now is only called for the runFeature method
// StringBuilder sb = new StringBuilder(1024);
// // Get the String identifier of the spec
// sb.append("String featureId = currentFeature.getFeatureMethod().getDescription().toString();\n");
// sb.append(JVoidInstrumentationHelperHolder.helperGetterRef() + ".beginTest(featureId);\n");
// sb.append("if (!" + JVoidInstrumentationHelperHolder.helperGetterRef() + ".wasTestRelatedCodeModified(featureId)) {\n");
// sb.append(" supervisor.featureSkipped(currentFeature); return;\n");
// sb.append("}\n");
// method.insertBefore(sb.toString());
// }
//
// @Override
// public boolean shouldInstrument(CtMethod ctMethod) {
// return true;
// }
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/spock/SpockInstrumentationProvider.java
// public class SpockInstrumentationProvider implements InstrumentationProvider {
//
// private MethodInstrumenter runFeatureMethodInstrumenter;
//
// @Inject
// public SpockInstrumentationProvider(RunFeatureMethodInstrumenter runFeatureMethodInstrumenter) {
// this.runFeatureMethodInstrumenter = runFeatureMethodInstrumenter;
// }
//
// @Override
// public boolean matches(CtClass ctClass) {
// return ctClass.getName().contains("org.spockframework.runtime.BaseSpecRunner");
// }
//
// @Override
// public List<ClassHandler> getClassHandlers(CtClass ctClass) {
// return Collections.emptyList();
// }
//
// @Override
// public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) {
// if (ctMethod.getName().equals("runFeature")) {
// return Collections.singletonList(runFeatureMethodInstrumenter);
// }
// return Collections.emptyList();
// }
//
// }
//
// Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java
// @UseModules({ JVoidModule.class })
// @RunWith(JVoidTestRunner.class)
// public abstract class AbstractJVoidTest {
//
// protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config";
//
// private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests?
//
// protected static final ClassPool classPool;
//
// @Inject
// protected MetadataDatabase metadataDatabase;
//
// @Inject
// protected JVoidInstrumentationHelper instrumentationHelper;
//
// @Inject
// protected ExecutionsRepository executionsRepository;
//
// @Inject
// protected JVoidExecutionContext jvoidExecutionContext;
//
// static {
// // See ClassPool JavaDoc for memory consumption issues
// ClassPool.doPruning = true;
// classPool = ClassPool.getDefault();
// }
//
// @Before
// public void setUp() throws Exception {
// // Make sure the database is initialized
// metadataDatabase.startup();
//
// // Makes sure that the database is clean, then restarts it to apply the migrations.
// // To be sure that each test runs in its own clean db environment.
// // TODO: Can this be more elegant?
// DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS");
// metadataDatabase.shutdown();
// metadataDatabase.startup();
//
// currentExecutionId.set(0L);
// }
//
// @After
// public void tearDown() {
// metadataDatabase.shutdown();
// JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper);
// }
//
// /*
// * Utility methods for current JExecution
// */
// protected Long getCurrentExecutionId() {
// return currentExecutionId.get();
// }
//
// protected synchronized JExecution setupCurrentExecution() {
// return setupCurrentExecution(null);
// }
//
// protected synchronized JExecution setupCurrentExecution(Long timestamp) {
// JExecution currentExecution = new JExecution();
// currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp);
// currentExecution = executionsRepository.add(currentExecution);
// currentExecutionId.set(currentExecution.getId());
// jvoidExecutionContext.setCurrentExecution(currentExecution);
// return currentExecution;
// }
// }
| import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.inject.Inject;
import io.jvoid.instrumentation.provider.spock.RunFeatureMethodInstrumenter;
import io.jvoid.instrumentation.provider.spock.SpockInstrumentationProvider;
import io.jvoid.test.AbstractJVoidTest;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException; | package io.jvoid.test.instrumentation.provider.spock;
public class SpockInstrumentationProviderTest extends AbstractJVoidTest {
@Inject
private RunFeatureMethodInstrumenter runFeatureMethodInstrumenter;
| // Path: src/main/java/io/jvoid/instrumentation/provider/spock/RunFeatureMethodInstrumenter.java
// public class RunFeatureMethodInstrumenter implements MethodInstrumenter {
//
// @Override
// public void instrument(CtMethod method) throws CannotCompileException {
// // Right now is only called for the runFeature method
// StringBuilder sb = new StringBuilder(1024);
// // Get the String identifier of the spec
// sb.append("String featureId = currentFeature.getFeatureMethod().getDescription().toString();\n");
// sb.append(JVoidInstrumentationHelperHolder.helperGetterRef() + ".beginTest(featureId);\n");
// sb.append("if (!" + JVoidInstrumentationHelperHolder.helperGetterRef() + ".wasTestRelatedCodeModified(featureId)) {\n");
// sb.append(" supervisor.featureSkipped(currentFeature); return;\n");
// sb.append("}\n");
// method.insertBefore(sb.toString());
// }
//
// @Override
// public boolean shouldInstrument(CtMethod ctMethod) {
// return true;
// }
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/spock/SpockInstrumentationProvider.java
// public class SpockInstrumentationProvider implements InstrumentationProvider {
//
// private MethodInstrumenter runFeatureMethodInstrumenter;
//
// @Inject
// public SpockInstrumentationProvider(RunFeatureMethodInstrumenter runFeatureMethodInstrumenter) {
// this.runFeatureMethodInstrumenter = runFeatureMethodInstrumenter;
// }
//
// @Override
// public boolean matches(CtClass ctClass) {
// return ctClass.getName().contains("org.spockframework.runtime.BaseSpecRunner");
// }
//
// @Override
// public List<ClassHandler> getClassHandlers(CtClass ctClass) {
// return Collections.emptyList();
// }
//
// @Override
// public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) {
// if (ctMethod.getName().equals("runFeature")) {
// return Collections.singletonList(runFeatureMethodInstrumenter);
// }
// return Collections.emptyList();
// }
//
// }
//
// Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java
// @UseModules({ JVoidModule.class })
// @RunWith(JVoidTestRunner.class)
// public abstract class AbstractJVoidTest {
//
// protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config";
//
// private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests?
//
// protected static final ClassPool classPool;
//
// @Inject
// protected MetadataDatabase metadataDatabase;
//
// @Inject
// protected JVoidInstrumentationHelper instrumentationHelper;
//
// @Inject
// protected ExecutionsRepository executionsRepository;
//
// @Inject
// protected JVoidExecutionContext jvoidExecutionContext;
//
// static {
// // See ClassPool JavaDoc for memory consumption issues
// ClassPool.doPruning = true;
// classPool = ClassPool.getDefault();
// }
//
// @Before
// public void setUp() throws Exception {
// // Make sure the database is initialized
// metadataDatabase.startup();
//
// // Makes sure that the database is clean, then restarts it to apply the migrations.
// // To be sure that each test runs in its own clean db environment.
// // TODO: Can this be more elegant?
// DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS");
// metadataDatabase.shutdown();
// metadataDatabase.startup();
//
// currentExecutionId.set(0L);
// }
//
// @After
// public void tearDown() {
// metadataDatabase.shutdown();
// JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper);
// }
//
// /*
// * Utility methods for current JExecution
// */
// protected Long getCurrentExecutionId() {
// return currentExecutionId.get();
// }
//
// protected synchronized JExecution setupCurrentExecution() {
// return setupCurrentExecution(null);
// }
//
// protected synchronized JExecution setupCurrentExecution(Long timestamp) {
// JExecution currentExecution = new JExecution();
// currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp);
// currentExecution = executionsRepository.add(currentExecution);
// currentExecutionId.set(currentExecution.getId());
// jvoidExecutionContext.setCurrentExecution(currentExecution);
// return currentExecution;
// }
// }
// Path: src/test/java/io/jvoid/test/instrumentation/provider/spock/SpockInstrumentationProviderTest.java
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.inject.Inject;
import io.jvoid.instrumentation.provider.spock.RunFeatureMethodInstrumenter;
import io.jvoid.instrumentation.provider.spock.SpockInstrumentationProvider;
import io.jvoid.test.AbstractJVoidTest;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
package io.jvoid.test.instrumentation.provider.spock;
public class SpockInstrumentationProviderTest extends AbstractJVoidTest {
@Inject
private RunFeatureMethodInstrumenter runFeatureMethodInstrumenter;
| private SpockInstrumentationProvider spockProvider; |
jVoid/jVoid | src/main/java/io/jvoid/instrumentation/provider/spock/SpockInstrumentationProvider.java | // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java
// public interface ClassHandler {
//
// void handleClass(CtClass ctClass) throws CannotCompileException;
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java
// public interface InstrumentationProvider {
//
// boolean matches(CtClass ctClass);
//
// List<ClassHandler> getClassHandlers(CtClass ctClass);
//
// List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod);
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java
// public interface MethodInstrumenter {
//
// void instrument(CtMethod ctMethod) throws CannotCompileException;
//
// boolean shouldInstrument(CtMethod ctMethod);
//
// }
| import java.util.Collections;
import java.util.List;
import com.google.inject.Inject;
import io.jvoid.instrumentation.provider.api.ClassHandler;
import io.jvoid.instrumentation.provider.api.InstrumentationProvider;
import io.jvoid.instrumentation.provider.api.MethodInstrumenter;
import javassist.CtClass;
import javassist.CtMethod; | package io.jvoid.instrumentation.provider.spock;
/**
* JVoid instrumentation provider for Spock Framework. It indirectly uses also
* the JUnit instrumentation to realize the full JVoid functionalities.
*
*/
public class SpockInstrumentationProvider implements InstrumentationProvider {
private MethodInstrumenter runFeatureMethodInstrumenter;
@Inject
public SpockInstrumentationProvider(RunFeatureMethodInstrumenter runFeatureMethodInstrumenter) {
this.runFeatureMethodInstrumenter = runFeatureMethodInstrumenter;
}
@Override
public boolean matches(CtClass ctClass) {
return ctClass.getName().contains("org.spockframework.runtime.BaseSpecRunner");
}
@Override | // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java
// public interface ClassHandler {
//
// void handleClass(CtClass ctClass) throws CannotCompileException;
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java
// public interface InstrumentationProvider {
//
// boolean matches(CtClass ctClass);
//
// List<ClassHandler> getClassHandlers(CtClass ctClass);
//
// List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod);
//
// }
//
// Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java
// public interface MethodInstrumenter {
//
// void instrument(CtMethod ctMethod) throws CannotCompileException;
//
// boolean shouldInstrument(CtMethod ctMethod);
//
// }
// Path: src/main/java/io/jvoid/instrumentation/provider/spock/SpockInstrumentationProvider.java
import java.util.Collections;
import java.util.List;
import com.google.inject.Inject;
import io.jvoid.instrumentation.provider.api.ClassHandler;
import io.jvoid.instrumentation.provider.api.InstrumentationProvider;
import io.jvoid.instrumentation.provider.api.MethodInstrumenter;
import javassist.CtClass;
import javassist.CtMethod;
package io.jvoid.instrumentation.provider.spock;
/**
* JVoid instrumentation provider for Spock Framework. It indirectly uses also
* the JUnit instrumentation to realize the full JVoid functionalities.
*
*/
public class SpockInstrumentationProvider implements InstrumentationProvider {
private MethodInstrumenter runFeatureMethodInstrumenter;
@Inject
public SpockInstrumentationProvider(RunFeatureMethodInstrumenter runFeatureMethodInstrumenter) {
this.runFeatureMethodInstrumenter = runFeatureMethodInstrumenter;
}
@Override
public boolean matches(CtClass ctClass) {
return ctClass.getName().contains("org.spockframework.runtime.BaseSpecRunner");
}
@Override | public List<ClassHandler> getClassHandlers(CtClass ctClass) { |
jVoid/jVoid | src/main/java/io/jvoid/metadata/repositories/ClassesRepository.java | // Path: src/main/java/io/jvoid/database/MetadataDatabase.java
// @Singleton
// public class MetadataDatabase {
//
// private JVoidConfiguration configuration;
//
// private HikariDataSource ds;
//
// /**
// *
// * @param configuration
// */
// @Inject
// public MetadataDatabase(JVoidConfiguration configuration) {
// this.configuration = configuration;
// }
//
// /**
// *
// */
// @Inject
// public void startup() {
// if (ds != null && !ds.isClosed()) {
// return;
// }
//
// HikariConfig config = new HikariConfig();
// config.setJdbcUrl(configuration.dbUrl());
// config.setUsername(configuration.dbUsername());
// config.setPassword(configuration.dbPassword());
// config.addDataSourceProperty("cachePrepStmts", "true");
// config.addDataSourceProperty("prepStmtCacheSize", "250");
// config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
//
// ds = new HikariDataSource(config);
//
// initializeDatabase();
// }
//
// /**
// *
// */
// public void shutdown() {
// if (ds != null) {
// ds.close();
// ds = null;
// }
// }
//
// /**
// *
// */
// private void initializeDatabase() {
// Flyway flyway = new Flyway();
// flyway.setDataSource(ds);
// flyway.migrate();
// }
//
// /**
// *
// * @return A connection from the pool
// */
// public Connection getConnection() {
// try {
// return ds.getConnection();
// } catch (SQLException e) {
// throw new JVoidDataAccessException(e);
// }
// }
// }
//
// Path: src/main/java/io/jvoid/metadata/model/JClass.java
// @Data
// public class JClass implements JEntity<Long>, ChecksumAware {
//
// private Long id;
// private Long executionId;
// private String identifier;
// private String checksum;
// private String superClassIdentifier;
//
// }
| import java.util.Map;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanMapHandler;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.jvoid.database.MetadataDatabase;
import io.jvoid.metadata.model.JClass; | package io.jvoid.metadata.repositories;
/**
*
*/
@Singleton
public class ClassesRepository extends AbstractRepository<JClass, Long>implements TestRelatedEntityRepository<JClass, Long> {
private ResultSetHandler<JClass> objectHandler = new BeanHandler<>(JClass.class);
private ResultSetHandler<Map<String, JClass>> identifierMapHandler = new BeanMapHandler<>(JClass.class, "identifier");
@Inject | // Path: src/main/java/io/jvoid/database/MetadataDatabase.java
// @Singleton
// public class MetadataDatabase {
//
// private JVoidConfiguration configuration;
//
// private HikariDataSource ds;
//
// /**
// *
// * @param configuration
// */
// @Inject
// public MetadataDatabase(JVoidConfiguration configuration) {
// this.configuration = configuration;
// }
//
// /**
// *
// */
// @Inject
// public void startup() {
// if (ds != null && !ds.isClosed()) {
// return;
// }
//
// HikariConfig config = new HikariConfig();
// config.setJdbcUrl(configuration.dbUrl());
// config.setUsername(configuration.dbUsername());
// config.setPassword(configuration.dbPassword());
// config.addDataSourceProperty("cachePrepStmts", "true");
// config.addDataSourceProperty("prepStmtCacheSize", "250");
// config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
//
// ds = new HikariDataSource(config);
//
// initializeDatabase();
// }
//
// /**
// *
// */
// public void shutdown() {
// if (ds != null) {
// ds.close();
// ds = null;
// }
// }
//
// /**
// *
// */
// private void initializeDatabase() {
// Flyway flyway = new Flyway();
// flyway.setDataSource(ds);
// flyway.migrate();
// }
//
// /**
// *
// * @return A connection from the pool
// */
// public Connection getConnection() {
// try {
// return ds.getConnection();
// } catch (SQLException e) {
// throw new JVoidDataAccessException(e);
// }
// }
// }
//
// Path: src/main/java/io/jvoid/metadata/model/JClass.java
// @Data
// public class JClass implements JEntity<Long>, ChecksumAware {
//
// private Long id;
// private Long executionId;
// private String identifier;
// private String checksum;
// private String superClassIdentifier;
//
// }
// Path: src/main/java/io/jvoid/metadata/repositories/ClassesRepository.java
import java.util.Map;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanMapHandler;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.jvoid.database.MetadataDatabase;
import io.jvoid.metadata.model.JClass;
package io.jvoid.metadata.repositories;
/**
*
*/
@Singleton
public class ClassesRepository extends AbstractRepository<JClass, Long>implements TestRelatedEntityRepository<JClass, Long> {
private ResultSetHandler<JClass> objectHandler = new BeanHandler<>(JClass.class);
private ResultSetHandler<Map<String, JClass>> identifierMapHandler = new BeanMapHandler<>(JClass.class, "identifier");
@Inject | public ClassesRepository(MetadataDatabase database) { |
jVoid/jVoid | src/main/java/io/jvoid/configuration/JVoidConfigurationService.java | // Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java
// public class JVoidConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public JVoidConfigurationException(String message) {
// super(message);
// }
// public JVoidConfigurationException(String message, Throwable e) {
// super(message, e);
// }
//
// }
| import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.jvoid.exceptions.JVoidConfigurationException;
import lombok.extern.slf4j.Slf4j; | package io.jvoid.configuration;
/**
* Basic service to load and get the {@code JVoidConfiguration}.
*
*/
@Slf4j
@Singleton
public class JVoidConfigurationService {
private JVoidPropertiesBasedConfigurationLoader loader;
private JVoidConfigurationValidator validator;
private JVoidConfiguration configuration;
@Inject
public JVoidConfigurationService(JVoidPropertiesBasedConfigurationLoader loader, JVoidConfigurationValidator validator) {
this.loader = loader;
this.validator = validator;
}
| // Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java
// public class JVoidConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public JVoidConfigurationException(String message) {
// super(message);
// }
// public JVoidConfigurationException(String message, Throwable e) {
// super(message, e);
// }
//
// }
// Path: src/main/java/io/jvoid/configuration/JVoidConfigurationService.java
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.jvoid.exceptions.JVoidConfigurationException;
import lombok.extern.slf4j.Slf4j;
package io.jvoid.configuration;
/**
* Basic service to load and get the {@code JVoidConfiguration}.
*
*/
@Slf4j
@Singleton
public class JVoidConfigurationService {
private JVoidPropertiesBasedConfigurationLoader loader;
private JVoidConfigurationValidator validator;
private JVoidConfiguration configuration;
@Inject
public JVoidConfigurationService(JVoidPropertiesBasedConfigurationLoader loader, JVoidConfigurationValidator validator) {
this.loader = loader;
this.validator = validator;
}
| public synchronized void loadConfiguration(String parameterConfigurationPath) throws JVoidConfigurationException { |
tony-Shx/Swface | app/src/main/java/com/henu/swface/activity/LoginActivity.java | // Path: app/src/main/java/com/henu/swface/VO/UserLogin.java
// public class UserLogin extends BmobUser {
// private String QQ;
// private String WeChat;
// private String Weibo;
//
// public UserLogin() {
// }
//
// public String getQQ() {
// return QQ;
// }
//
// public void setQQ(String QQ) {
// this.QQ = QQ;
// }
//
// public String getWeChat() {
// return WeChat;
// }
//
// public void setWeChat(String weChat) {
// WeChat = weChat;
// }
//
// public String getWeibo() {
// return Weibo;
// }
//
// public void setWeibo(String weibo) {
// Weibo = weibo;
// }
// }
| import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import com.henu.swface.R;
import com.henu.swface.VO.UserLogin;
import java.util.List;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener; | private void findView() {
imageButton_login = (ImageButton) findViewById(R.id.imageButton_login);
editText3_username = (EditText) findViewById(R.id.editText3_username);
editText3_password = (EditText) findViewById(R.id.editText3_password);
checkBox_remember_password = (CheckBox) findViewById(R.id.checkBox_remember_password);
}
@Override
public void onClick(View v) {
System.out.println("执行了这句话");
switch (v.getId()) {
case R.id.imageButton_login:
String username, password;
username = editText3_username.getText().toString();
password = editText3_password.getText().toString();
if (username.length() != 11 || !username.startsWith("1")) {
showNormalDia("温馨提示", "请输入合法的手机号");
} else if (password.length() < 6 || password.length() > 20) {
showNormalDia("温馨提示", "密码为6-20位,不可过短或过长");
} else {
showReadProcess();
startSearchUser(username, password);
}
default:
break;
}
}
private void startSearchUser(final String username, final String password) { | // Path: app/src/main/java/com/henu/swface/VO/UserLogin.java
// public class UserLogin extends BmobUser {
// private String QQ;
// private String WeChat;
// private String Weibo;
//
// public UserLogin() {
// }
//
// public String getQQ() {
// return QQ;
// }
//
// public void setQQ(String QQ) {
// this.QQ = QQ;
// }
//
// public String getWeChat() {
// return WeChat;
// }
//
// public void setWeChat(String weChat) {
// WeChat = weChat;
// }
//
// public String getWeibo() {
// return Weibo;
// }
//
// public void setWeibo(String weibo) {
// Weibo = weibo;
// }
// }
// Path: app/src/main/java/com/henu/swface/activity/LoginActivity.java
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import com.henu.swface.R;
import com.henu.swface.VO.UserLogin;
import java.util.List;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
private void findView() {
imageButton_login = (ImageButton) findViewById(R.id.imageButton_login);
editText3_username = (EditText) findViewById(R.id.editText3_username);
editText3_password = (EditText) findViewById(R.id.editText3_password);
checkBox_remember_password = (CheckBox) findViewById(R.id.checkBox_remember_password);
}
@Override
public void onClick(View v) {
System.out.println("执行了这句话");
switch (v.getId()) {
case R.id.imageButton_login:
String username, password;
username = editText3_username.getText().toString();
password = editText3_password.getText().toString();
if (username.length() != 11 || !username.startsWith("1")) {
showNormalDia("温馨提示", "请输入合法的手机号");
} else if (password.length() < 6 || password.length() > 20) {
showNormalDia("温馨提示", "密码为6-20位,不可过短或过长");
} else {
showReadProcess();
startSearchUser(username, password);
}
default:
break;
}
}
private void startSearchUser(final String username, final String password) { | BmobQuery<UserLogin> query = new BmobQuery<>(); |
ScreenBasedSimulator/ScreenBasedSimulator | sbs/src/main/java/edu/cmu/lti/bic/sbs/db/DBHelper.java | // Path: sbs/src/main/java/edu/cmu/lti/bic/sbs/gson/Record.java
// public class Record {
// String user;
// int scenarioId;
// Float score;
// String report = "N/A";
// String debrief = "N/A";
// public Record(String user, int scenarioId, Float score, String report, String debrief) {
// this.user = user;
// this.scenarioId = scenarioId;
// this.score = score;
// this.report = report;
// this.debrief = debrief;
// }
// @Override
// public String toString() {
// String text =
// "<br/>" +
// "<p>User: " + user + "</p>" +
// "<p>Score: " + score + "</p>" +
// "<p> Report: " + report.replace("\n", "<br/>") + "</p>" +
// "<p> Debreif:" + debrief + "</p>" +
// "<p> Scenario:" + scenarioId + "</p>" +
// "<br/>";
// return text;
// }
// }
| import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import edu.cmu.lti.bic.sbs.gson.Record; | package edu.cmu.lti.bic.sbs.db;
// Notice, do not import com.mysql.jdbc.*
// or you will have problems!
public class DBHelper {
private static Statement statement = null;
private static PreparedStatement preparedStatement = null;
private static ResultSet resultSet = null;
private static Connection conn = null;
| // Path: sbs/src/main/java/edu/cmu/lti/bic/sbs/gson/Record.java
// public class Record {
// String user;
// int scenarioId;
// Float score;
// String report = "N/A";
// String debrief = "N/A";
// public Record(String user, int scenarioId, Float score, String report, String debrief) {
// this.user = user;
// this.scenarioId = scenarioId;
// this.score = score;
// this.report = report;
// this.debrief = debrief;
// }
// @Override
// public String toString() {
// String text =
// "<br/>" +
// "<p>User: " + user + "</p>" +
// "<p>Score: " + score + "</p>" +
// "<p> Report: " + report.replace("\n", "<br/>") + "</p>" +
// "<p> Debreif:" + debrief + "</p>" +
// "<p> Scenario:" + scenarioId + "</p>" +
// "<br/>";
// return text;
// }
// }
// Path: sbs/src/main/java/edu/cmu/lti/bic/sbs/db/DBHelper.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import edu.cmu.lti.bic.sbs.gson.Record;
package edu.cmu.lti.bic.sbs.db;
// Notice, do not import com.mysql.jdbc.*
// or you will have problems!
public class DBHelper {
private static Statement statement = null;
private static PreparedStatement preparedStatement = null;
private static ResultSet resultSet = null;
private static Connection conn = null;
| public static Record[] displayDataBase(String username) throws Exception { |
ScreenBasedSimulator/ScreenBasedSimulator | sbs/src/main/java/edu/cmu/lti/bic/sbs/ui/DrugWindow.java | // Path: sbs/src/main/java/edu/cmu/lti/bic/sbs/gson/Drug.java
// public class Drug {
// private String name = "";
//
// private String description = "";
//
// private String id = "";
//
// public Drug() {
// this.name = "-";
// this.description = "Default description";
// this.id = "Default id";
// }
//
// // constructor without does
// public Drug(String name, String description, String id) {
// super();
// this.name = name;
// this.description = description;
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public String getName() {
// return name;
// }
//
// /**
// * @param name the name to set
// */
// public void setName(String name) {
// this.name = name;
// }
//
// /**
// * @return the description
// */
// public String getDescription() {
// return description;
// }
//
// /**
// * @param description the description to set
// */
// public void setDescription(String description) {
// this.description = description;
// }
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @param id the id to set
// */
// public void setId(String id) {
// this.id = id;
// }
// }
| import java.util.HashMap;
import javax.swing.JFrame;
import edu.cmu.lti.bic.sbs.gson.Drug; | package edu.cmu.lti.bic.sbs.ui;
public class DrugWindow {
JFrame frame;
UserInterface ui;
/**
* Create the application.
* @param ui user interface
*/
public DrugWindow(UserInterface ui) {
this.ui=ui;
initialize(new DrugPanel(ui));
}
/**
* Initialize the contents of the frame.
* @param drugPanel
*/
private void initialize(DrugPanel drugPanel) {
frame = new JFrame();
frame.setBounds(100, 100, 500, 70);
drugPanel.setBounds(200, 200, 100, 50);
frame.getContentPane().add(drugPanel); | // Path: sbs/src/main/java/edu/cmu/lti/bic/sbs/gson/Drug.java
// public class Drug {
// private String name = "";
//
// private String description = "";
//
// private String id = "";
//
// public Drug() {
// this.name = "-";
// this.description = "Default description";
// this.id = "Default id";
// }
//
// // constructor without does
// public Drug(String name, String description, String id) {
// super();
// this.name = name;
// this.description = description;
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public String getName() {
// return name;
// }
//
// /**
// * @param name the name to set
// */
// public void setName(String name) {
// this.name = name;
// }
//
// /**
// * @return the description
// */
// public String getDescription() {
// return description;
// }
//
// /**
// * @param description the description to set
// */
// public void setDescription(String description) {
// this.description = description;
// }
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @param id the id to set
// */
// public void setId(String id) {
// this.id = id;
// }
// }
// Path: sbs/src/main/java/edu/cmu/lti/bic/sbs/ui/DrugWindow.java
import java.util.HashMap;
import javax.swing.JFrame;
import edu.cmu.lti.bic.sbs.gson.Drug;
package edu.cmu.lti.bic.sbs.ui;
public class DrugWindow {
JFrame frame;
UserInterface ui;
/**
* Create the application.
* @param ui user interface
*/
public DrugWindow(UserInterface ui) {
this.ui=ui;
initialize(new DrugPanel(ui));
}
/**
* Initialize the contents of the frame.
* @param drugPanel
*/
private void initialize(DrugPanel drugPanel) {
frame = new JFrame();
frame.setBounds(100, 100, 500, 70);
drugPanel.setBounds(200, 200, 100, 50);
frame.getContentPane().add(drugPanel); | HashMap<String,Drug> drugMap=ui.getDrugMap(); |
ScreenBasedSimulator/ScreenBasedSimulator | sbs/src/test/java/edu/cmu/lti/bic/sbs/gson/test/EquipmentTest.java | // Path: sbs/src/main/java/edu/cmu/lti/bic/sbs/gson/Tool.java
// public class Tool {
// private String name = "-";
//
// private String id = null;
//
// public Tool() {
// this("Default id", "-", 100);
// }
//
// private double value;
//
// public String getName() {
// return name;
// }
//
// public Tool setName(String toolName) {
// this.name = toolName;
// return this;
// }
//
// public String getId() {
// return id;
// }
//
// public String toString() {
// return name;
// }
//
// public Tool(String id, String name, double value) {
//
// this.id = id;
// this.name = name;
// }
//
// public double getValue() {
// return value;
// }
//
// public void setValue(double value) {
// this.value = value;
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.gson.Gson;
import edu.cmu.lti.bic.sbs.gson.Tool; | package edu.cmu.lti.bic.sbs.gson.test;
public class EquipmentTest {
static Gson gson = new Gson(); | // Path: sbs/src/main/java/edu/cmu/lti/bic/sbs/gson/Tool.java
// public class Tool {
// private String name = "-";
//
// private String id = null;
//
// public Tool() {
// this("Default id", "-", 100);
// }
//
// private double value;
//
// public String getName() {
// return name;
// }
//
// public Tool setName(String toolName) {
// this.name = toolName;
// return this;
// }
//
// public String getId() {
// return id;
// }
//
// public String toString() {
// return name;
// }
//
// public Tool(String id, String name, double value) {
//
// this.id = id;
// this.name = name;
// }
//
// public double getValue() {
// return value;
// }
//
// public void setValue(double value) {
// this.value = value;
// }
// }
// Path: sbs/src/test/java/edu/cmu/lti/bic/sbs/gson/test/EquipmentTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.gson.Gson;
import edu.cmu.lti.bic.sbs.gson.Tool;
package edu.cmu.lti.bic.sbs.gson.test;
public class EquipmentTest {
static Gson gson = new Gson(); | static Tool[] tools = null; |
manuel-woelker/jimix | samples/vertx/src/main/java/org/woelker/jimix/samples/vertx/JimixSampleVertxMain.java | // Path: vertx/src/main/java/org/woelker/jimix/vertx/JimixVertxHandler.java
// public class JimixVertxHandler implements Handler<HttpServerRequest> {
//
// RequestHandler requestHandler = new JimixRequestHandler();
//
// @Override
// public void handle(HttpServerRequest request) {
// try {
// requestHandler.handle(new VertxHttpRequestWrapper(request));
// request.response().end();
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
| import org.vertx.java.core.Vertx;
import org.vertx.java.core.http.HttpServer;
import org.vertx.java.core.http.RouteMatcher;
import org.vertx.java.core.impl.DefaultVertx;
import org.woelker.jimix.vertx.JimixVertxHandler; | package org.woelker.jimix.samples.vertx;
public class JimixSampleVertxMain {
public static void main(String[] args) throws Exception {
new JimixSampleVertxMain().run();
}
private void run() throws Exception {
Vertx vertx = new DefaultVertx();
HttpServer server = vertx.createHttpServer();
RouteMatcher routeMatcher = new RouteMatcher();
| // Path: vertx/src/main/java/org/woelker/jimix/vertx/JimixVertxHandler.java
// public class JimixVertxHandler implements Handler<HttpServerRequest> {
//
// RequestHandler requestHandler = new JimixRequestHandler();
//
// @Override
// public void handle(HttpServerRequest request) {
// try {
// requestHandler.handle(new VertxHttpRequestWrapper(request));
// request.response().end();
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
// Path: samples/vertx/src/main/java/org/woelker/jimix/samples/vertx/JimixSampleVertxMain.java
import org.vertx.java.core.Vertx;
import org.vertx.java.core.http.HttpServer;
import org.vertx.java.core.http.RouteMatcher;
import org.vertx.java.core.impl.DefaultVertx;
import org.woelker.jimix.vertx.JimixVertxHandler;
package org.woelker.jimix.samples.vertx;
public class JimixSampleVertxMain {
public static void main(String[] args) throws Exception {
new JimixSampleVertxMain().run();
}
private void run() throws Exception {
Vertx vertx = new DefaultVertx();
HttpServer server = vertx.createHttpServer();
RouteMatcher routeMatcher = new RouteMatcher();
| routeMatcher.allWithRegEx("/jimix(.*)", new JimixVertxHandler()); |
manuel-woelker/jimix | samples/jetty/src/main/java/org/woelker/jimix/samples/jetty/JimixSampleJetty.java | // Path: servlet/src/main/java/org/woelker/jimix/servlet/JimixServlet.java
// public class JimixServlet extends HttpServlet {
//
// private final JimixRequestHandler jimixRequestHandler;
//
// public JimixServlet() {
// jimixRequestHandler = new JimixRequestHandler();
// }
//
// @Override
// protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// try {
// jimixRequestHandler.handle(new ServletHttpRequestWrapper(request, response));
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// }
| import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Gauge;
import com.yammer.metrics.core.MetricName;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.woelker.jimix.servlet.JimixServlet;
import javax.management.*;
import java.lang.management.ManagementFactory;
import java.util.Arrays;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger; | package org.woelker.jimix.samples.jetty;
public class JimixSampleJetty {
public static void main(String[] args) throws Exception {
new JimixSampleJetty().run();
}
private void run() throws Exception {
addSampleMetrics();
ManagementFactory.getPlatformMBeanServer().registerMBean(new Hello(), new ObjectName("asdf:name=bar"));
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
| // Path: servlet/src/main/java/org/woelker/jimix/servlet/JimixServlet.java
// public class JimixServlet extends HttpServlet {
//
// private final JimixRequestHandler jimixRequestHandler;
//
// public JimixServlet() {
// jimixRequestHandler = new JimixRequestHandler();
// }
//
// @Override
// protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// try {
// jimixRequestHandler.handle(new ServletHttpRequestWrapper(request, response));
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// }
// Path: samples/jetty/src/main/java/org/woelker/jimix/samples/jetty/JimixSampleJetty.java
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Gauge;
import com.yammer.metrics.core.MetricName;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.woelker.jimix.servlet.JimixServlet;
import javax.management.*;
import java.lang.management.ManagementFactory;
import java.util.Arrays;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
package org.woelker.jimix.samples.jetty;
public class JimixSampleJetty {
public static void main(String[] args) throws Exception {
new JimixSampleJetty().run();
}
private void run() throws Exception {
addSampleMetrics();
ManagementFactory.getPlatformMBeanServer().registerMBean(new Hello(), new ObjectName("asdf:name=bar"));
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
| context.addServlet(new ServletHolder(new JimixServlet()), "/jimix/*"); |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/di/PlayListActivityModule.java | // Path: app/src/main/java/in/arjsna/audiorecorder/activities/PlayListActivity.java
// public class PlayListActivity extends BaseActivity implements HasSupportFragmentInjector {
//
// @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
//
// @Override public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_record_list);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// ActionBar actionBar = getSupportActionBar();
// if (actionBar != null) {
// actionBar.setTitle(R.string.tab_title_saved_recordings);
// actionBar.setDisplayHomeAsUpEnabled(true);
// actionBar.setDisplayShowHomeEnabled(true);
// }
// setNavBarColor();
//
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.record_list_container, PlayListFragment.newInstance())
// .commit();
// }
// }
//
// @Override public AndroidInjector<Fragment> supportFragmentInjector() {
// return dispatchingAndroidInjector;
// }
// }
| import android.content.Context;
import dagger.Module;
import dagger.Provides;
import in.arjsna.audiorecorder.activities.PlayListActivity;
import in.arjsna.audiorecorder.di.qualifiers.ActivityContext;
import in.arjsna.audiorecorder.di.scopes.ActivityScope; | package in.arjsna.audiorecorder.di;
/**
* Created by arjun on 12/1/17.
*/
@Module
class PlayListActivityModule {
@Provides
@ActivityContext
@ActivityScope | // Path: app/src/main/java/in/arjsna/audiorecorder/activities/PlayListActivity.java
// public class PlayListActivity extends BaseActivity implements HasSupportFragmentInjector {
//
// @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
//
// @Override public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_record_list);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// ActionBar actionBar = getSupportActionBar();
// if (actionBar != null) {
// actionBar.setTitle(R.string.tab_title_saved_recordings);
// actionBar.setDisplayHomeAsUpEnabled(true);
// actionBar.setDisplayShowHomeEnabled(true);
// }
// setNavBarColor();
//
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.record_list_container, PlayListFragment.newInstance())
// .commit();
// }
// }
//
// @Override public AndroidInjector<Fragment> supportFragmentInjector() {
// return dispatchingAndroidInjector;
// }
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/di/PlayListActivityModule.java
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import in.arjsna.audiorecorder.activities.PlayListActivity;
import in.arjsna.audiorecorder.di.qualifiers.ActivityContext;
import in.arjsna.audiorecorder.di.scopes.ActivityScope;
package in.arjsna.audiorecorder.di;
/**
* Created by arjun on 12/1/17.
*/
@Module
class PlayListActivityModule {
@Provides
@ActivityContext
@ActivityScope | Context provideActivityContext(PlayListActivity activity) { |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/recordingservice/AudioRecordService.java | // Path: app/src/main/java/in/arjsna/audiorecorder/AppConstants.java
// public class AppConstants {
// public static final String ACTION_PAUSE = "in.arjsna.audiorecorder.PAUSE";
// public static final String ACTION_RESUME = "in.arjsna.audiorecorder.RESUME";
// public static final String ACTION_STOP = "in.arjsna.audiorecorder.STOP";
// public static final String ACTION_IN_SERVICE = "in.arjsna.audiorecorder.ACTION_IN_SERVICE";
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/activities/MainActivity.java
// public class MainActivity extends BaseActivity
// implements HasSupportFragmentInjector, EasyPermissions.PermissionCallbacks {
//
// private static final String LOG_TAG = MainActivity.class.getSimpleName();
// private static final int PERMISSION_REQ = 222;
//
// @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
//
// @Override public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.main_container, RecordFragment.newInstance())
// .commit();
// }
// getPermissions();
// }
//
// @Override public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_main, menu);
// return true;
// }
//
// @Override public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case R.id.action_settings:
// Intent i = new Intent(this, SettingsActivity.class);
// startActivity(i);
// return true;
// default:
// return super.onOptionsItemSelected(item);
// }
// }
//
// @TargetApi(23)
// private void getPermissions() {
// String[] permissions = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE,
// Manifest.permission.RECORD_AUDIO};
// if (!EasyPermissions.hasPermissions(MainActivity.this, permissions)) {
// EasyPermissions.requestPermissions(this, getString(R.string.permissions_required),
// PERMISSION_REQ, permissions);
// }
// }
//
// @TargetApi(23)
// @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
// @NonNull int[] grantResults) {
// EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
// }
//
// private void showRationale() {
// AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// builder.setTitle("Permissions Required")
// .setCancelable(false)
// .setMessage(
// getString(R.string.permissions_required))
// .setPositiveButton(R.string.dialog_action_ok, (dialog, which) -> {
// openSettingsPage();
// dialog.dismiss();
// })
// .setNegativeButton(R.string.dialog_action_cancel,
// (dialog, which) -> onBackPressed())
// .show();
// }
//
// private void openSettingsPage() {
// Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
// intent.setData(Uri.parse("package:" + getPackageName()));
// startActivityForResult(intent, PERMISSION_REQ);
// }
//
// @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
// getPermissions();
// }
//
// @Override public AndroidInjector<Fragment> supportFragmentInjector() {
// return dispatchingAndroidInjector;
// }
//
// @Override public void onPermissionsGranted(int requestCode, List<String> perms) {
// //NO-OP
// }
//
// @Override public void onPermissionsDenied(int requestCode, List<String> perms) {
// if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
// showRationale();
// return;
// }
// finish();
// }
// }
| import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import com.orhanobut.hawk.Hawk;
import dagger.android.AndroidInjection;
import in.arjsna.audiorecorder.AppConstants;
import in.arjsna.audiorecorder.R;
import in.arjsna.audiorecorder.activities.MainActivity;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import java.util.Locale;
import javax.inject.Inject; | private NotificationManager mNotificationManager;
private static final int NOTIFY_ID = 100;
private AudioRecorder.RecordTime lastUpdated;
private boolean mIsClientBound = false;
@Override public IBinder onBind(Intent intent) {
mIsClientBound = true;
return mIBinder;
}
public boolean isRecording() {
return audioRecorder.isRecording();
}
@Override
public void onCreate() {
super.onCreate();
AndroidInjection.inject(this);
handler.addRecorder(audioRecorder);
mIBinder = new ServiceBinder();
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
public AudioRecordingDbmHandler getHandler() {
return handler;
}
@Override public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction() != null) {
switch (intent.getAction()) { | // Path: app/src/main/java/in/arjsna/audiorecorder/AppConstants.java
// public class AppConstants {
// public static final String ACTION_PAUSE = "in.arjsna.audiorecorder.PAUSE";
// public static final String ACTION_RESUME = "in.arjsna.audiorecorder.RESUME";
// public static final String ACTION_STOP = "in.arjsna.audiorecorder.STOP";
// public static final String ACTION_IN_SERVICE = "in.arjsna.audiorecorder.ACTION_IN_SERVICE";
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/activities/MainActivity.java
// public class MainActivity extends BaseActivity
// implements HasSupportFragmentInjector, EasyPermissions.PermissionCallbacks {
//
// private static final String LOG_TAG = MainActivity.class.getSimpleName();
// private static final int PERMISSION_REQ = 222;
//
// @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
//
// @Override public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.main_container, RecordFragment.newInstance())
// .commit();
// }
// getPermissions();
// }
//
// @Override public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_main, menu);
// return true;
// }
//
// @Override public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case R.id.action_settings:
// Intent i = new Intent(this, SettingsActivity.class);
// startActivity(i);
// return true;
// default:
// return super.onOptionsItemSelected(item);
// }
// }
//
// @TargetApi(23)
// private void getPermissions() {
// String[] permissions = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE,
// Manifest.permission.RECORD_AUDIO};
// if (!EasyPermissions.hasPermissions(MainActivity.this, permissions)) {
// EasyPermissions.requestPermissions(this, getString(R.string.permissions_required),
// PERMISSION_REQ, permissions);
// }
// }
//
// @TargetApi(23)
// @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
// @NonNull int[] grantResults) {
// EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
// }
//
// private void showRationale() {
// AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// builder.setTitle("Permissions Required")
// .setCancelable(false)
// .setMessage(
// getString(R.string.permissions_required))
// .setPositiveButton(R.string.dialog_action_ok, (dialog, which) -> {
// openSettingsPage();
// dialog.dismiss();
// })
// .setNegativeButton(R.string.dialog_action_cancel,
// (dialog, which) -> onBackPressed())
// .show();
// }
//
// private void openSettingsPage() {
// Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
// intent.setData(Uri.parse("package:" + getPackageName()));
// startActivityForResult(intent, PERMISSION_REQ);
// }
//
// @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
// getPermissions();
// }
//
// @Override public AndroidInjector<Fragment> supportFragmentInjector() {
// return dispatchingAndroidInjector;
// }
//
// @Override public void onPermissionsGranted(int requestCode, List<String> perms) {
// //NO-OP
// }
//
// @Override public void onPermissionsDenied(int requestCode, List<String> perms) {
// if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
// showRationale();
// return;
// }
// finish();
// }
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/recordingservice/AudioRecordService.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import com.orhanobut.hawk.Hawk;
import dagger.android.AndroidInjection;
import in.arjsna.audiorecorder.AppConstants;
import in.arjsna.audiorecorder.R;
import in.arjsna.audiorecorder.activities.MainActivity;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import java.util.Locale;
import javax.inject.Inject;
private NotificationManager mNotificationManager;
private static final int NOTIFY_ID = 100;
private AudioRecorder.RecordTime lastUpdated;
private boolean mIsClientBound = false;
@Override public IBinder onBind(Intent intent) {
mIsClientBound = true;
return mIBinder;
}
public boolean isRecording() {
return audioRecorder.isRecording();
}
@Override
public void onCreate() {
super.onCreate();
AndroidInjection.inject(this);
handler.addRecorder(audioRecorder);
mIBinder = new ServiceBinder();
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
public AudioRecordingDbmHandler getHandler() {
return handler;
}
@Override public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction() != null) {
switch (intent.getAction()) { | case AppConstants.ACTION_PAUSE: |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/recordingservice/AudioRecordService.java | // Path: app/src/main/java/in/arjsna/audiorecorder/AppConstants.java
// public class AppConstants {
// public static final String ACTION_PAUSE = "in.arjsna.audiorecorder.PAUSE";
// public static final String ACTION_RESUME = "in.arjsna.audiorecorder.RESUME";
// public static final String ACTION_STOP = "in.arjsna.audiorecorder.STOP";
// public static final String ACTION_IN_SERVICE = "in.arjsna.audiorecorder.ACTION_IN_SERVICE";
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/activities/MainActivity.java
// public class MainActivity extends BaseActivity
// implements HasSupportFragmentInjector, EasyPermissions.PermissionCallbacks {
//
// private static final String LOG_TAG = MainActivity.class.getSimpleName();
// private static final int PERMISSION_REQ = 222;
//
// @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
//
// @Override public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.main_container, RecordFragment.newInstance())
// .commit();
// }
// getPermissions();
// }
//
// @Override public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_main, menu);
// return true;
// }
//
// @Override public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case R.id.action_settings:
// Intent i = new Intent(this, SettingsActivity.class);
// startActivity(i);
// return true;
// default:
// return super.onOptionsItemSelected(item);
// }
// }
//
// @TargetApi(23)
// private void getPermissions() {
// String[] permissions = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE,
// Manifest.permission.RECORD_AUDIO};
// if (!EasyPermissions.hasPermissions(MainActivity.this, permissions)) {
// EasyPermissions.requestPermissions(this, getString(R.string.permissions_required),
// PERMISSION_REQ, permissions);
// }
// }
//
// @TargetApi(23)
// @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
// @NonNull int[] grantResults) {
// EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
// }
//
// private void showRationale() {
// AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// builder.setTitle("Permissions Required")
// .setCancelable(false)
// .setMessage(
// getString(R.string.permissions_required))
// .setPositiveButton(R.string.dialog_action_ok, (dialog, which) -> {
// openSettingsPage();
// dialog.dismiss();
// })
// .setNegativeButton(R.string.dialog_action_cancel,
// (dialog, which) -> onBackPressed())
// .show();
// }
//
// private void openSettingsPage() {
// Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
// intent.setData(Uri.parse("package:" + getPackageName()));
// startActivityForResult(intent, PERMISSION_REQ);
// }
//
// @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
// getPermissions();
// }
//
// @Override public AndroidInjector<Fragment> supportFragmentInjector() {
// return dispatchingAndroidInjector;
// }
//
// @Override public void onPermissionsGranted(int requestCode, List<String> perms) {
// //NO-OP
// }
//
// @Override public void onPermissionsDenied(int requestCode, List<String> perms) {
// if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
// showRationale();
// return;
// }
// finish();
// }
// }
| import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import com.orhanobut.hawk.Hawk;
import dagger.android.AndroidInjection;
import in.arjsna.audiorecorder.AppConstants;
import in.arjsna.audiorecorder.R;
import in.arjsna.audiorecorder.activities.MainActivity;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import java.util.Locale;
import javax.inject.Inject; | public Disposable subscribeForTimer(Consumer<AudioRecorder.RecordTime> timerConsumer) {
return audioRecorder.subscribeTimer(timerConsumer);
}
private void updateNotification(AudioRecorder.RecordTime recordTime) {
mNotificationManager.notify(NOTIFY_ID, createNotification(recordTime));
}
private Notification createNotification(AudioRecorder.RecordTime recordTime) {
lastUpdated = recordTime;
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext()).setSmallIcon(
R.drawable.ic_media_record)
.setContentTitle(getString(R.string.notification_recording))
.setContentText(
String.format(Locale.getDefault(), getString(R.string.record_time_format),
recordTime.hours,
recordTime.minutes,
recordTime.seconds))
.addAction(R.drawable.ic_media_stop, getString(R.string.stop_recording),
getActionIntent(AppConstants.ACTION_STOP))
.setOngoing(true);
if (audioRecorder.isPaused()) {
mBuilder.addAction(R.drawable.ic_media_record, getString(R.string.resume_recording_button),
getActionIntent(AppConstants.ACTION_RESUME));
} else {
mBuilder.addAction(R.drawable.ic_media_pause, getString(R.string.pause_recording_button),
getActionIntent(AppConstants.ACTION_PAUSE));
}
mBuilder.setContentIntent(PendingIntent.getActivities(getApplicationContext(), 0, | // Path: app/src/main/java/in/arjsna/audiorecorder/AppConstants.java
// public class AppConstants {
// public static final String ACTION_PAUSE = "in.arjsna.audiorecorder.PAUSE";
// public static final String ACTION_RESUME = "in.arjsna.audiorecorder.RESUME";
// public static final String ACTION_STOP = "in.arjsna.audiorecorder.STOP";
// public static final String ACTION_IN_SERVICE = "in.arjsna.audiorecorder.ACTION_IN_SERVICE";
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/activities/MainActivity.java
// public class MainActivity extends BaseActivity
// implements HasSupportFragmentInjector, EasyPermissions.PermissionCallbacks {
//
// private static final String LOG_TAG = MainActivity.class.getSimpleName();
// private static final int PERMISSION_REQ = 222;
//
// @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
//
// @Override public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.main_container, RecordFragment.newInstance())
// .commit();
// }
// getPermissions();
// }
//
// @Override public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_main, menu);
// return true;
// }
//
// @Override public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case R.id.action_settings:
// Intent i = new Intent(this, SettingsActivity.class);
// startActivity(i);
// return true;
// default:
// return super.onOptionsItemSelected(item);
// }
// }
//
// @TargetApi(23)
// private void getPermissions() {
// String[] permissions = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE,
// Manifest.permission.RECORD_AUDIO};
// if (!EasyPermissions.hasPermissions(MainActivity.this, permissions)) {
// EasyPermissions.requestPermissions(this, getString(R.string.permissions_required),
// PERMISSION_REQ, permissions);
// }
// }
//
// @TargetApi(23)
// @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
// @NonNull int[] grantResults) {
// EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
// }
//
// private void showRationale() {
// AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// builder.setTitle("Permissions Required")
// .setCancelable(false)
// .setMessage(
// getString(R.string.permissions_required))
// .setPositiveButton(R.string.dialog_action_ok, (dialog, which) -> {
// openSettingsPage();
// dialog.dismiss();
// })
// .setNegativeButton(R.string.dialog_action_cancel,
// (dialog, which) -> onBackPressed())
// .show();
// }
//
// private void openSettingsPage() {
// Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
// intent.setData(Uri.parse("package:" + getPackageName()));
// startActivityForResult(intent, PERMISSION_REQ);
// }
//
// @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
// getPermissions();
// }
//
// @Override public AndroidInjector<Fragment> supportFragmentInjector() {
// return dispatchingAndroidInjector;
// }
//
// @Override public void onPermissionsGranted(int requestCode, List<String> perms) {
// //NO-OP
// }
//
// @Override public void onPermissionsDenied(int requestCode, List<String> perms) {
// if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
// showRationale();
// return;
// }
// finish();
// }
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/recordingservice/AudioRecordService.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import com.orhanobut.hawk.Hawk;
import dagger.android.AndroidInjection;
import in.arjsna.audiorecorder.AppConstants;
import in.arjsna.audiorecorder.R;
import in.arjsna.audiorecorder.activities.MainActivity;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import java.util.Locale;
import javax.inject.Inject;
public Disposable subscribeForTimer(Consumer<AudioRecorder.RecordTime> timerConsumer) {
return audioRecorder.subscribeTimer(timerConsumer);
}
private void updateNotification(AudioRecorder.RecordTime recordTime) {
mNotificationManager.notify(NOTIFY_ID, createNotification(recordTime));
}
private Notification createNotification(AudioRecorder.RecordTime recordTime) {
lastUpdated = recordTime;
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext()).setSmallIcon(
R.drawable.ic_media_record)
.setContentTitle(getString(R.string.notification_recording))
.setContentText(
String.format(Locale.getDefault(), getString(R.string.record_time_format),
recordTime.hours,
recordTime.minutes,
recordTime.seconds))
.addAction(R.drawable.ic_media_stop, getString(R.string.stop_recording),
getActionIntent(AppConstants.ACTION_STOP))
.setOngoing(true);
if (audioRecorder.isPaused()) {
mBuilder.addAction(R.drawable.ic_media_record, getString(R.string.resume_recording_button),
getActionIntent(AppConstants.ACTION_RESUME));
} else {
mBuilder.addAction(R.drawable.ic_media_pause, getString(R.string.pause_recording_button),
getActionIntent(AppConstants.ACTION_PAUSE));
}
mBuilder.setContentIntent(PendingIntent.getActivities(getApplicationContext(), 0, | new Intent[] {new Intent(getApplicationContext(), MainActivity.class)}, 0)); |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/di/MainActivityModule.java | // Path: app/src/main/java/in/arjsna/audiorecorder/activities/MainActivity.java
// public class MainActivity extends BaseActivity
// implements HasSupportFragmentInjector, EasyPermissions.PermissionCallbacks {
//
// private static final String LOG_TAG = MainActivity.class.getSimpleName();
// private static final int PERMISSION_REQ = 222;
//
// @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
//
// @Override public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.main_container, RecordFragment.newInstance())
// .commit();
// }
// getPermissions();
// }
//
// @Override public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_main, menu);
// return true;
// }
//
// @Override public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case R.id.action_settings:
// Intent i = new Intent(this, SettingsActivity.class);
// startActivity(i);
// return true;
// default:
// return super.onOptionsItemSelected(item);
// }
// }
//
// @TargetApi(23)
// private void getPermissions() {
// String[] permissions = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE,
// Manifest.permission.RECORD_AUDIO};
// if (!EasyPermissions.hasPermissions(MainActivity.this, permissions)) {
// EasyPermissions.requestPermissions(this, getString(R.string.permissions_required),
// PERMISSION_REQ, permissions);
// }
// }
//
// @TargetApi(23)
// @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
// @NonNull int[] grantResults) {
// EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
// }
//
// private void showRationale() {
// AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// builder.setTitle("Permissions Required")
// .setCancelable(false)
// .setMessage(
// getString(R.string.permissions_required))
// .setPositiveButton(R.string.dialog_action_ok, (dialog, which) -> {
// openSettingsPage();
// dialog.dismiss();
// })
// .setNegativeButton(R.string.dialog_action_cancel,
// (dialog, which) -> onBackPressed())
// .show();
// }
//
// private void openSettingsPage() {
// Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
// intent.setData(Uri.parse("package:" + getPackageName()));
// startActivityForResult(intent, PERMISSION_REQ);
// }
//
// @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
// getPermissions();
// }
//
// @Override public AndroidInjector<Fragment> supportFragmentInjector() {
// return dispatchingAndroidInjector;
// }
//
// @Override public void onPermissionsGranted(int requestCode, List<String> perms) {
// //NO-OP
// }
//
// @Override public void onPermissionsDenied(int requestCode, List<String> perms) {
// if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
// showRationale();
// return;
// }
// finish();
// }
// }
| import android.content.Context;
import dagger.Module;
import dagger.Provides;
import in.arjsna.audiorecorder.activities.MainActivity;
import in.arjsna.audiorecorder.di.qualifiers.ActivityContext;
import in.arjsna.audiorecorder.di.scopes.ActivityScope; | package in.arjsna.audiorecorder.di;
@Module
public class MainActivityModule {
@Provides
@ActivityContext
@ActivityScope | // Path: app/src/main/java/in/arjsna/audiorecorder/activities/MainActivity.java
// public class MainActivity extends BaseActivity
// implements HasSupportFragmentInjector, EasyPermissions.PermissionCallbacks {
//
// private static final String LOG_TAG = MainActivity.class.getSimpleName();
// private static final int PERMISSION_REQ = 222;
//
// @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
//
// @Override public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.main_container, RecordFragment.newInstance())
// .commit();
// }
// getPermissions();
// }
//
// @Override public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_main, menu);
// return true;
// }
//
// @Override public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case R.id.action_settings:
// Intent i = new Intent(this, SettingsActivity.class);
// startActivity(i);
// return true;
// default:
// return super.onOptionsItemSelected(item);
// }
// }
//
// @TargetApi(23)
// private void getPermissions() {
// String[] permissions = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE,
// Manifest.permission.RECORD_AUDIO};
// if (!EasyPermissions.hasPermissions(MainActivity.this, permissions)) {
// EasyPermissions.requestPermissions(this, getString(R.string.permissions_required),
// PERMISSION_REQ, permissions);
// }
// }
//
// @TargetApi(23)
// @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
// @NonNull int[] grantResults) {
// EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
// }
//
// private void showRationale() {
// AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// builder.setTitle("Permissions Required")
// .setCancelable(false)
// .setMessage(
// getString(R.string.permissions_required))
// .setPositiveButton(R.string.dialog_action_ok, (dialog, which) -> {
// openSettingsPage();
// dialog.dismiss();
// })
// .setNegativeButton(R.string.dialog_action_cancel,
// (dialog, which) -> onBackPressed())
// .show();
// }
//
// private void openSettingsPage() {
// Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
// intent.setData(Uri.parse("package:" + getPackageName()));
// startActivityForResult(intent, PERMISSION_REQ);
// }
//
// @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
// getPermissions();
// }
//
// @Override public AndroidInjector<Fragment> supportFragmentInjector() {
// return dispatchingAndroidInjector;
// }
//
// @Override public void onPermissionsGranted(int requestCode, List<String> perms) {
// //NO-OP
// }
//
// @Override public void onPermissionsDenied(int requestCode, List<String> perms) {
// if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
// showRationale();
// return;
// }
// finish();
// }
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/di/MainActivityModule.java
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import in.arjsna.audiorecorder.activities.MainActivity;
import in.arjsna.audiorecorder.di.qualifiers.ActivityContext;
import in.arjsna.audiorecorder.di.scopes.ActivityScope;
package in.arjsna.audiorecorder.di;
@Module
public class MainActivityModule {
@Provides
@ActivityContext
@ActivityScope | Context provideActivityContext(MainActivity activity) { |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/di/ServiceBuilderModule.java | // Path: app/src/main/java/in/arjsna/audiorecorder/recordingservice/AudioRecordService.java
// public class AudioRecordService extends Service {
// private static final String LOG_TAG = "RecordingService";
//
// @Inject
// public AudioRecorder audioRecorder;
// @Inject
// public AudioRecordingDbmHandler handler;
// private ServiceBinder mIBinder;
// private NotificationManager mNotificationManager;
// private static final int NOTIFY_ID = 100;
// private AudioRecorder.RecordTime lastUpdated;
// private boolean mIsClientBound = false;
//
// @Override public IBinder onBind(Intent intent) {
// mIsClientBound = true;
// return mIBinder;
// }
//
// public boolean isRecording() {
// return audioRecorder.isRecording();
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// AndroidInjection.inject(this);
// handler.addRecorder(audioRecorder);
// mIBinder = new ServiceBinder();
// mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// }
//
// public AudioRecordingDbmHandler getHandler() {
// return handler;
// }
//
// @Override public int onStartCommand(Intent intent, int flags, int startId) {
// if (intent.getAction() != null) {
// switch (intent.getAction()) {
// case AppConstants.ACTION_PAUSE:
// pauseRecord();
// break;
// case AppConstants.ACTION_RESUME:
// resumeRecord();
// break;
// case AppConstants.ACTION_STOP:
// if (!mIsClientBound) {
// stopSelf();
// }
// }
// if (mIsClientBound) {
// intent.putExtra(AppConstants.ACTION_IN_SERVICE, intent.getAction());
// intent.setAction(AppConstants.ACTION_IN_SERVICE);
// LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
// }
// } else {
// startRecording();
// startForeground(NOTIFY_ID, createNotification(new AudioRecorder.RecordTime()));
// }
// return START_STICKY;
// }
//
// @Override public void onDestroy() {
// super.onDestroy();
// if (isRecording()) {
// stopRecodingAndRelease();
// }
// }
//
// private void stopRecodingAndRelease() {
// audioRecorder.finishRecord();
// handler.stop();
// }
//
// private void startRecording() {
// boolean prefHighQuality =
// Hawk.get(getApplicationContext().getString(R.string.pref_high_quality_key), false);
// audioRecorder.startRecord(
// prefHighQuality ? Constants.RECORDER_SAMPLE_RATE_HIGH : Constants.RECORDER_SAMPLE_RATE_LOW);
// handler.startDbmThread();
// audioRecorder.subscribeTimer(this::updateNotification);
// }
//
// public Disposable subscribeForTimer(Consumer<AudioRecorder.RecordTime> timerConsumer) {
// return audioRecorder.subscribeTimer(timerConsumer);
// }
//
// private void updateNotification(AudioRecorder.RecordTime recordTime) {
// mNotificationManager.notify(NOTIFY_ID, createNotification(recordTime));
// }
//
// private Notification createNotification(AudioRecorder.RecordTime recordTime) {
// lastUpdated = recordTime;
// NotificationCompat.Builder mBuilder =
// new NotificationCompat.Builder(getApplicationContext()).setSmallIcon(
// R.drawable.ic_media_record)
// .setContentTitle(getString(R.string.notification_recording))
// .setContentText(
// String.format(Locale.getDefault(), getString(R.string.record_time_format),
// recordTime.hours,
// recordTime.minutes,
// recordTime.seconds))
// .addAction(R.drawable.ic_media_stop, getString(R.string.stop_recording),
// getActionIntent(AppConstants.ACTION_STOP))
// .setOngoing(true);
// if (audioRecorder.isPaused()) {
// mBuilder.addAction(R.drawable.ic_media_record, getString(R.string.resume_recording_button),
// getActionIntent(AppConstants.ACTION_RESUME));
// } else {
// mBuilder.addAction(R.drawable.ic_media_pause, getString(R.string.pause_recording_button),
// getActionIntent(AppConstants.ACTION_PAUSE));
// }
// mBuilder.setContentIntent(PendingIntent.getActivities(getApplicationContext(), 0,
// new Intent[] {new Intent(getApplicationContext(), MainActivity.class)}, 0));
//
// return mBuilder.build();
// }
//
// public void pauseRecord() {
// audioRecorder.pauseRecord();
// updateNotification(lastUpdated);
// }
//
// public boolean isPaused() {
// return audioRecorder.isPaused();
// }
//
// public void resumeRecord() {
// audioRecorder.resumeRecord();
// }
//
// public class ServiceBinder extends Binder {
// public AudioRecordService getService() {
// return AudioRecordService.this;
// }
// }
//
// private PendingIntent getActionIntent(String action) {
// Intent pauseIntent = new Intent(this, AudioRecordService.class);
// pauseIntent.setAction(action);
// return PendingIntent.getService(this, 100, pauseIntent, 0);
// }
//
// @Override public boolean onUnbind(Intent intent) {
// mIsClientBound = false;
// return true;
// }
//
// @Override public void onRebind(Intent intent) {
// mIsClientBound = true;
// }
// }
| import dagger.Module;
import dagger.android.ContributesAndroidInjector;
import in.arjsna.audiorecorder.recordingservice.AudioRecordService; | package in.arjsna.audiorecorder.di;
/**
* Created by arjun on 12/1/17.
*/
@Module
abstract public class ServiceBuilderModule {
@ContributesAndroidInjector(modules = {ServiceModule.class}) | // Path: app/src/main/java/in/arjsna/audiorecorder/recordingservice/AudioRecordService.java
// public class AudioRecordService extends Service {
// private static final String LOG_TAG = "RecordingService";
//
// @Inject
// public AudioRecorder audioRecorder;
// @Inject
// public AudioRecordingDbmHandler handler;
// private ServiceBinder mIBinder;
// private NotificationManager mNotificationManager;
// private static final int NOTIFY_ID = 100;
// private AudioRecorder.RecordTime lastUpdated;
// private boolean mIsClientBound = false;
//
// @Override public IBinder onBind(Intent intent) {
// mIsClientBound = true;
// return mIBinder;
// }
//
// public boolean isRecording() {
// return audioRecorder.isRecording();
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// AndroidInjection.inject(this);
// handler.addRecorder(audioRecorder);
// mIBinder = new ServiceBinder();
// mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// }
//
// public AudioRecordingDbmHandler getHandler() {
// return handler;
// }
//
// @Override public int onStartCommand(Intent intent, int flags, int startId) {
// if (intent.getAction() != null) {
// switch (intent.getAction()) {
// case AppConstants.ACTION_PAUSE:
// pauseRecord();
// break;
// case AppConstants.ACTION_RESUME:
// resumeRecord();
// break;
// case AppConstants.ACTION_STOP:
// if (!mIsClientBound) {
// stopSelf();
// }
// }
// if (mIsClientBound) {
// intent.putExtra(AppConstants.ACTION_IN_SERVICE, intent.getAction());
// intent.setAction(AppConstants.ACTION_IN_SERVICE);
// LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
// }
// } else {
// startRecording();
// startForeground(NOTIFY_ID, createNotification(new AudioRecorder.RecordTime()));
// }
// return START_STICKY;
// }
//
// @Override public void onDestroy() {
// super.onDestroy();
// if (isRecording()) {
// stopRecodingAndRelease();
// }
// }
//
// private void stopRecodingAndRelease() {
// audioRecorder.finishRecord();
// handler.stop();
// }
//
// private void startRecording() {
// boolean prefHighQuality =
// Hawk.get(getApplicationContext().getString(R.string.pref_high_quality_key), false);
// audioRecorder.startRecord(
// prefHighQuality ? Constants.RECORDER_SAMPLE_RATE_HIGH : Constants.RECORDER_SAMPLE_RATE_LOW);
// handler.startDbmThread();
// audioRecorder.subscribeTimer(this::updateNotification);
// }
//
// public Disposable subscribeForTimer(Consumer<AudioRecorder.RecordTime> timerConsumer) {
// return audioRecorder.subscribeTimer(timerConsumer);
// }
//
// private void updateNotification(AudioRecorder.RecordTime recordTime) {
// mNotificationManager.notify(NOTIFY_ID, createNotification(recordTime));
// }
//
// private Notification createNotification(AudioRecorder.RecordTime recordTime) {
// lastUpdated = recordTime;
// NotificationCompat.Builder mBuilder =
// new NotificationCompat.Builder(getApplicationContext()).setSmallIcon(
// R.drawable.ic_media_record)
// .setContentTitle(getString(R.string.notification_recording))
// .setContentText(
// String.format(Locale.getDefault(), getString(R.string.record_time_format),
// recordTime.hours,
// recordTime.minutes,
// recordTime.seconds))
// .addAction(R.drawable.ic_media_stop, getString(R.string.stop_recording),
// getActionIntent(AppConstants.ACTION_STOP))
// .setOngoing(true);
// if (audioRecorder.isPaused()) {
// mBuilder.addAction(R.drawable.ic_media_record, getString(R.string.resume_recording_button),
// getActionIntent(AppConstants.ACTION_RESUME));
// } else {
// mBuilder.addAction(R.drawable.ic_media_pause, getString(R.string.pause_recording_button),
// getActionIntent(AppConstants.ACTION_PAUSE));
// }
// mBuilder.setContentIntent(PendingIntent.getActivities(getApplicationContext(), 0,
// new Intent[] {new Intent(getApplicationContext(), MainActivity.class)}, 0));
//
// return mBuilder.build();
// }
//
// public void pauseRecord() {
// audioRecorder.pauseRecord();
// updateNotification(lastUpdated);
// }
//
// public boolean isPaused() {
// return audioRecorder.isPaused();
// }
//
// public void resumeRecord() {
// audioRecorder.resumeRecord();
// }
//
// public class ServiceBinder extends Binder {
// public AudioRecordService getService() {
// return AudioRecordService.this;
// }
// }
//
// private PendingIntent getActionIntent(String action) {
// Intent pauseIntent = new Intent(this, AudioRecordService.class);
// pauseIntent.setAction(action);
// return PendingIntent.getService(this, 100, pauseIntent, 0);
// }
//
// @Override public boolean onUnbind(Intent intent) {
// mIsClientBound = false;
// return true;
// }
//
// @Override public void onRebind(Intent intent) {
// mIsClientBound = true;
// }
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/di/ServiceBuilderModule.java
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
import in.arjsna.audiorecorder.recordingservice.AudioRecordService;
package in.arjsna.audiorecorder.di;
/**
* Created by arjun on 12/1/17.
*/
@Module
abstract public class ServiceBuilderModule {
@ContributesAndroidInjector(modules = {ServiceModule.class}) | abstract AudioRecordService contributeAudioRecordService(); |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/di/ActivityBuilderModule.java | // Path: app/src/main/java/in/arjsna/audiorecorder/activities/MainActivity.java
// public class MainActivity extends BaseActivity
// implements HasSupportFragmentInjector, EasyPermissions.PermissionCallbacks {
//
// private static final String LOG_TAG = MainActivity.class.getSimpleName();
// private static final int PERMISSION_REQ = 222;
//
// @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
//
// @Override public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.main_container, RecordFragment.newInstance())
// .commit();
// }
// getPermissions();
// }
//
// @Override public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_main, menu);
// return true;
// }
//
// @Override public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case R.id.action_settings:
// Intent i = new Intent(this, SettingsActivity.class);
// startActivity(i);
// return true;
// default:
// return super.onOptionsItemSelected(item);
// }
// }
//
// @TargetApi(23)
// private void getPermissions() {
// String[] permissions = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE,
// Manifest.permission.RECORD_AUDIO};
// if (!EasyPermissions.hasPermissions(MainActivity.this, permissions)) {
// EasyPermissions.requestPermissions(this, getString(R.string.permissions_required),
// PERMISSION_REQ, permissions);
// }
// }
//
// @TargetApi(23)
// @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
// @NonNull int[] grantResults) {
// EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
// }
//
// private void showRationale() {
// AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// builder.setTitle("Permissions Required")
// .setCancelable(false)
// .setMessage(
// getString(R.string.permissions_required))
// .setPositiveButton(R.string.dialog_action_ok, (dialog, which) -> {
// openSettingsPage();
// dialog.dismiss();
// })
// .setNegativeButton(R.string.dialog_action_cancel,
// (dialog, which) -> onBackPressed())
// .show();
// }
//
// private void openSettingsPage() {
// Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
// intent.setData(Uri.parse("package:" + getPackageName()));
// startActivityForResult(intent, PERMISSION_REQ);
// }
//
// @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
// getPermissions();
// }
//
// @Override public AndroidInjector<Fragment> supportFragmentInjector() {
// return dispatchingAndroidInjector;
// }
//
// @Override public void onPermissionsGranted(int requestCode, List<String> perms) {
// //NO-OP
// }
//
// @Override public void onPermissionsDenied(int requestCode, List<String> perms) {
// if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
// showRationale();
// return;
// }
// finish();
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/activities/PlayListActivity.java
// public class PlayListActivity extends BaseActivity implements HasSupportFragmentInjector {
//
// @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
//
// @Override public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_record_list);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// ActionBar actionBar = getSupportActionBar();
// if (actionBar != null) {
// actionBar.setTitle(R.string.tab_title_saved_recordings);
// actionBar.setDisplayHomeAsUpEnabled(true);
// actionBar.setDisplayShowHomeEnabled(true);
// }
// setNavBarColor();
//
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.record_list_container, PlayListFragment.newInstance())
// .commit();
// }
// }
//
// @Override public AndroidInjector<Fragment> supportFragmentInjector() {
// return dispatchingAndroidInjector;
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/activities/SettingsActivity.java
// public class SettingsActivity extends BaseActivity {
// @Override public void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_preferences);
//
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// ActionBar actionBar = getSupportActionBar();
// if (actionBar != null) {
// actionBar.setTitle(R.string.action_settings);
// actionBar.setDisplayHomeAsUpEnabled(true);
// actionBar.setDisplayShowHomeEnabled(true);
// }
//
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.container, new SettingsFragment())
// .commit();
// }
// }
| import dagger.Module;
import dagger.android.ContributesAndroidInjector;
import in.arjsna.audiorecorder.activities.MainActivity;
import in.arjsna.audiorecorder.activities.PlayListActivity;
import in.arjsna.audiorecorder.activities.SettingsActivity;
import in.arjsna.audiorecorder.di.scopes.ActivityScope; | package in.arjsna.audiorecorder.di;
/**
* Created by arjun on 12/1/17.
*/
@Module
abstract class ActivityBuilderModule {
@ActivityScope
@ContributesAndroidInjector(modules = {MainActivityModule.class, RecordFragmentBuilderModule.class}) | // Path: app/src/main/java/in/arjsna/audiorecorder/activities/MainActivity.java
// public class MainActivity extends BaseActivity
// implements HasSupportFragmentInjector, EasyPermissions.PermissionCallbacks {
//
// private static final String LOG_TAG = MainActivity.class.getSimpleName();
// private static final int PERMISSION_REQ = 222;
//
// @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
//
// @Override public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.main_container, RecordFragment.newInstance())
// .commit();
// }
// getPermissions();
// }
//
// @Override public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_main, menu);
// return true;
// }
//
// @Override public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case R.id.action_settings:
// Intent i = new Intent(this, SettingsActivity.class);
// startActivity(i);
// return true;
// default:
// return super.onOptionsItemSelected(item);
// }
// }
//
// @TargetApi(23)
// private void getPermissions() {
// String[] permissions = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE,
// Manifest.permission.RECORD_AUDIO};
// if (!EasyPermissions.hasPermissions(MainActivity.this, permissions)) {
// EasyPermissions.requestPermissions(this, getString(R.string.permissions_required),
// PERMISSION_REQ, permissions);
// }
// }
//
// @TargetApi(23)
// @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
// @NonNull int[] grantResults) {
// EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
// }
//
// private void showRationale() {
// AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// builder.setTitle("Permissions Required")
// .setCancelable(false)
// .setMessage(
// getString(R.string.permissions_required))
// .setPositiveButton(R.string.dialog_action_ok, (dialog, which) -> {
// openSettingsPage();
// dialog.dismiss();
// })
// .setNegativeButton(R.string.dialog_action_cancel,
// (dialog, which) -> onBackPressed())
// .show();
// }
//
// private void openSettingsPage() {
// Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
// intent.setData(Uri.parse("package:" + getPackageName()));
// startActivityForResult(intent, PERMISSION_REQ);
// }
//
// @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
// getPermissions();
// }
//
// @Override public AndroidInjector<Fragment> supportFragmentInjector() {
// return dispatchingAndroidInjector;
// }
//
// @Override public void onPermissionsGranted(int requestCode, List<String> perms) {
// //NO-OP
// }
//
// @Override public void onPermissionsDenied(int requestCode, List<String> perms) {
// if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
// showRationale();
// return;
// }
// finish();
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/activities/PlayListActivity.java
// public class PlayListActivity extends BaseActivity implements HasSupportFragmentInjector {
//
// @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
//
// @Override public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_record_list);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// ActionBar actionBar = getSupportActionBar();
// if (actionBar != null) {
// actionBar.setTitle(R.string.tab_title_saved_recordings);
// actionBar.setDisplayHomeAsUpEnabled(true);
// actionBar.setDisplayShowHomeEnabled(true);
// }
// setNavBarColor();
//
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.record_list_container, PlayListFragment.newInstance())
// .commit();
// }
// }
//
// @Override public AndroidInjector<Fragment> supportFragmentInjector() {
// return dispatchingAndroidInjector;
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/activities/SettingsActivity.java
// public class SettingsActivity extends BaseActivity {
// @Override public void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_preferences);
//
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// ActionBar actionBar = getSupportActionBar();
// if (actionBar != null) {
// actionBar.setTitle(R.string.action_settings);
// actionBar.setDisplayHomeAsUpEnabled(true);
// actionBar.setDisplayShowHomeEnabled(true);
// }
//
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.container, new SettingsFragment())
// .commit();
// }
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/di/ActivityBuilderModule.java
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
import in.arjsna.audiorecorder.activities.MainActivity;
import in.arjsna.audiorecorder.activities.PlayListActivity;
import in.arjsna.audiorecorder.activities.SettingsActivity;
import in.arjsna.audiorecorder.di.scopes.ActivityScope;
package in.arjsna.audiorecorder.di;
/**
* Created by arjun on 12/1/17.
*/
@Module
abstract class ActivityBuilderModule {
@ActivityScope
@ContributesAndroidInjector(modules = {MainActivityModule.class, RecordFragmentBuilderModule.class}) | abstract MainActivity contributeMainActivity(); |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/libs/FillSeekBar.java | // Path: app/src/main/java/in/arjsna/audiorecorder/theme/ThemedActivity.java
// public abstract class ThemedActivity extends AppCompatActivity implements UiElementInizializer {
//
// private ThemeHelper themeHelper;
//
// private boolean coloredNavBar;
// private boolean applyThemeSingleImgAct;
// private boolean customIconColor;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// themeHelper = ThemeHelper.getInstance(getApplicationContext());
// }
//
// @Override
// public void onResume() {
// super.onResume();
// updateTheme();
// updateUiElements();
// setStatusBarColor();
// }
//
// public ThemeHelper getThemeHelper() {
// return themeHelper;
// }
//
// public void updateTheme() {
// themeHelper.updateTheme();
// applyThemeSingleImgAct = Hawk.get("apply_theme_img_act", true);
// }
//
// @CallSuper
// @Override
// public void updateUiElements() {
// setStatusBarColor();
// for (View view : ViewUtil.getAllChildren(findViewById(android.R.id.content))) {
// if (view instanceof Themed) ((Themed) view).refreshTheme(getThemeHelper());
// }
// }
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP) protected void setNavBarColor() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// if (isNavigationBarColored()) {
// getWindow().setNavigationBarColor(getPrimaryColor());
// } else {
// getWindow().setNavigationBarColor(
// ContextCompat.getColor(getApplicationContext(), R.color.md_black_1000));
// }
// }
// }
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// protected void setStatusBarColor() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// getWindow().setStatusBarColor(ColorPalette.getObscuredColor(getPrimaryColor()));
// }
// }
//
// protected void setScrollViewColor(ScrollView scr) {
// themeHelper.setScrollViewColor(scr);
// }
//
// public boolean isNavigationBarColored() {
// return coloredNavBar;
// }
//
// public boolean themeOnSingleImgAct() {
// return applyThemeSingleImgAct;
// }
//
// public void setBaseTheme(Theme baseTheme) {
// themeHelper.setBaseTheme(baseTheme);
// }
//
// public void themeSeekBar(SeekBar bar) {
// themeHelper.themeSeekBar(bar);
// }
//
// public int getPrimaryColor() {
// return themeHelper.getPrimaryColor();
// }
//
// public int getAccentColor() {
// return themeHelper.getAccentColor();
// }
//
// public Theme getBaseTheme() {
// return themeHelper.getBaseTheme();
// }
//
// public int getBackgroundColor() {
// return themeHelper.getBackgroundColor();
// }
//
// protected int getInvertedBackgroundColor() {
// return themeHelper.getInvertedBackgroundColor();
// }
//
// public int getTextColor() {
// return themeHelper.getTextColor();
// }
//
// public int getSubTextColor() {
// return themeHelper.getSubTextColor();
// }
//
// public int getCardBackgroundColor() {
// return themeHelper.getCardBackgroundColor();
// }
//
// protected int getDrawerBackground() {
// return themeHelper.getDrawerBackground();
// }
//
// protected int getDefaultThemeToolbarColor3th() {
// return themeHelper.getDefaultThemeToolbarColor3th();
// }
//
// public void themeRadioButton(RadioButton radioButton) {
// themeHelper.themeRadioButton(radioButton);
// }
//
// public void themeCheckBox(CheckBox chk) {
// themeHelper.themeCheckBox(chk);
// }
//
// protected void themeButton(Button btn) {
// themeHelper.themeButton(btn);
// }
//
// public void setSwitchColor(int color, SwitchCompat... sw) {
// for (SwitchCompat switchCompat : sw)
// themeHelper.setSwitchCompactColor(switchCompat, color);
// }
//
// public void setTextViewColor(int color, TextView... textViews) {
// for (TextView txt : textViews)
// themeHelper.setTextViewColor(txt, color);
// }
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import in.arjsna.audiorecorder.R;
import in.arjsna.audiorecorder.theme.ThemedActivity; | package in.arjsna.audiorecorder.libs;
public class FillSeekBar extends FrameLayout {
private long mProgress = 0;
private Solid mSolid;
private final int DEFAULT_FILL_COLOR = Color.WHITE;
private double mMaxValue = 1.0;
public FillSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
//load styled attributes.
final TypedArray attributes = context.getTheme()
.obtainStyledAttributes(attrs, R.styleable.FillSeekBar, R.attr.fillseekbarViewStyle, 0); | // Path: app/src/main/java/in/arjsna/audiorecorder/theme/ThemedActivity.java
// public abstract class ThemedActivity extends AppCompatActivity implements UiElementInizializer {
//
// private ThemeHelper themeHelper;
//
// private boolean coloredNavBar;
// private boolean applyThemeSingleImgAct;
// private boolean customIconColor;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// themeHelper = ThemeHelper.getInstance(getApplicationContext());
// }
//
// @Override
// public void onResume() {
// super.onResume();
// updateTheme();
// updateUiElements();
// setStatusBarColor();
// }
//
// public ThemeHelper getThemeHelper() {
// return themeHelper;
// }
//
// public void updateTheme() {
// themeHelper.updateTheme();
// applyThemeSingleImgAct = Hawk.get("apply_theme_img_act", true);
// }
//
// @CallSuper
// @Override
// public void updateUiElements() {
// setStatusBarColor();
// for (View view : ViewUtil.getAllChildren(findViewById(android.R.id.content))) {
// if (view instanceof Themed) ((Themed) view).refreshTheme(getThemeHelper());
// }
// }
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP) protected void setNavBarColor() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// if (isNavigationBarColored()) {
// getWindow().setNavigationBarColor(getPrimaryColor());
// } else {
// getWindow().setNavigationBarColor(
// ContextCompat.getColor(getApplicationContext(), R.color.md_black_1000));
// }
// }
// }
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// protected void setStatusBarColor() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// getWindow().setStatusBarColor(ColorPalette.getObscuredColor(getPrimaryColor()));
// }
// }
//
// protected void setScrollViewColor(ScrollView scr) {
// themeHelper.setScrollViewColor(scr);
// }
//
// public boolean isNavigationBarColored() {
// return coloredNavBar;
// }
//
// public boolean themeOnSingleImgAct() {
// return applyThemeSingleImgAct;
// }
//
// public void setBaseTheme(Theme baseTheme) {
// themeHelper.setBaseTheme(baseTheme);
// }
//
// public void themeSeekBar(SeekBar bar) {
// themeHelper.themeSeekBar(bar);
// }
//
// public int getPrimaryColor() {
// return themeHelper.getPrimaryColor();
// }
//
// public int getAccentColor() {
// return themeHelper.getAccentColor();
// }
//
// public Theme getBaseTheme() {
// return themeHelper.getBaseTheme();
// }
//
// public int getBackgroundColor() {
// return themeHelper.getBackgroundColor();
// }
//
// protected int getInvertedBackgroundColor() {
// return themeHelper.getInvertedBackgroundColor();
// }
//
// public int getTextColor() {
// return themeHelper.getTextColor();
// }
//
// public int getSubTextColor() {
// return themeHelper.getSubTextColor();
// }
//
// public int getCardBackgroundColor() {
// return themeHelper.getCardBackgroundColor();
// }
//
// protected int getDrawerBackground() {
// return themeHelper.getDrawerBackground();
// }
//
// protected int getDefaultThemeToolbarColor3th() {
// return themeHelper.getDefaultThemeToolbarColor3th();
// }
//
// public void themeRadioButton(RadioButton radioButton) {
// themeHelper.themeRadioButton(radioButton);
// }
//
// public void themeCheckBox(CheckBox chk) {
// themeHelper.themeCheckBox(chk);
// }
//
// protected void themeButton(Button btn) {
// themeHelper.themeButton(btn);
// }
//
// public void setSwitchColor(int color, SwitchCompat... sw) {
// for (SwitchCompat switchCompat : sw)
// themeHelper.setSwitchCompactColor(switchCompat, color);
// }
//
// public void setTextViewColor(int color, TextView... textViews) {
// for (TextView txt : textViews)
// themeHelper.setTextViewColor(txt, color);
// }
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/libs/FillSeekBar.java
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import in.arjsna.audiorecorder.R;
import in.arjsna.audiorecorder.theme.ThemedActivity;
package in.arjsna.audiorecorder.libs;
public class FillSeekBar extends FrameLayout {
private long mProgress = 0;
private Solid mSolid;
private final int DEFAULT_FILL_COLOR = Color.WHITE;
private double mMaxValue = 1.0;
public FillSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
//load styled attributes.
final TypedArray attributes = context.getTheme()
.obtainStyledAttributes(attrs, R.styleable.FillSeekBar, R.attr.fillseekbarViewStyle, 0); | int mFillColor = ((ThemedActivity) context).getPrimaryColor(); |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/playlist/PlayListPresenter.java | // Path: app/src/main/java/in/arjsna/audiorecorder/db/RecordingItem.java
// @Entity(tableName = "recordings")
// public class RecordingItem implements Parcelable {
// @PrimaryKey(autoGenerate = true)
// private int id;
// private String mName; // file name
// private String mFilePath; //file path
// //private int mId; //id in database
// private long mLength; // length of recording in seconds
// private long mTime; // date/time of the recording
//
// @Ignore
// public boolean isPlaying = false;
//
// @Ignore
// public boolean isPaused;
// @Ignore
// public long playProgress;
//
// public RecordingItem() {
// }
//
// private RecordingItem(Parcel in) {
// mName = in.readString();
// mFilePath = in.readString();
// //mId = in.readInt();
// mLength = in.readLong();
// mTime = in.readLong();
// }
//
// public String getFilePath() {
// return mFilePath;
// }
//
// public void setFilePath(String filePath) {
// mFilePath = filePath;
// }
//
// public long getLength() {
// return mLength;
// }
//
// public void setLength(long length) {
// mLength = length;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// mName = name;
// }
//
// public long getTime() {
// return mTime;
// }
//
// public void setTime(long time) {
// mTime = time;
// }
//
// public static final Parcelable.Creator<RecordingItem> CREATOR =
// new Parcelable.Creator<RecordingItem>() {
// public RecordingItem createFromParcel(Parcel in) {
// return new RecordingItem(in);
// }
//
// public RecordingItem[] newArray(int size) {
// return new RecordingItem[size];
// }
// };
//
// @Override public void writeToParcel(Parcel dest, int flags) {
// //dest.writeInt(mId);
// dest.writeLong(mLength);
// dest.writeLong(mTime);
// dest.writeString(mFilePath);
// dest.writeString(mName);
// }
//
// @Override public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/mvpbase/IMVPPresenter.java
// public interface IMVPPresenter<V extends IMVPView> {
// void onAttach(V view);
//
// void onDetach();
// }
| import in.arjsna.audiorecorder.db.RecordingItem;
import in.arjsna.audiorecorder.mvpbase.IMVPPresenter; | package in.arjsna.audiorecorder.playlist;
public interface PlayListPresenter<V extends PlayListMVPView> extends IMVPPresenter<V> {
void onViewInitialised();
void renameFile(int position, String value);
void deleteFile(int position);
| // Path: app/src/main/java/in/arjsna/audiorecorder/db/RecordingItem.java
// @Entity(tableName = "recordings")
// public class RecordingItem implements Parcelable {
// @PrimaryKey(autoGenerate = true)
// private int id;
// private String mName; // file name
// private String mFilePath; //file path
// //private int mId; //id in database
// private long mLength; // length of recording in seconds
// private long mTime; // date/time of the recording
//
// @Ignore
// public boolean isPlaying = false;
//
// @Ignore
// public boolean isPaused;
// @Ignore
// public long playProgress;
//
// public RecordingItem() {
// }
//
// private RecordingItem(Parcel in) {
// mName = in.readString();
// mFilePath = in.readString();
// //mId = in.readInt();
// mLength = in.readLong();
// mTime = in.readLong();
// }
//
// public String getFilePath() {
// return mFilePath;
// }
//
// public void setFilePath(String filePath) {
// mFilePath = filePath;
// }
//
// public long getLength() {
// return mLength;
// }
//
// public void setLength(long length) {
// mLength = length;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// mName = name;
// }
//
// public long getTime() {
// return mTime;
// }
//
// public void setTime(long time) {
// mTime = time;
// }
//
// public static final Parcelable.Creator<RecordingItem> CREATOR =
// new Parcelable.Creator<RecordingItem>() {
// public RecordingItem createFromParcel(Parcel in) {
// return new RecordingItem(in);
// }
//
// public RecordingItem[] newArray(int size) {
// return new RecordingItem[size];
// }
// };
//
// @Override public void writeToParcel(Parcel dest, int flags) {
// //dest.writeInt(mId);
// dest.writeLong(mLength);
// dest.writeLong(mTime);
// dest.writeString(mFilePath);
// dest.writeString(mName);
// }
//
// @Override public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/mvpbase/IMVPPresenter.java
// public interface IMVPPresenter<V extends IMVPView> {
// void onAttach(V view);
//
// void onDetach();
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/playlist/PlayListPresenter.java
import in.arjsna.audiorecorder.db.RecordingItem;
import in.arjsna.audiorecorder.mvpbase.IMVPPresenter;
package in.arjsna.audiorecorder.playlist;
public interface PlayListPresenter<V extends PlayListMVPView> extends IMVPPresenter<V> {
void onViewInitialised();
void renameFile(int position, String value);
void deleteFile(int position);
| RecordingItem getListItemAt(int position); |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/activities/SettingsActivity.java | // Path: app/src/main/java/in/arjsna/audiorecorder/mvpbase/BaseActivity.java
// public abstract class BaseActivity extends ThemedActivity implements IMVPView {
// @Override public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// AndroidInjection.inject(this);
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/settings/SettingsFragment.java
// public class SettingsFragment extends ThemedFragment {
//
// private View rootView;
// private SettingBasic themeSetting;
// private ThemedActivity parent;
// private SettingBasic rateApp;
//
// @Nullable @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
// @Nullable Bundle savedInstanceState) {
// rootView = inflater.inflate(R.layout.fragment_settings, container, false);
// parent = (ThemedActivity) getActivity();
// initViews();
// bindEvents();
// return rootView;
// }
//
// private void bindEvents() {
// themeSetting.setOnClickListener(v -> {
// final int originalColor = getPrimaryColor();
// new ColorsSetting((ThemedActivity) getActivity()).chooseColor(R.string.primary_color,
// new ColorsSetting.ColorChooser() {
// @Override
// public void onColorSelected(ColorsSetting.SelectedColor color) {
// Hawk.put(getString(R.string.preference_primary_color), color.colorPrimary);
// Hawk.put(getString(R.string.preference_accent_color), color.colorPrimary);
// Hawk.put(getString(R.string.preference_layer_colors), color.shades);
// parent.updateTheme();
// parent.updateUiElements();
// }
//
// @Override
// public void onDialogDismiss() {
// Hawk.put(getString(R.string.preference_primary_color), originalColor);
// Hawk.put(getString(R.string.preference_accent_color), originalColor);
// parent.updateTheme();
// parent.updateUiElements();
// }
//
// @Override
// public void onColorChanged(int color) {
// Hawk.put(getString(R.string.preference_primary_color), color);
// Hawk.put(getString(R.string.preference_accent_color), color);
// parent.updateTheme();
// parent.updateUiElements();
// }
// }, getPrimaryColor());
// });
// rateApp.setOnClickListener(v -> {
// Uri uri = Uri.parse("market://details?id=" + getActivity().getPackageName());
// Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
// Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
// Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
// try {
// startActivity(goToMarket);
// } catch (ActivityNotFoundException e) {
// startActivity(new Intent(Intent.ACTION_VIEW,
// Uri.parse(
// "http://play.google.com/store/apps/details?id=" + getActivity().getPackageName())));
// }
// });
// }
//
// private void initViews() {
// themeSetting = rootView.findViewById(R.id.theme_settings);
// rateApp = rootView.findViewById(R.id.rate_app);
// }
//
// //Preference aboutPref = findPreference(getString(R.string.pref_about_key));
// // aboutPref.setSummary(getString(R.string.pref_about_desc, BuildConfig.VERSION_NAME));
// // aboutPref.setOnPreferenceClickListener(preference -> {
// // LicensesFragment licensesFragment = new LicensesFragment();
// // licensesFragment.show(
// // ((SettingsActivity) getActivity()).getSupportFragmentManager(),
// // "dialog_licenses");
// // return true;
// //});
//
// @Override public void refreshTheme(ThemeHelper themeHelper) {
//
// }
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import in.arjsna.audiorecorder.R;
import in.arjsna.audiorecorder.mvpbase.BaseActivity;
import in.arjsna.audiorecorder.settings.SettingsFragment; | package in.arjsna.audiorecorder.activities;
public class SettingsActivity extends BaseActivity {
@Override public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.action_settings);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
getSupportFragmentManager().beginTransaction() | // Path: app/src/main/java/in/arjsna/audiorecorder/mvpbase/BaseActivity.java
// public abstract class BaseActivity extends ThemedActivity implements IMVPView {
// @Override public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// AndroidInjection.inject(this);
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/settings/SettingsFragment.java
// public class SettingsFragment extends ThemedFragment {
//
// private View rootView;
// private SettingBasic themeSetting;
// private ThemedActivity parent;
// private SettingBasic rateApp;
//
// @Nullable @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
// @Nullable Bundle savedInstanceState) {
// rootView = inflater.inflate(R.layout.fragment_settings, container, false);
// parent = (ThemedActivity) getActivity();
// initViews();
// bindEvents();
// return rootView;
// }
//
// private void bindEvents() {
// themeSetting.setOnClickListener(v -> {
// final int originalColor = getPrimaryColor();
// new ColorsSetting((ThemedActivity) getActivity()).chooseColor(R.string.primary_color,
// new ColorsSetting.ColorChooser() {
// @Override
// public void onColorSelected(ColorsSetting.SelectedColor color) {
// Hawk.put(getString(R.string.preference_primary_color), color.colorPrimary);
// Hawk.put(getString(R.string.preference_accent_color), color.colorPrimary);
// Hawk.put(getString(R.string.preference_layer_colors), color.shades);
// parent.updateTheme();
// parent.updateUiElements();
// }
//
// @Override
// public void onDialogDismiss() {
// Hawk.put(getString(R.string.preference_primary_color), originalColor);
// Hawk.put(getString(R.string.preference_accent_color), originalColor);
// parent.updateTheme();
// parent.updateUiElements();
// }
//
// @Override
// public void onColorChanged(int color) {
// Hawk.put(getString(R.string.preference_primary_color), color);
// Hawk.put(getString(R.string.preference_accent_color), color);
// parent.updateTheme();
// parent.updateUiElements();
// }
// }, getPrimaryColor());
// });
// rateApp.setOnClickListener(v -> {
// Uri uri = Uri.parse("market://details?id=" + getActivity().getPackageName());
// Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
// Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
// Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
// try {
// startActivity(goToMarket);
// } catch (ActivityNotFoundException e) {
// startActivity(new Intent(Intent.ACTION_VIEW,
// Uri.parse(
// "http://play.google.com/store/apps/details?id=" + getActivity().getPackageName())));
// }
// });
// }
//
// private void initViews() {
// themeSetting = rootView.findViewById(R.id.theme_settings);
// rateApp = rootView.findViewById(R.id.rate_app);
// }
//
// //Preference aboutPref = findPreference(getString(R.string.pref_about_key));
// // aboutPref.setSummary(getString(R.string.pref_about_desc, BuildConfig.VERSION_NAME));
// // aboutPref.setOnPreferenceClickListener(preference -> {
// // LicensesFragment licensesFragment = new LicensesFragment();
// // licensesFragment.show(
// // ((SettingsActivity) getActivity()).getSupportFragmentManager(),
// // "dialog_licenses");
// // return true;
// //});
//
// @Override public void refreshTheme(ThemeHelper themeHelper) {
//
// }
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/activities/SettingsActivity.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import in.arjsna.audiorecorder.R;
import in.arjsna.audiorecorder.mvpbase.BaseActivity;
import in.arjsna.audiorecorder.settings.SettingsFragment;
package in.arjsna.audiorecorder.activities;
public class SettingsActivity extends BaseActivity {
@Override public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.action_settings);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
getSupportFragmentManager().beginTransaction() | .replace(R.id.container, new SettingsFragment()) |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/di/ApplicationModule.java | // Path: app/src/main/java/in/arjsna/audiorecorder/db/AppDataBase.java
// @Database(entities = { RecordingItem.class }, version = 1, exportSchema = false)
// public abstract class AppDataBase extends RoomDatabase {
// public abstract RecordItemDao recordItemDao();
//
// private static final String DATABASE_NAME = "saved_recordings.db";
//
// private static AppDataBase appDataBaseInstance;
// private RecordItemDataSource recordItemDataSource;
//
// public static AppDataBase getInstance(Context context) {
// if (appDataBaseInstance == null) {
// appDataBaseInstance = Room.databaseBuilder(context, AppDataBase.class, DATABASE_NAME).build();
// appDataBaseInstance.recordItemDataSource =
// new RecordItemDataSource(appDataBaseInstance.recordItemDao());
// } return appDataBaseInstance;
// }
//
// public RecordItemDataSource getRecordItemDataSource() {
// return recordItemDataSource;
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/db/RecordItemDataSource.java
// public class RecordItemDataSource {
// private RecordItemDao recordItemDao;
//
// public RecordItemDataSource(RecordItemDao recordItemDao) {
// this.recordItemDao = recordItemDao;
// }
//
// public Single<List<RecordingItem>> getAllRecordings() {
// return Single.fromCallable(() -> recordItemDao.getAllRecordings()).subscribeOn(Schedulers.io());
// }
//
// public Single<Boolean> insertNewRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.insertNewRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public long insertNewRecordItem(RecordingItem recordingItem) {
// return recordItemDao.insertNewRecordItem(recordingItem);
// }
//
// public Single<Boolean> deleteRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.deleteRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public int deleteRecordItem(RecordingItem recordingItem) {
// return recordItemDao.deleteRecordItem(recordingItem);
// }
//
// public Single<Boolean> updateRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.updateRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public int updateRecordItem(RecordingItem recordingItem) {
// return recordItemDao.updateRecordItem(recordingItem);
// }
//
// public int getRecordingsCount() {
// return recordItemDao.getCount();
// }
// }
| import android.app.Application;
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import in.arjsna.audiorecorder.db.AppDataBase;
import in.arjsna.audiorecorder.db.RecordItemDataSource;
import in.arjsna.audiorecorder.di.qualifiers.ApplicationContext;
import javax.inject.Singleton; | package in.arjsna.audiorecorder.di;
@Module
public class ApplicationModule {
@Provides
@ApplicationContext
@Singleton
Context provideApplicationContext(Application application) {
return application.getApplicationContext();
}
@Provides
@Singleton | // Path: app/src/main/java/in/arjsna/audiorecorder/db/AppDataBase.java
// @Database(entities = { RecordingItem.class }, version = 1, exportSchema = false)
// public abstract class AppDataBase extends RoomDatabase {
// public abstract RecordItemDao recordItemDao();
//
// private static final String DATABASE_NAME = "saved_recordings.db";
//
// private static AppDataBase appDataBaseInstance;
// private RecordItemDataSource recordItemDataSource;
//
// public static AppDataBase getInstance(Context context) {
// if (appDataBaseInstance == null) {
// appDataBaseInstance = Room.databaseBuilder(context, AppDataBase.class, DATABASE_NAME).build();
// appDataBaseInstance.recordItemDataSource =
// new RecordItemDataSource(appDataBaseInstance.recordItemDao());
// } return appDataBaseInstance;
// }
//
// public RecordItemDataSource getRecordItemDataSource() {
// return recordItemDataSource;
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/db/RecordItemDataSource.java
// public class RecordItemDataSource {
// private RecordItemDao recordItemDao;
//
// public RecordItemDataSource(RecordItemDao recordItemDao) {
// this.recordItemDao = recordItemDao;
// }
//
// public Single<List<RecordingItem>> getAllRecordings() {
// return Single.fromCallable(() -> recordItemDao.getAllRecordings()).subscribeOn(Schedulers.io());
// }
//
// public Single<Boolean> insertNewRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.insertNewRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public long insertNewRecordItem(RecordingItem recordingItem) {
// return recordItemDao.insertNewRecordItem(recordingItem);
// }
//
// public Single<Boolean> deleteRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.deleteRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public int deleteRecordItem(RecordingItem recordingItem) {
// return recordItemDao.deleteRecordItem(recordingItem);
// }
//
// public Single<Boolean> updateRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.updateRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public int updateRecordItem(RecordingItem recordingItem) {
// return recordItemDao.updateRecordItem(recordingItem);
// }
//
// public int getRecordingsCount() {
// return recordItemDao.getCount();
// }
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/di/ApplicationModule.java
import android.app.Application;
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import in.arjsna.audiorecorder.db.AppDataBase;
import in.arjsna.audiorecorder.db.RecordItemDataSource;
import in.arjsna.audiorecorder.di.qualifiers.ApplicationContext;
import javax.inject.Singleton;
package in.arjsna.audiorecorder.di;
@Module
public class ApplicationModule {
@Provides
@ApplicationContext
@Singleton
Context provideApplicationContext(Application application) {
return application.getApplicationContext();
}
@Provides
@Singleton | RecordItemDataSource provideRecordItemDataSource(@ApplicationContext Context context) { |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/di/ApplicationModule.java | // Path: app/src/main/java/in/arjsna/audiorecorder/db/AppDataBase.java
// @Database(entities = { RecordingItem.class }, version = 1, exportSchema = false)
// public abstract class AppDataBase extends RoomDatabase {
// public abstract RecordItemDao recordItemDao();
//
// private static final String DATABASE_NAME = "saved_recordings.db";
//
// private static AppDataBase appDataBaseInstance;
// private RecordItemDataSource recordItemDataSource;
//
// public static AppDataBase getInstance(Context context) {
// if (appDataBaseInstance == null) {
// appDataBaseInstance = Room.databaseBuilder(context, AppDataBase.class, DATABASE_NAME).build();
// appDataBaseInstance.recordItemDataSource =
// new RecordItemDataSource(appDataBaseInstance.recordItemDao());
// } return appDataBaseInstance;
// }
//
// public RecordItemDataSource getRecordItemDataSource() {
// return recordItemDataSource;
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/db/RecordItemDataSource.java
// public class RecordItemDataSource {
// private RecordItemDao recordItemDao;
//
// public RecordItemDataSource(RecordItemDao recordItemDao) {
// this.recordItemDao = recordItemDao;
// }
//
// public Single<List<RecordingItem>> getAllRecordings() {
// return Single.fromCallable(() -> recordItemDao.getAllRecordings()).subscribeOn(Schedulers.io());
// }
//
// public Single<Boolean> insertNewRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.insertNewRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public long insertNewRecordItem(RecordingItem recordingItem) {
// return recordItemDao.insertNewRecordItem(recordingItem);
// }
//
// public Single<Boolean> deleteRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.deleteRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public int deleteRecordItem(RecordingItem recordingItem) {
// return recordItemDao.deleteRecordItem(recordingItem);
// }
//
// public Single<Boolean> updateRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.updateRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public int updateRecordItem(RecordingItem recordingItem) {
// return recordItemDao.updateRecordItem(recordingItem);
// }
//
// public int getRecordingsCount() {
// return recordItemDao.getCount();
// }
// }
| import android.app.Application;
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import in.arjsna.audiorecorder.db.AppDataBase;
import in.arjsna.audiorecorder.db.RecordItemDataSource;
import in.arjsna.audiorecorder.di.qualifiers.ApplicationContext;
import javax.inject.Singleton; | package in.arjsna.audiorecorder.di;
@Module
public class ApplicationModule {
@Provides
@ApplicationContext
@Singleton
Context provideApplicationContext(Application application) {
return application.getApplicationContext();
}
@Provides
@Singleton
RecordItemDataSource provideRecordItemDataSource(@ApplicationContext Context context) { | // Path: app/src/main/java/in/arjsna/audiorecorder/db/AppDataBase.java
// @Database(entities = { RecordingItem.class }, version = 1, exportSchema = false)
// public abstract class AppDataBase extends RoomDatabase {
// public abstract RecordItemDao recordItemDao();
//
// private static final String DATABASE_NAME = "saved_recordings.db";
//
// private static AppDataBase appDataBaseInstance;
// private RecordItemDataSource recordItemDataSource;
//
// public static AppDataBase getInstance(Context context) {
// if (appDataBaseInstance == null) {
// appDataBaseInstance = Room.databaseBuilder(context, AppDataBase.class, DATABASE_NAME).build();
// appDataBaseInstance.recordItemDataSource =
// new RecordItemDataSource(appDataBaseInstance.recordItemDao());
// } return appDataBaseInstance;
// }
//
// public RecordItemDataSource getRecordItemDataSource() {
// return recordItemDataSource;
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/db/RecordItemDataSource.java
// public class RecordItemDataSource {
// private RecordItemDao recordItemDao;
//
// public RecordItemDataSource(RecordItemDao recordItemDao) {
// this.recordItemDao = recordItemDao;
// }
//
// public Single<List<RecordingItem>> getAllRecordings() {
// return Single.fromCallable(() -> recordItemDao.getAllRecordings()).subscribeOn(Schedulers.io());
// }
//
// public Single<Boolean> insertNewRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.insertNewRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public long insertNewRecordItem(RecordingItem recordingItem) {
// return recordItemDao.insertNewRecordItem(recordingItem);
// }
//
// public Single<Boolean> deleteRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.deleteRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public int deleteRecordItem(RecordingItem recordingItem) {
// return recordItemDao.deleteRecordItem(recordingItem);
// }
//
// public Single<Boolean> updateRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.updateRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public int updateRecordItem(RecordingItem recordingItem) {
// return recordItemDao.updateRecordItem(recordingItem);
// }
//
// public int getRecordingsCount() {
// return recordItemDao.getCount();
// }
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/di/ApplicationModule.java
import android.app.Application;
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import in.arjsna.audiorecorder.db.AppDataBase;
import in.arjsna.audiorecorder.db.RecordItemDataSource;
import in.arjsna.audiorecorder.di.qualifiers.ApplicationContext;
import javax.inject.Singleton;
package in.arjsna.audiorecorder.di;
@Module
public class ApplicationModule {
@Provides
@ApplicationContext
@Singleton
Context provideApplicationContext(Application application) {
return application.getApplicationContext();
}
@Provides
@Singleton
RecordItemDataSource provideRecordItemDataSource(@ApplicationContext Context context) { | return AppDataBase.getInstance(context).getRecordItemDataSource(); |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/playlist/PlayListMVPView.java | // Path: app/src/main/java/in/arjsna/audiorecorder/db/RecordingItem.java
// @Entity(tableName = "recordings")
// public class RecordingItem implements Parcelable {
// @PrimaryKey(autoGenerate = true)
// private int id;
// private String mName; // file name
// private String mFilePath; //file path
// //private int mId; //id in database
// private long mLength; // length of recording in seconds
// private long mTime; // date/time of the recording
//
// @Ignore
// public boolean isPlaying = false;
//
// @Ignore
// public boolean isPaused;
// @Ignore
// public long playProgress;
//
// public RecordingItem() {
// }
//
// private RecordingItem(Parcel in) {
// mName = in.readString();
// mFilePath = in.readString();
// //mId = in.readInt();
// mLength = in.readLong();
// mTime = in.readLong();
// }
//
// public String getFilePath() {
// return mFilePath;
// }
//
// public void setFilePath(String filePath) {
// mFilePath = filePath;
// }
//
// public long getLength() {
// return mLength;
// }
//
// public void setLength(long length) {
// mLength = length;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// mName = name;
// }
//
// public long getTime() {
// return mTime;
// }
//
// public void setTime(long time) {
// mTime = time;
// }
//
// public static final Parcelable.Creator<RecordingItem> CREATOR =
// new Parcelable.Creator<RecordingItem>() {
// public RecordingItem createFromParcel(Parcel in) {
// return new RecordingItem(in);
// }
//
// public RecordingItem[] newArray(int size) {
// return new RecordingItem[size];
// }
// };
//
// @Override public void writeToParcel(Parcel dest, int flags) {
// //dest.writeInt(mId);
// dest.writeLong(mLength);
// dest.writeLong(mTime);
// dest.writeString(mFilePath);
// dest.writeString(mName);
// }
//
// @Override public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/mvpbase/IMVPView.java
// public interface IMVPView {
// }
| import in.arjsna.audiorecorder.db.RecordingItem;
import in.arjsna.audiorecorder.mvpbase.IMVPView;
import java.io.IOException; | package in.arjsna.audiorecorder.playlist;
public interface PlayListMVPView extends IMVPView {
void notifyListAdapter();
void setRecordingListVisible();
void setRecordingListInVisible();
void setEmptyLabelVisible();
void setEmptyLabelInVisible();
void startWatchingForFileChanges();
void stopWatchingForFileChanges();
void notifyListItemChange(Integer position);
void showError(String message);
void notifyListItemRemove(Integer position);
void pauseMediaPlayer(int position);
void stopMediaPlayer(int currentPlayingItem);
| // Path: app/src/main/java/in/arjsna/audiorecorder/db/RecordingItem.java
// @Entity(tableName = "recordings")
// public class RecordingItem implements Parcelable {
// @PrimaryKey(autoGenerate = true)
// private int id;
// private String mName; // file name
// private String mFilePath; //file path
// //private int mId; //id in database
// private long mLength; // length of recording in seconds
// private long mTime; // date/time of the recording
//
// @Ignore
// public boolean isPlaying = false;
//
// @Ignore
// public boolean isPaused;
// @Ignore
// public long playProgress;
//
// public RecordingItem() {
// }
//
// private RecordingItem(Parcel in) {
// mName = in.readString();
// mFilePath = in.readString();
// //mId = in.readInt();
// mLength = in.readLong();
// mTime = in.readLong();
// }
//
// public String getFilePath() {
// return mFilePath;
// }
//
// public void setFilePath(String filePath) {
// mFilePath = filePath;
// }
//
// public long getLength() {
// return mLength;
// }
//
// public void setLength(long length) {
// mLength = length;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// mName = name;
// }
//
// public long getTime() {
// return mTime;
// }
//
// public void setTime(long time) {
// mTime = time;
// }
//
// public static final Parcelable.Creator<RecordingItem> CREATOR =
// new Parcelable.Creator<RecordingItem>() {
// public RecordingItem createFromParcel(Parcel in) {
// return new RecordingItem(in);
// }
//
// public RecordingItem[] newArray(int size) {
// return new RecordingItem[size];
// }
// };
//
// @Override public void writeToParcel(Parcel dest, int flags) {
// //dest.writeInt(mId);
// dest.writeLong(mLength);
// dest.writeLong(mTime);
// dest.writeString(mFilePath);
// dest.writeString(mName);
// }
//
// @Override public int describeContents() {
// return 0;
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/mvpbase/IMVPView.java
// public interface IMVPView {
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/playlist/PlayListMVPView.java
import in.arjsna.audiorecorder.db.RecordingItem;
import in.arjsna.audiorecorder.mvpbase.IMVPView;
import java.io.IOException;
package in.arjsna.audiorecorder.playlist;
public interface PlayListMVPView extends IMVPView {
void notifyListAdapter();
void setRecordingListVisible();
void setRecordingListInVisible();
void setEmptyLabelVisible();
void setEmptyLabelInVisible();
void startWatchingForFileChanges();
void stopWatchingForFileChanges();
void notifyListItemChange(Integer position);
void showError(String message);
void notifyListItemRemove(Integer position);
void pauseMediaPlayer(int position);
void stopMediaPlayer(int currentPlayingItem);
| void startMediaPlayer(int position, RecordingItem recordingItem) throws IOException; |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/di/ApplicationComponent.java | // Path: app/src/main/java/in/arjsna/audiorecorder/AudioRecorderApp.java
// public class AudioRecorderApp extends Application implements HasActivityInjector, HasServiceInjector{
// private ApplicationComponent applicationComponent;
//
// @Inject DispatchingAndroidInjector<Activity> dispatchingAndroidActivityInjector;
// @Inject DispatchingAndroidInjector<Service> dispatchingAndroidServiceInjector;
//
// @Override public void onCreate() {
// super.onCreate();
// if (LeakCanary.isInAnalyzerProcess(this)) {
// return;
// }
// LeakCanary.install(this);
// Hawk.init(getApplicationContext()).build();
// DaggerApplicationComponent.builder().application(this).build().inject(this);
// }
//
// @Override public AndroidInjector<Activity> activityInjector() {
// return dispatchingAndroidActivityInjector;
// }
//
// @Override public AndroidInjector<Service> serviceInjector() {
// return dispatchingAndroidServiceInjector;
// }
// }
| import android.app.Application;
import dagger.BindsInstance;
import dagger.Component;
import dagger.android.AndroidInjectionModule;
import in.arjsna.audiorecorder.AudioRecorderApp;
import javax.inject.Singleton; | package in.arjsna.audiorecorder.di;
@Singleton
@Component(modules = {ApplicationModule.class, AndroidInjectionModule.class, ActivityBuilderModule.class, ServiceBuilderModule.class})
public interface ApplicationComponent {
@Component.Builder
interface Builder {
@BindsInstance Builder application(Application application);
ApplicationComponent build();
}
| // Path: app/src/main/java/in/arjsna/audiorecorder/AudioRecorderApp.java
// public class AudioRecorderApp extends Application implements HasActivityInjector, HasServiceInjector{
// private ApplicationComponent applicationComponent;
//
// @Inject DispatchingAndroidInjector<Activity> dispatchingAndroidActivityInjector;
// @Inject DispatchingAndroidInjector<Service> dispatchingAndroidServiceInjector;
//
// @Override public void onCreate() {
// super.onCreate();
// if (LeakCanary.isInAnalyzerProcess(this)) {
// return;
// }
// LeakCanary.install(this);
// Hawk.init(getApplicationContext()).build();
// DaggerApplicationComponent.builder().application(this).build().inject(this);
// }
//
// @Override public AndroidInjector<Activity> activityInjector() {
// return dispatchingAndroidActivityInjector;
// }
//
// @Override public AndroidInjector<Service> serviceInjector() {
// return dispatchingAndroidServiceInjector;
// }
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/di/ApplicationComponent.java
import android.app.Application;
import dagger.BindsInstance;
import dagger.Component;
import dagger.android.AndroidInjectionModule;
import in.arjsna.audiorecorder.AudioRecorderApp;
import javax.inject.Singleton;
package in.arjsna.audiorecorder.di;
@Singleton
@Component(modules = {ApplicationModule.class, AndroidInjectionModule.class, ActivityBuilderModule.class, ServiceBuilderModule.class})
public interface ApplicationComponent {
@Component.Builder
interface Builder {
@BindsInstance Builder application(Application application);
ApplicationComponent build();
}
| void inject(AudioRecorderApp audioRecorderApp); |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/di/RecordFragmentModule.java | // Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordMVPView.java
// public interface AudioRecordMVPView extends IMVPView {
// void updateChronometer(String text);
//
// void togglePauseStatus();
//
// void toggleRecordButton();
//
// void linkGLViewToHandler();
//
// void setPauseButtonVisible();
//
// void setPauseButtonInVisible();
//
// void setScreenOnFlag();
//
// void clearScreenOnFlag();
//
// void startServiceAndBind();
//
// void stopServiceAndUnBind();
//
// void bindToService();
//
// void unbindFromService();
//
// void pauseRecord();
//
// void resumeRecord();
//
// Disposable subscribeForTimer(Consumer<AudioRecorder.RecordTime> recordTimeConsumer);
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordPresenter.java
// public interface AudioRecordPresenter<V extends AudioRecordMVPView> extends IMVPPresenter<V> {
// void onToggleRecodingStatus();
//
// void onTogglePauseStatus();
//
// boolean isRecording();
//
// boolean isPaused();
//
// void onViewInitialised();
//
// void onServiceStatusAvailable(boolean isRecoding, boolean isRecordingPaused);
//
// void onServiceUpdateReceived(String actionExtra);
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordPresenterImpl.java
// public class AudioRecordPresenterImpl<V extends AudioRecordMVPView> extends BasePresenter<V>
// implements AudioRecordPresenter<V> {
//
// @Inject
// @ActivityContext
// public Context mContext;
// private boolean mIsRecording = false;
// private boolean mIsRecordingPaused = false;
//
// @Inject
// public AudioRecordPresenterImpl(CompositeDisposable compositeDisposable) {
// super(compositeDisposable);
// }
//
// @Override
// public void onToggleRecodingStatus() {
// if (!mIsRecording) {
// mIsRecording = true;
// getAttachedView().startServiceAndBind();
// getAttachedView().toggleRecordButton();
// getAttachedView().setPauseButtonVisible();
// getAttachedView().togglePauseStatus();
// getAttachedView().setScreenOnFlag();
// } else {
// stopRecording();
// }
// }
//
// @Override public void onTogglePauseStatus() {
// getAttachedView().setPauseButtonVisible();
// mIsRecordingPaused = !mIsRecordingPaused;
// if (mIsRecordingPaused) {
// getAttachedView().pauseRecord();
// } else {
// getAttachedView().resumeRecord();
// }
// }
//
// @Override public boolean isRecording() {
// return mIsRecording;
// }
//
// @Override public boolean isPaused() {
// return mIsRecordingPaused;
// }
//
// @Override public void onAttach(V view) {
// super.onAttach(view);
// getAttachedView().bindToService();
// }
//
// @Override public void onViewInitialised() {
// getAttachedView().updateChronometer(getChronometerText(new AudioRecorder.RecordTime()));
// getAttachedView().toggleRecordButton();
// }
//
// @Override public void onDetach() {
// getAttachedView().unbindFromService();
// super.onDetach();
// }
//
// private void stopRecording() {
// mIsRecording = false;
// mIsRecordingPaused = false;
// getAttachedView().stopServiceAndUnBind();
// getAttachedView().toggleRecordButton();
// getAttachedView().clearScreenOnFlag();
// getAttachedView().updateChronometer(getChronometerText(new AudioRecorder.RecordTime()));
// getAttachedView().setPauseButtonInVisible();
// getAttachedView().togglePauseStatus();
// }
//
// private final Consumer<AudioRecorder.RecordTime> recordTimeConsumer =
// recordTime -> getAttachedView().updateChronometer(getChronometerText(recordTime));
//
// private String getChronometerText(AudioRecorder.RecordTime recordTime) {
// return String.format(Locale.getDefault(), mContext.getString(R.string.record_time_format),
// recordTime.hours,
// recordTime.minutes,
// recordTime.seconds);
// }
//
// @Override public void onServiceStatusAvailable(boolean isRecoding, boolean isRecordingPaused) {
// mIsRecording = isRecoding;
// mIsRecordingPaused = isRecordingPaused;
// if (mIsRecording) {
// getAttachedView().setPauseButtonVisible();
// getAttachedView().togglePauseStatus();
// getAttachedView().linkGLViewToHandler();
// getAttachedView().toggleRecordButton();
// getCompositeDisposable().add(getAttachedView().subscribeForTimer(recordTimeConsumer));
// } else {
// getAttachedView().unbindFromService();
// }
// }
//
// @Override public void onServiceUpdateReceived(String actionExtra) {
// switch (actionExtra) {
// case AppConstants.ACTION_PAUSE:
// mIsRecordingPaused = true;
// getAttachedView().togglePauseStatus();
// break;
// case AppConstants.ACTION_RESUME:
// mIsRecordingPaused = false;
// getAttachedView().togglePauseStatus();
// break;
// case AppConstants.ACTION_STOP:
// stopRecording();
// break;
// }
// }
// }
| import dagger.Module;
import dagger.Provides;
import in.arjsna.audiorecorder.audiorecording.AudioRecordMVPView;
import in.arjsna.audiorecorder.audiorecording.AudioRecordPresenter;
import in.arjsna.audiorecorder.audiorecording.AudioRecordPresenterImpl;
import in.arjsna.audiorecorder.di.scopes.FragmentScope;
import io.reactivex.disposables.CompositeDisposable; | package in.arjsna.audiorecorder.di;
/**
* Created by arjun on 12/1/17.
*/
@Module
class RecordFragmentModule {
@Provides
@FragmentScope | // Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordMVPView.java
// public interface AudioRecordMVPView extends IMVPView {
// void updateChronometer(String text);
//
// void togglePauseStatus();
//
// void toggleRecordButton();
//
// void linkGLViewToHandler();
//
// void setPauseButtonVisible();
//
// void setPauseButtonInVisible();
//
// void setScreenOnFlag();
//
// void clearScreenOnFlag();
//
// void startServiceAndBind();
//
// void stopServiceAndUnBind();
//
// void bindToService();
//
// void unbindFromService();
//
// void pauseRecord();
//
// void resumeRecord();
//
// Disposable subscribeForTimer(Consumer<AudioRecorder.RecordTime> recordTimeConsumer);
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordPresenter.java
// public interface AudioRecordPresenter<V extends AudioRecordMVPView> extends IMVPPresenter<V> {
// void onToggleRecodingStatus();
//
// void onTogglePauseStatus();
//
// boolean isRecording();
//
// boolean isPaused();
//
// void onViewInitialised();
//
// void onServiceStatusAvailable(boolean isRecoding, boolean isRecordingPaused);
//
// void onServiceUpdateReceived(String actionExtra);
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordPresenterImpl.java
// public class AudioRecordPresenterImpl<V extends AudioRecordMVPView> extends BasePresenter<V>
// implements AudioRecordPresenter<V> {
//
// @Inject
// @ActivityContext
// public Context mContext;
// private boolean mIsRecording = false;
// private boolean mIsRecordingPaused = false;
//
// @Inject
// public AudioRecordPresenterImpl(CompositeDisposable compositeDisposable) {
// super(compositeDisposable);
// }
//
// @Override
// public void onToggleRecodingStatus() {
// if (!mIsRecording) {
// mIsRecording = true;
// getAttachedView().startServiceAndBind();
// getAttachedView().toggleRecordButton();
// getAttachedView().setPauseButtonVisible();
// getAttachedView().togglePauseStatus();
// getAttachedView().setScreenOnFlag();
// } else {
// stopRecording();
// }
// }
//
// @Override public void onTogglePauseStatus() {
// getAttachedView().setPauseButtonVisible();
// mIsRecordingPaused = !mIsRecordingPaused;
// if (mIsRecordingPaused) {
// getAttachedView().pauseRecord();
// } else {
// getAttachedView().resumeRecord();
// }
// }
//
// @Override public boolean isRecording() {
// return mIsRecording;
// }
//
// @Override public boolean isPaused() {
// return mIsRecordingPaused;
// }
//
// @Override public void onAttach(V view) {
// super.onAttach(view);
// getAttachedView().bindToService();
// }
//
// @Override public void onViewInitialised() {
// getAttachedView().updateChronometer(getChronometerText(new AudioRecorder.RecordTime()));
// getAttachedView().toggleRecordButton();
// }
//
// @Override public void onDetach() {
// getAttachedView().unbindFromService();
// super.onDetach();
// }
//
// private void stopRecording() {
// mIsRecording = false;
// mIsRecordingPaused = false;
// getAttachedView().stopServiceAndUnBind();
// getAttachedView().toggleRecordButton();
// getAttachedView().clearScreenOnFlag();
// getAttachedView().updateChronometer(getChronometerText(new AudioRecorder.RecordTime()));
// getAttachedView().setPauseButtonInVisible();
// getAttachedView().togglePauseStatus();
// }
//
// private final Consumer<AudioRecorder.RecordTime> recordTimeConsumer =
// recordTime -> getAttachedView().updateChronometer(getChronometerText(recordTime));
//
// private String getChronometerText(AudioRecorder.RecordTime recordTime) {
// return String.format(Locale.getDefault(), mContext.getString(R.string.record_time_format),
// recordTime.hours,
// recordTime.minutes,
// recordTime.seconds);
// }
//
// @Override public void onServiceStatusAvailable(boolean isRecoding, boolean isRecordingPaused) {
// mIsRecording = isRecoding;
// mIsRecordingPaused = isRecordingPaused;
// if (mIsRecording) {
// getAttachedView().setPauseButtonVisible();
// getAttachedView().togglePauseStatus();
// getAttachedView().linkGLViewToHandler();
// getAttachedView().toggleRecordButton();
// getCompositeDisposable().add(getAttachedView().subscribeForTimer(recordTimeConsumer));
// } else {
// getAttachedView().unbindFromService();
// }
// }
//
// @Override public void onServiceUpdateReceived(String actionExtra) {
// switch (actionExtra) {
// case AppConstants.ACTION_PAUSE:
// mIsRecordingPaused = true;
// getAttachedView().togglePauseStatus();
// break;
// case AppConstants.ACTION_RESUME:
// mIsRecordingPaused = false;
// getAttachedView().togglePauseStatus();
// break;
// case AppConstants.ACTION_STOP:
// stopRecording();
// break;
// }
// }
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/di/RecordFragmentModule.java
import dagger.Module;
import dagger.Provides;
import in.arjsna.audiorecorder.audiorecording.AudioRecordMVPView;
import in.arjsna.audiorecorder.audiorecording.AudioRecordPresenter;
import in.arjsna.audiorecorder.audiorecording.AudioRecordPresenterImpl;
import in.arjsna.audiorecorder.di.scopes.FragmentScope;
import io.reactivex.disposables.CompositeDisposable;
package in.arjsna.audiorecorder.di;
/**
* Created by arjun on 12/1/17.
*/
@Module
class RecordFragmentModule {
@Provides
@FragmentScope | AudioRecordPresenter<AudioRecordMVPView> provideAudioRecordPresenter( |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/di/RecordFragmentModule.java | // Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordMVPView.java
// public interface AudioRecordMVPView extends IMVPView {
// void updateChronometer(String text);
//
// void togglePauseStatus();
//
// void toggleRecordButton();
//
// void linkGLViewToHandler();
//
// void setPauseButtonVisible();
//
// void setPauseButtonInVisible();
//
// void setScreenOnFlag();
//
// void clearScreenOnFlag();
//
// void startServiceAndBind();
//
// void stopServiceAndUnBind();
//
// void bindToService();
//
// void unbindFromService();
//
// void pauseRecord();
//
// void resumeRecord();
//
// Disposable subscribeForTimer(Consumer<AudioRecorder.RecordTime> recordTimeConsumer);
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordPresenter.java
// public interface AudioRecordPresenter<V extends AudioRecordMVPView> extends IMVPPresenter<V> {
// void onToggleRecodingStatus();
//
// void onTogglePauseStatus();
//
// boolean isRecording();
//
// boolean isPaused();
//
// void onViewInitialised();
//
// void onServiceStatusAvailable(boolean isRecoding, boolean isRecordingPaused);
//
// void onServiceUpdateReceived(String actionExtra);
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordPresenterImpl.java
// public class AudioRecordPresenterImpl<V extends AudioRecordMVPView> extends BasePresenter<V>
// implements AudioRecordPresenter<V> {
//
// @Inject
// @ActivityContext
// public Context mContext;
// private boolean mIsRecording = false;
// private boolean mIsRecordingPaused = false;
//
// @Inject
// public AudioRecordPresenterImpl(CompositeDisposable compositeDisposable) {
// super(compositeDisposable);
// }
//
// @Override
// public void onToggleRecodingStatus() {
// if (!mIsRecording) {
// mIsRecording = true;
// getAttachedView().startServiceAndBind();
// getAttachedView().toggleRecordButton();
// getAttachedView().setPauseButtonVisible();
// getAttachedView().togglePauseStatus();
// getAttachedView().setScreenOnFlag();
// } else {
// stopRecording();
// }
// }
//
// @Override public void onTogglePauseStatus() {
// getAttachedView().setPauseButtonVisible();
// mIsRecordingPaused = !mIsRecordingPaused;
// if (mIsRecordingPaused) {
// getAttachedView().pauseRecord();
// } else {
// getAttachedView().resumeRecord();
// }
// }
//
// @Override public boolean isRecording() {
// return mIsRecording;
// }
//
// @Override public boolean isPaused() {
// return mIsRecordingPaused;
// }
//
// @Override public void onAttach(V view) {
// super.onAttach(view);
// getAttachedView().bindToService();
// }
//
// @Override public void onViewInitialised() {
// getAttachedView().updateChronometer(getChronometerText(new AudioRecorder.RecordTime()));
// getAttachedView().toggleRecordButton();
// }
//
// @Override public void onDetach() {
// getAttachedView().unbindFromService();
// super.onDetach();
// }
//
// private void stopRecording() {
// mIsRecording = false;
// mIsRecordingPaused = false;
// getAttachedView().stopServiceAndUnBind();
// getAttachedView().toggleRecordButton();
// getAttachedView().clearScreenOnFlag();
// getAttachedView().updateChronometer(getChronometerText(new AudioRecorder.RecordTime()));
// getAttachedView().setPauseButtonInVisible();
// getAttachedView().togglePauseStatus();
// }
//
// private final Consumer<AudioRecorder.RecordTime> recordTimeConsumer =
// recordTime -> getAttachedView().updateChronometer(getChronometerText(recordTime));
//
// private String getChronometerText(AudioRecorder.RecordTime recordTime) {
// return String.format(Locale.getDefault(), mContext.getString(R.string.record_time_format),
// recordTime.hours,
// recordTime.minutes,
// recordTime.seconds);
// }
//
// @Override public void onServiceStatusAvailable(boolean isRecoding, boolean isRecordingPaused) {
// mIsRecording = isRecoding;
// mIsRecordingPaused = isRecordingPaused;
// if (mIsRecording) {
// getAttachedView().setPauseButtonVisible();
// getAttachedView().togglePauseStatus();
// getAttachedView().linkGLViewToHandler();
// getAttachedView().toggleRecordButton();
// getCompositeDisposable().add(getAttachedView().subscribeForTimer(recordTimeConsumer));
// } else {
// getAttachedView().unbindFromService();
// }
// }
//
// @Override public void onServiceUpdateReceived(String actionExtra) {
// switch (actionExtra) {
// case AppConstants.ACTION_PAUSE:
// mIsRecordingPaused = true;
// getAttachedView().togglePauseStatus();
// break;
// case AppConstants.ACTION_RESUME:
// mIsRecordingPaused = false;
// getAttachedView().togglePauseStatus();
// break;
// case AppConstants.ACTION_STOP:
// stopRecording();
// break;
// }
// }
// }
| import dagger.Module;
import dagger.Provides;
import in.arjsna.audiorecorder.audiorecording.AudioRecordMVPView;
import in.arjsna.audiorecorder.audiorecording.AudioRecordPresenter;
import in.arjsna.audiorecorder.audiorecording.AudioRecordPresenterImpl;
import in.arjsna.audiorecorder.di.scopes.FragmentScope;
import io.reactivex.disposables.CompositeDisposable; | package in.arjsna.audiorecorder.di;
/**
* Created by arjun on 12/1/17.
*/
@Module
class RecordFragmentModule {
@Provides
@FragmentScope | // Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordMVPView.java
// public interface AudioRecordMVPView extends IMVPView {
// void updateChronometer(String text);
//
// void togglePauseStatus();
//
// void toggleRecordButton();
//
// void linkGLViewToHandler();
//
// void setPauseButtonVisible();
//
// void setPauseButtonInVisible();
//
// void setScreenOnFlag();
//
// void clearScreenOnFlag();
//
// void startServiceAndBind();
//
// void stopServiceAndUnBind();
//
// void bindToService();
//
// void unbindFromService();
//
// void pauseRecord();
//
// void resumeRecord();
//
// Disposable subscribeForTimer(Consumer<AudioRecorder.RecordTime> recordTimeConsumer);
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordPresenter.java
// public interface AudioRecordPresenter<V extends AudioRecordMVPView> extends IMVPPresenter<V> {
// void onToggleRecodingStatus();
//
// void onTogglePauseStatus();
//
// boolean isRecording();
//
// boolean isPaused();
//
// void onViewInitialised();
//
// void onServiceStatusAvailable(boolean isRecoding, boolean isRecordingPaused);
//
// void onServiceUpdateReceived(String actionExtra);
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordPresenterImpl.java
// public class AudioRecordPresenterImpl<V extends AudioRecordMVPView> extends BasePresenter<V>
// implements AudioRecordPresenter<V> {
//
// @Inject
// @ActivityContext
// public Context mContext;
// private boolean mIsRecording = false;
// private boolean mIsRecordingPaused = false;
//
// @Inject
// public AudioRecordPresenterImpl(CompositeDisposable compositeDisposable) {
// super(compositeDisposable);
// }
//
// @Override
// public void onToggleRecodingStatus() {
// if (!mIsRecording) {
// mIsRecording = true;
// getAttachedView().startServiceAndBind();
// getAttachedView().toggleRecordButton();
// getAttachedView().setPauseButtonVisible();
// getAttachedView().togglePauseStatus();
// getAttachedView().setScreenOnFlag();
// } else {
// stopRecording();
// }
// }
//
// @Override public void onTogglePauseStatus() {
// getAttachedView().setPauseButtonVisible();
// mIsRecordingPaused = !mIsRecordingPaused;
// if (mIsRecordingPaused) {
// getAttachedView().pauseRecord();
// } else {
// getAttachedView().resumeRecord();
// }
// }
//
// @Override public boolean isRecording() {
// return mIsRecording;
// }
//
// @Override public boolean isPaused() {
// return mIsRecordingPaused;
// }
//
// @Override public void onAttach(V view) {
// super.onAttach(view);
// getAttachedView().bindToService();
// }
//
// @Override public void onViewInitialised() {
// getAttachedView().updateChronometer(getChronometerText(new AudioRecorder.RecordTime()));
// getAttachedView().toggleRecordButton();
// }
//
// @Override public void onDetach() {
// getAttachedView().unbindFromService();
// super.onDetach();
// }
//
// private void stopRecording() {
// mIsRecording = false;
// mIsRecordingPaused = false;
// getAttachedView().stopServiceAndUnBind();
// getAttachedView().toggleRecordButton();
// getAttachedView().clearScreenOnFlag();
// getAttachedView().updateChronometer(getChronometerText(new AudioRecorder.RecordTime()));
// getAttachedView().setPauseButtonInVisible();
// getAttachedView().togglePauseStatus();
// }
//
// private final Consumer<AudioRecorder.RecordTime> recordTimeConsumer =
// recordTime -> getAttachedView().updateChronometer(getChronometerText(recordTime));
//
// private String getChronometerText(AudioRecorder.RecordTime recordTime) {
// return String.format(Locale.getDefault(), mContext.getString(R.string.record_time_format),
// recordTime.hours,
// recordTime.minutes,
// recordTime.seconds);
// }
//
// @Override public void onServiceStatusAvailable(boolean isRecoding, boolean isRecordingPaused) {
// mIsRecording = isRecoding;
// mIsRecordingPaused = isRecordingPaused;
// if (mIsRecording) {
// getAttachedView().setPauseButtonVisible();
// getAttachedView().togglePauseStatus();
// getAttachedView().linkGLViewToHandler();
// getAttachedView().toggleRecordButton();
// getCompositeDisposable().add(getAttachedView().subscribeForTimer(recordTimeConsumer));
// } else {
// getAttachedView().unbindFromService();
// }
// }
//
// @Override public void onServiceUpdateReceived(String actionExtra) {
// switch (actionExtra) {
// case AppConstants.ACTION_PAUSE:
// mIsRecordingPaused = true;
// getAttachedView().togglePauseStatus();
// break;
// case AppConstants.ACTION_RESUME:
// mIsRecordingPaused = false;
// getAttachedView().togglePauseStatus();
// break;
// case AppConstants.ACTION_STOP:
// stopRecording();
// break;
// }
// }
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/di/RecordFragmentModule.java
import dagger.Module;
import dagger.Provides;
import in.arjsna.audiorecorder.audiorecording.AudioRecordMVPView;
import in.arjsna.audiorecorder.audiorecording.AudioRecordPresenter;
import in.arjsna.audiorecorder.audiorecording.AudioRecordPresenterImpl;
import in.arjsna.audiorecorder.di.scopes.FragmentScope;
import io.reactivex.disposables.CompositeDisposable;
package in.arjsna.audiorecorder.di;
/**
* Created by arjun on 12/1/17.
*/
@Module
class RecordFragmentModule {
@Provides
@FragmentScope | AudioRecordPresenter<AudioRecordMVPView> provideAudioRecordPresenter( |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/di/RecordFragmentModule.java | // Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordMVPView.java
// public interface AudioRecordMVPView extends IMVPView {
// void updateChronometer(String text);
//
// void togglePauseStatus();
//
// void toggleRecordButton();
//
// void linkGLViewToHandler();
//
// void setPauseButtonVisible();
//
// void setPauseButtonInVisible();
//
// void setScreenOnFlag();
//
// void clearScreenOnFlag();
//
// void startServiceAndBind();
//
// void stopServiceAndUnBind();
//
// void bindToService();
//
// void unbindFromService();
//
// void pauseRecord();
//
// void resumeRecord();
//
// Disposable subscribeForTimer(Consumer<AudioRecorder.RecordTime> recordTimeConsumer);
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordPresenter.java
// public interface AudioRecordPresenter<V extends AudioRecordMVPView> extends IMVPPresenter<V> {
// void onToggleRecodingStatus();
//
// void onTogglePauseStatus();
//
// boolean isRecording();
//
// boolean isPaused();
//
// void onViewInitialised();
//
// void onServiceStatusAvailable(boolean isRecoding, boolean isRecordingPaused);
//
// void onServiceUpdateReceived(String actionExtra);
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordPresenterImpl.java
// public class AudioRecordPresenterImpl<V extends AudioRecordMVPView> extends BasePresenter<V>
// implements AudioRecordPresenter<V> {
//
// @Inject
// @ActivityContext
// public Context mContext;
// private boolean mIsRecording = false;
// private boolean mIsRecordingPaused = false;
//
// @Inject
// public AudioRecordPresenterImpl(CompositeDisposable compositeDisposable) {
// super(compositeDisposable);
// }
//
// @Override
// public void onToggleRecodingStatus() {
// if (!mIsRecording) {
// mIsRecording = true;
// getAttachedView().startServiceAndBind();
// getAttachedView().toggleRecordButton();
// getAttachedView().setPauseButtonVisible();
// getAttachedView().togglePauseStatus();
// getAttachedView().setScreenOnFlag();
// } else {
// stopRecording();
// }
// }
//
// @Override public void onTogglePauseStatus() {
// getAttachedView().setPauseButtonVisible();
// mIsRecordingPaused = !mIsRecordingPaused;
// if (mIsRecordingPaused) {
// getAttachedView().pauseRecord();
// } else {
// getAttachedView().resumeRecord();
// }
// }
//
// @Override public boolean isRecording() {
// return mIsRecording;
// }
//
// @Override public boolean isPaused() {
// return mIsRecordingPaused;
// }
//
// @Override public void onAttach(V view) {
// super.onAttach(view);
// getAttachedView().bindToService();
// }
//
// @Override public void onViewInitialised() {
// getAttachedView().updateChronometer(getChronometerText(new AudioRecorder.RecordTime()));
// getAttachedView().toggleRecordButton();
// }
//
// @Override public void onDetach() {
// getAttachedView().unbindFromService();
// super.onDetach();
// }
//
// private void stopRecording() {
// mIsRecording = false;
// mIsRecordingPaused = false;
// getAttachedView().stopServiceAndUnBind();
// getAttachedView().toggleRecordButton();
// getAttachedView().clearScreenOnFlag();
// getAttachedView().updateChronometer(getChronometerText(new AudioRecorder.RecordTime()));
// getAttachedView().setPauseButtonInVisible();
// getAttachedView().togglePauseStatus();
// }
//
// private final Consumer<AudioRecorder.RecordTime> recordTimeConsumer =
// recordTime -> getAttachedView().updateChronometer(getChronometerText(recordTime));
//
// private String getChronometerText(AudioRecorder.RecordTime recordTime) {
// return String.format(Locale.getDefault(), mContext.getString(R.string.record_time_format),
// recordTime.hours,
// recordTime.minutes,
// recordTime.seconds);
// }
//
// @Override public void onServiceStatusAvailable(boolean isRecoding, boolean isRecordingPaused) {
// mIsRecording = isRecoding;
// mIsRecordingPaused = isRecordingPaused;
// if (mIsRecording) {
// getAttachedView().setPauseButtonVisible();
// getAttachedView().togglePauseStatus();
// getAttachedView().linkGLViewToHandler();
// getAttachedView().toggleRecordButton();
// getCompositeDisposable().add(getAttachedView().subscribeForTimer(recordTimeConsumer));
// } else {
// getAttachedView().unbindFromService();
// }
// }
//
// @Override public void onServiceUpdateReceived(String actionExtra) {
// switch (actionExtra) {
// case AppConstants.ACTION_PAUSE:
// mIsRecordingPaused = true;
// getAttachedView().togglePauseStatus();
// break;
// case AppConstants.ACTION_RESUME:
// mIsRecordingPaused = false;
// getAttachedView().togglePauseStatus();
// break;
// case AppConstants.ACTION_STOP:
// stopRecording();
// break;
// }
// }
// }
| import dagger.Module;
import dagger.Provides;
import in.arjsna.audiorecorder.audiorecording.AudioRecordMVPView;
import in.arjsna.audiorecorder.audiorecording.AudioRecordPresenter;
import in.arjsna.audiorecorder.audiorecording.AudioRecordPresenterImpl;
import in.arjsna.audiorecorder.di.scopes.FragmentScope;
import io.reactivex.disposables.CompositeDisposable; | package in.arjsna.audiorecorder.di;
/**
* Created by arjun on 12/1/17.
*/
@Module
class RecordFragmentModule {
@Provides
@FragmentScope
AudioRecordPresenter<AudioRecordMVPView> provideAudioRecordPresenter( | // Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordMVPView.java
// public interface AudioRecordMVPView extends IMVPView {
// void updateChronometer(String text);
//
// void togglePauseStatus();
//
// void toggleRecordButton();
//
// void linkGLViewToHandler();
//
// void setPauseButtonVisible();
//
// void setPauseButtonInVisible();
//
// void setScreenOnFlag();
//
// void clearScreenOnFlag();
//
// void startServiceAndBind();
//
// void stopServiceAndUnBind();
//
// void bindToService();
//
// void unbindFromService();
//
// void pauseRecord();
//
// void resumeRecord();
//
// Disposable subscribeForTimer(Consumer<AudioRecorder.RecordTime> recordTimeConsumer);
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordPresenter.java
// public interface AudioRecordPresenter<V extends AudioRecordMVPView> extends IMVPPresenter<V> {
// void onToggleRecodingStatus();
//
// void onTogglePauseStatus();
//
// boolean isRecording();
//
// boolean isPaused();
//
// void onViewInitialised();
//
// void onServiceStatusAvailable(boolean isRecoding, boolean isRecordingPaused);
//
// void onServiceUpdateReceived(String actionExtra);
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/audiorecording/AudioRecordPresenterImpl.java
// public class AudioRecordPresenterImpl<V extends AudioRecordMVPView> extends BasePresenter<V>
// implements AudioRecordPresenter<V> {
//
// @Inject
// @ActivityContext
// public Context mContext;
// private boolean mIsRecording = false;
// private boolean mIsRecordingPaused = false;
//
// @Inject
// public AudioRecordPresenterImpl(CompositeDisposable compositeDisposable) {
// super(compositeDisposable);
// }
//
// @Override
// public void onToggleRecodingStatus() {
// if (!mIsRecording) {
// mIsRecording = true;
// getAttachedView().startServiceAndBind();
// getAttachedView().toggleRecordButton();
// getAttachedView().setPauseButtonVisible();
// getAttachedView().togglePauseStatus();
// getAttachedView().setScreenOnFlag();
// } else {
// stopRecording();
// }
// }
//
// @Override public void onTogglePauseStatus() {
// getAttachedView().setPauseButtonVisible();
// mIsRecordingPaused = !mIsRecordingPaused;
// if (mIsRecordingPaused) {
// getAttachedView().pauseRecord();
// } else {
// getAttachedView().resumeRecord();
// }
// }
//
// @Override public boolean isRecording() {
// return mIsRecording;
// }
//
// @Override public boolean isPaused() {
// return mIsRecordingPaused;
// }
//
// @Override public void onAttach(V view) {
// super.onAttach(view);
// getAttachedView().bindToService();
// }
//
// @Override public void onViewInitialised() {
// getAttachedView().updateChronometer(getChronometerText(new AudioRecorder.RecordTime()));
// getAttachedView().toggleRecordButton();
// }
//
// @Override public void onDetach() {
// getAttachedView().unbindFromService();
// super.onDetach();
// }
//
// private void stopRecording() {
// mIsRecording = false;
// mIsRecordingPaused = false;
// getAttachedView().stopServiceAndUnBind();
// getAttachedView().toggleRecordButton();
// getAttachedView().clearScreenOnFlag();
// getAttachedView().updateChronometer(getChronometerText(new AudioRecorder.RecordTime()));
// getAttachedView().setPauseButtonInVisible();
// getAttachedView().togglePauseStatus();
// }
//
// private final Consumer<AudioRecorder.RecordTime> recordTimeConsumer =
// recordTime -> getAttachedView().updateChronometer(getChronometerText(recordTime));
//
// private String getChronometerText(AudioRecorder.RecordTime recordTime) {
// return String.format(Locale.getDefault(), mContext.getString(R.string.record_time_format),
// recordTime.hours,
// recordTime.minutes,
// recordTime.seconds);
// }
//
// @Override public void onServiceStatusAvailable(boolean isRecoding, boolean isRecordingPaused) {
// mIsRecording = isRecoding;
// mIsRecordingPaused = isRecordingPaused;
// if (mIsRecording) {
// getAttachedView().setPauseButtonVisible();
// getAttachedView().togglePauseStatus();
// getAttachedView().linkGLViewToHandler();
// getAttachedView().toggleRecordButton();
// getCompositeDisposable().add(getAttachedView().subscribeForTimer(recordTimeConsumer));
// } else {
// getAttachedView().unbindFromService();
// }
// }
//
// @Override public void onServiceUpdateReceived(String actionExtra) {
// switch (actionExtra) {
// case AppConstants.ACTION_PAUSE:
// mIsRecordingPaused = true;
// getAttachedView().togglePauseStatus();
// break;
// case AppConstants.ACTION_RESUME:
// mIsRecordingPaused = false;
// getAttachedView().togglePauseStatus();
// break;
// case AppConstants.ACTION_STOP:
// stopRecording();
// break;
// }
// }
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/di/RecordFragmentModule.java
import dagger.Module;
import dagger.Provides;
import in.arjsna.audiorecorder.audiorecording.AudioRecordMVPView;
import in.arjsna.audiorecorder.audiorecording.AudioRecordPresenter;
import in.arjsna.audiorecorder.audiorecording.AudioRecordPresenterImpl;
import in.arjsna.audiorecorder.di.scopes.FragmentScope;
import io.reactivex.disposables.CompositeDisposable;
package in.arjsna.audiorecorder.di;
/**
* Created by arjun on 12/1/17.
*/
@Module
class RecordFragmentModule {
@Provides
@FragmentScope
AudioRecordPresenter<AudioRecordMVPView> provideAudioRecordPresenter( | AudioRecordPresenterImpl<AudioRecordMVPView> audioRecordPresenter) { |
Arjun-sna/Android-AudioRecorder-App | app/src/main/java/in/arjsna/audiorecorder/recordingservice/AudioSaveHelper.java | // Path: app/src/main/java/in/arjsna/audiorecorder/db/RecordItemDataSource.java
// public class RecordItemDataSource {
// private RecordItemDao recordItemDao;
//
// public RecordItemDataSource(RecordItemDao recordItemDao) {
// this.recordItemDao = recordItemDao;
// }
//
// public Single<List<RecordingItem>> getAllRecordings() {
// return Single.fromCallable(() -> recordItemDao.getAllRecordings()).subscribeOn(Schedulers.io());
// }
//
// public Single<Boolean> insertNewRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.insertNewRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public long insertNewRecordItem(RecordingItem recordingItem) {
// return recordItemDao.insertNewRecordItem(recordingItem);
// }
//
// public Single<Boolean> deleteRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.deleteRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public int deleteRecordItem(RecordingItem recordingItem) {
// return recordItemDao.deleteRecordItem(recordingItem);
// }
//
// public Single<Boolean> updateRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.updateRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public int updateRecordItem(RecordingItem recordingItem) {
// return recordItemDao.updateRecordItem(recordingItem);
// }
//
// public int getRecordingsCount() {
// return recordItemDao.getCount();
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/db/RecordingItem.java
// @Entity(tableName = "recordings")
// public class RecordingItem implements Parcelable {
// @PrimaryKey(autoGenerate = true)
// private int id;
// private String mName; // file name
// private String mFilePath; //file path
// //private int mId; //id in database
// private long mLength; // length of recording in seconds
// private long mTime; // date/time of the recording
//
// @Ignore
// public boolean isPlaying = false;
//
// @Ignore
// public boolean isPaused;
// @Ignore
// public long playProgress;
//
// public RecordingItem() {
// }
//
// private RecordingItem(Parcel in) {
// mName = in.readString();
// mFilePath = in.readString();
// //mId = in.readInt();
// mLength = in.readLong();
// mTime = in.readLong();
// }
//
// public String getFilePath() {
// return mFilePath;
// }
//
// public void setFilePath(String filePath) {
// mFilePath = filePath;
// }
//
// public long getLength() {
// return mLength;
// }
//
// public void setLength(long length) {
// mLength = length;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// mName = name;
// }
//
// public long getTime() {
// return mTime;
// }
//
// public void setTime(long time) {
// mTime = time;
// }
//
// public static final Parcelable.Creator<RecordingItem> CREATOR =
// new Parcelable.Creator<RecordingItem>() {
// public RecordingItem createFromParcel(Parcel in) {
// return new RecordingItem(in);
// }
//
// public RecordingItem[] newArray(int size) {
// return new RecordingItem[size];
// }
// };
//
// @Override public void writeToParcel(Parcel dest, int flags) {
// //dest.writeInt(mId);
// dest.writeLong(mLength);
// dest.writeLong(mTime);
// dest.writeString(mFilePath);
// dest.writeString(mName);
// }
//
// @Override public int describeContents() {
// return 0;
// }
// }
| import android.media.AudioFormat;
import android.os.Environment;
import android.util.Log;
import in.arjsna.audiorecorder.db.RecordItemDataSource;
import in.arjsna.audiorecorder.db.RecordingItem;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.inject.Inject; | os = new FileOutputStream(mFile);
writeWavHeader(os, Constants.RECORDER_CHANNELS, mRecordSampleRate,
Constants.RECORDER_AUDIO_ENCODING);
} catch (IOException e) {
// TODO: 4/9/17 handle this
e.printStackTrace();
}
}
public void onDataReady(byte[] data) {
try {
os.write(data, 0, data.length);
} catch (IOException e) {
e.printStackTrace();
}
}
public void onRecordingStopped(AudioRecorder.RecordTime currentRecordTime) {
try {
os.close();
updateWavHeader(mFile);
saveFileDetails(currentRecordTime);
System.out.println("Record Complete. Saving and closing");
} catch (IOException e) {
mFile.deleteOnExit();
e.printStackTrace();
}
}
private void saveFileDetails(AudioRecorder.RecordTime currentRecordTime) { | // Path: app/src/main/java/in/arjsna/audiorecorder/db/RecordItemDataSource.java
// public class RecordItemDataSource {
// private RecordItemDao recordItemDao;
//
// public RecordItemDataSource(RecordItemDao recordItemDao) {
// this.recordItemDao = recordItemDao;
// }
//
// public Single<List<RecordingItem>> getAllRecordings() {
// return Single.fromCallable(() -> recordItemDao.getAllRecordings()).subscribeOn(Schedulers.io());
// }
//
// public Single<Boolean> insertNewRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.insertNewRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public long insertNewRecordItem(RecordingItem recordingItem) {
// return recordItemDao.insertNewRecordItem(recordingItem);
// }
//
// public Single<Boolean> deleteRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.deleteRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public int deleteRecordItem(RecordingItem recordingItem) {
// return recordItemDao.deleteRecordItem(recordingItem);
// }
//
// public Single<Boolean> updateRecordItemAsync(RecordingItem recordingItem) {
// return Single.fromCallable(() -> recordItemDao.updateRecordItem(recordingItem) > 1)
// .subscribeOn(Schedulers.io());
// }
//
// public int updateRecordItem(RecordingItem recordingItem) {
// return recordItemDao.updateRecordItem(recordingItem);
// }
//
// public int getRecordingsCount() {
// return recordItemDao.getCount();
// }
// }
//
// Path: app/src/main/java/in/arjsna/audiorecorder/db/RecordingItem.java
// @Entity(tableName = "recordings")
// public class RecordingItem implements Parcelable {
// @PrimaryKey(autoGenerate = true)
// private int id;
// private String mName; // file name
// private String mFilePath; //file path
// //private int mId; //id in database
// private long mLength; // length of recording in seconds
// private long mTime; // date/time of the recording
//
// @Ignore
// public boolean isPlaying = false;
//
// @Ignore
// public boolean isPaused;
// @Ignore
// public long playProgress;
//
// public RecordingItem() {
// }
//
// private RecordingItem(Parcel in) {
// mName = in.readString();
// mFilePath = in.readString();
// //mId = in.readInt();
// mLength = in.readLong();
// mTime = in.readLong();
// }
//
// public String getFilePath() {
// return mFilePath;
// }
//
// public void setFilePath(String filePath) {
// mFilePath = filePath;
// }
//
// public long getLength() {
// return mLength;
// }
//
// public void setLength(long length) {
// mLength = length;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// mName = name;
// }
//
// public long getTime() {
// return mTime;
// }
//
// public void setTime(long time) {
// mTime = time;
// }
//
// public static final Parcelable.Creator<RecordingItem> CREATOR =
// new Parcelable.Creator<RecordingItem>() {
// public RecordingItem createFromParcel(Parcel in) {
// return new RecordingItem(in);
// }
//
// public RecordingItem[] newArray(int size) {
// return new RecordingItem[size];
// }
// };
//
// @Override public void writeToParcel(Parcel dest, int flags) {
// //dest.writeInt(mId);
// dest.writeLong(mLength);
// dest.writeLong(mTime);
// dest.writeString(mFilePath);
// dest.writeString(mName);
// }
//
// @Override public int describeContents() {
// return 0;
// }
// }
// Path: app/src/main/java/in/arjsna/audiorecorder/recordingservice/AudioSaveHelper.java
import android.media.AudioFormat;
import android.os.Environment;
import android.util.Log;
import in.arjsna.audiorecorder.db.RecordItemDataSource;
import in.arjsna.audiorecorder.db.RecordingItem;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.inject.Inject;
os = new FileOutputStream(mFile);
writeWavHeader(os, Constants.RECORDER_CHANNELS, mRecordSampleRate,
Constants.RECORDER_AUDIO_ENCODING);
} catch (IOException e) {
// TODO: 4/9/17 handle this
e.printStackTrace();
}
}
public void onDataReady(byte[] data) {
try {
os.write(data, 0, data.length);
} catch (IOException e) {
e.printStackTrace();
}
}
public void onRecordingStopped(AudioRecorder.RecordTime currentRecordTime) {
try {
os.close();
updateWavHeader(mFile);
saveFileDetails(currentRecordTime);
System.out.println("Record Complete. Saving and closing");
} catch (IOException e) {
mFile.deleteOnExit();
e.printStackTrace();
}
}
private void saveFileDetails(AudioRecorder.RecordTime currentRecordTime) { | RecordingItem recordingItem = new RecordingItem(); |
hanhailong/DevHeadLine | app/src/main/java/com/hhl/devheadline/ui/activity/BusinessCoopActivity.java | // Path: app/src/main/java/com/hhl/devheadline/presenter/BasePresenter.java
// public abstract class BasePresenter<V extends IBaseView> {
//
// private Reference<V> mViewRef;
// protected V mView;
//
// protected static final ApiService mApiService = RetrofitFactory.getApiService();
//
// public BasePresenter(V view) {
// mViewRef = new WeakReference<V>(view);
// this.mView = mViewRef.get();
// }
//
// /**
// * 解除presenter与view的关联
// */
// public void detachView() {
// if (mViewRef != null) {
// mViewRef.clear();
// mViewRef = null;
// }
// }
//
// }
//
// Path: app/src/main/java/com/hhl/devheadline/presenter/FeedbackPresenter.java
// public class FeedbackPresenter extends BasePresenter<IFeedbackView> {
// public FeedbackPresenter(IFeedbackView view) {
// super(view);
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/ui/iview/IFeedbackView.java
// public interface IFeedbackView extends IBaseView {
// }
| import android.os.Bundle;
import com.hhl.devheadline.R;
import com.hhl.devheadline.presenter.BasePresenter;
import com.hhl.devheadline.presenter.FeedbackPresenter;
import com.hhl.devheadline.ui.iview.IFeedbackView; | package com.hhl.devheadline.ui.activity;
/**
* 商务合作
*/
public class BusinessCoopActivity extends BaseActivity implements IFeedbackView {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected int getContentView() {
return R.layout.activity_business_coop;
}
@Override | // Path: app/src/main/java/com/hhl/devheadline/presenter/BasePresenter.java
// public abstract class BasePresenter<V extends IBaseView> {
//
// private Reference<V> mViewRef;
// protected V mView;
//
// protected static final ApiService mApiService = RetrofitFactory.getApiService();
//
// public BasePresenter(V view) {
// mViewRef = new WeakReference<V>(view);
// this.mView = mViewRef.get();
// }
//
// /**
// * 解除presenter与view的关联
// */
// public void detachView() {
// if (mViewRef != null) {
// mViewRef.clear();
// mViewRef = null;
// }
// }
//
// }
//
// Path: app/src/main/java/com/hhl/devheadline/presenter/FeedbackPresenter.java
// public class FeedbackPresenter extends BasePresenter<IFeedbackView> {
// public FeedbackPresenter(IFeedbackView view) {
// super(view);
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/ui/iview/IFeedbackView.java
// public interface IFeedbackView extends IBaseView {
// }
// Path: app/src/main/java/com/hhl/devheadline/ui/activity/BusinessCoopActivity.java
import android.os.Bundle;
import com.hhl.devheadline.R;
import com.hhl.devheadline.presenter.BasePresenter;
import com.hhl.devheadline.presenter.FeedbackPresenter;
import com.hhl.devheadline.ui.iview.IFeedbackView;
package com.hhl.devheadline.ui.activity;
/**
* 商务合作
*/
public class BusinessCoopActivity extends BaseActivity implements IFeedbackView {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected int getContentView() {
return R.layout.activity_business_coop;
}
@Override | protected BasePresenter getPresenter() { |
hanhailong/DevHeadLine | app/src/main/java/com/hhl/devheadline/ui/activity/BusinessCoopActivity.java | // Path: app/src/main/java/com/hhl/devheadline/presenter/BasePresenter.java
// public abstract class BasePresenter<V extends IBaseView> {
//
// private Reference<V> mViewRef;
// protected V mView;
//
// protected static final ApiService mApiService = RetrofitFactory.getApiService();
//
// public BasePresenter(V view) {
// mViewRef = new WeakReference<V>(view);
// this.mView = mViewRef.get();
// }
//
// /**
// * 解除presenter与view的关联
// */
// public void detachView() {
// if (mViewRef != null) {
// mViewRef.clear();
// mViewRef = null;
// }
// }
//
// }
//
// Path: app/src/main/java/com/hhl/devheadline/presenter/FeedbackPresenter.java
// public class FeedbackPresenter extends BasePresenter<IFeedbackView> {
// public FeedbackPresenter(IFeedbackView view) {
// super(view);
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/ui/iview/IFeedbackView.java
// public interface IFeedbackView extends IBaseView {
// }
| import android.os.Bundle;
import com.hhl.devheadline.R;
import com.hhl.devheadline.presenter.BasePresenter;
import com.hhl.devheadline.presenter.FeedbackPresenter;
import com.hhl.devheadline.ui.iview.IFeedbackView; | package com.hhl.devheadline.ui.activity;
/**
* 商务合作
*/
public class BusinessCoopActivity extends BaseActivity implements IFeedbackView {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected int getContentView() {
return R.layout.activity_business_coop;
}
@Override
protected BasePresenter getPresenter() { | // Path: app/src/main/java/com/hhl/devheadline/presenter/BasePresenter.java
// public abstract class BasePresenter<V extends IBaseView> {
//
// private Reference<V> mViewRef;
// protected V mView;
//
// protected static final ApiService mApiService = RetrofitFactory.getApiService();
//
// public BasePresenter(V view) {
// mViewRef = new WeakReference<V>(view);
// this.mView = mViewRef.get();
// }
//
// /**
// * 解除presenter与view的关联
// */
// public void detachView() {
// if (mViewRef != null) {
// mViewRef.clear();
// mViewRef = null;
// }
// }
//
// }
//
// Path: app/src/main/java/com/hhl/devheadline/presenter/FeedbackPresenter.java
// public class FeedbackPresenter extends BasePresenter<IFeedbackView> {
// public FeedbackPresenter(IFeedbackView view) {
// super(view);
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/ui/iview/IFeedbackView.java
// public interface IFeedbackView extends IBaseView {
// }
// Path: app/src/main/java/com/hhl/devheadline/ui/activity/BusinessCoopActivity.java
import android.os.Bundle;
import com.hhl.devheadline.R;
import com.hhl.devheadline.presenter.BasePresenter;
import com.hhl.devheadline.presenter.FeedbackPresenter;
import com.hhl.devheadline.ui.iview.IFeedbackView;
package com.hhl.devheadline.ui.activity;
/**
* 商务合作
*/
public class BusinessCoopActivity extends BaseActivity implements IFeedbackView {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected int getContentView() {
return R.layout.activity_business_coop;
}
@Override
protected BasePresenter getPresenter() { | return new FeedbackPresenter(this); |
hanhailong/DevHeadLine | app/src/main/java/com/hhl/devheadline/ui/activity/NoteDetailsActivity.java | // Path: app/src/main/java/com/hhl/devheadline/presenter/NoteDetailsPresenter.java
// public class NoteDetailsPresenter extends BasePresenter<INoteDetailsView> {
// public NoteDetailsPresenter(INoteDetailsView view){
// super(view);
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/ui/iview/INoteDetailsView.java
// public interface INoteDetailsView extends IBaseView {
// }
//
// Path: app/src/main/java/com/hhl/devheadline/utils/AppTools.java
// public class AppTools {
// /**
// * 截取长字符
// * @param str
// * @return
// */
// public static String clipLongText(String str) {
// if (str != null) {
// final String encoding = "GBK";
// try {
// byte[] b = str.getBytes(encoding);
// if (b.length > 20) {
// int end = 16;
// String result = new String(b, 0, end, encoding);
// if (str.indexOf(result) == -1) {
// return new String(b, 0, end - 1, encoding) + "...";
// }
// return result + "...";
// }
// } catch (UnsupportedEncodingException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// }
// return str;
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/utils/ToastUtils.java
// public class ToastUtils {
//
// /**
// * Toast
// *
// * @param content
// */
// public static void toast(final String content) {
// new Handler(Looper.getMainLooper()).post(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(DevHeadLineApplication.getInstance(), content, Toast.LENGTH_SHORT).show();
// }
// });
// }
//
// /**
// * Toast
// *
// * @param id
// */
// public static void toast(@StringRes int id) {
// toast(DevHeadLineApplication.getInstance().getResources().getString(id));
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.hhl.devheadline.R;
import com.hhl.devheadline.presenter.NoteDetailsPresenter;
import com.hhl.devheadline.ui.iview.INoteDetailsView;
import com.hhl.devheadline.utils.AppTools;
import com.hhl.devheadline.utils.ToastUtils;
import butterknife.Bind;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers; | protected int getContentView() {
return R.layout.activity_notedetails;
}
@Override
protected NoteDetailsPresenter getPresenter() {
return new NoteDetailsPresenter(this);
}
class MyWebChromeClient extends WebChromeClient {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
progressBar.setVisibility(View.GONE);
} else {
if (progressBar.getVisibility() == View.GONE) {
progressBar.setVisibility(View.VISIBLE);
}
if (newProgress > progressBar.getProgress()) {
progressBar.setProgress(newProgress);
}
}
// TODO Auto-generated method stub
super.onProgressChanged(view, newProgress);
}
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
result.confirm(); | // Path: app/src/main/java/com/hhl/devheadline/presenter/NoteDetailsPresenter.java
// public class NoteDetailsPresenter extends BasePresenter<INoteDetailsView> {
// public NoteDetailsPresenter(INoteDetailsView view){
// super(view);
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/ui/iview/INoteDetailsView.java
// public interface INoteDetailsView extends IBaseView {
// }
//
// Path: app/src/main/java/com/hhl/devheadline/utils/AppTools.java
// public class AppTools {
// /**
// * 截取长字符
// * @param str
// * @return
// */
// public static String clipLongText(String str) {
// if (str != null) {
// final String encoding = "GBK";
// try {
// byte[] b = str.getBytes(encoding);
// if (b.length > 20) {
// int end = 16;
// String result = new String(b, 0, end, encoding);
// if (str.indexOf(result) == -1) {
// return new String(b, 0, end - 1, encoding) + "...";
// }
// return result + "...";
// }
// } catch (UnsupportedEncodingException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// }
// return str;
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/utils/ToastUtils.java
// public class ToastUtils {
//
// /**
// * Toast
// *
// * @param content
// */
// public static void toast(final String content) {
// new Handler(Looper.getMainLooper()).post(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(DevHeadLineApplication.getInstance(), content, Toast.LENGTH_SHORT).show();
// }
// });
// }
//
// /**
// * Toast
// *
// * @param id
// */
// public static void toast(@StringRes int id) {
// toast(DevHeadLineApplication.getInstance().getResources().getString(id));
// }
// }
// Path: app/src/main/java/com/hhl/devheadline/ui/activity/NoteDetailsActivity.java
import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.hhl.devheadline.R;
import com.hhl.devheadline.presenter.NoteDetailsPresenter;
import com.hhl.devheadline.ui.iview.INoteDetailsView;
import com.hhl.devheadline.utils.AppTools;
import com.hhl.devheadline.utils.ToastUtils;
import butterknife.Bind;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
protected int getContentView() {
return R.layout.activity_notedetails;
}
@Override
protected NoteDetailsPresenter getPresenter() {
return new NoteDetailsPresenter(this);
}
class MyWebChromeClient extends WebChromeClient {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
progressBar.setVisibility(View.GONE);
} else {
if (progressBar.getVisibility() == View.GONE) {
progressBar.setVisibility(View.VISIBLE);
}
if (newProgress > progressBar.getProgress()) {
progressBar.setProgress(newProgress);
}
}
// TODO Auto-generated method stub
super.onProgressChanged(view, newProgress);
}
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
result.confirm(); | ToastUtils.toast(message); |
hanhailong/DevHeadLine | app/src/main/java/com/hhl/devheadline/ui/activity/NoteDetailsActivity.java | // Path: app/src/main/java/com/hhl/devheadline/presenter/NoteDetailsPresenter.java
// public class NoteDetailsPresenter extends BasePresenter<INoteDetailsView> {
// public NoteDetailsPresenter(INoteDetailsView view){
// super(view);
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/ui/iview/INoteDetailsView.java
// public interface INoteDetailsView extends IBaseView {
// }
//
// Path: app/src/main/java/com/hhl/devheadline/utils/AppTools.java
// public class AppTools {
// /**
// * 截取长字符
// * @param str
// * @return
// */
// public static String clipLongText(String str) {
// if (str != null) {
// final String encoding = "GBK";
// try {
// byte[] b = str.getBytes(encoding);
// if (b.length > 20) {
// int end = 16;
// String result = new String(b, 0, end, encoding);
// if (str.indexOf(result) == -1) {
// return new String(b, 0, end - 1, encoding) + "...";
// }
// return result + "...";
// }
// } catch (UnsupportedEncodingException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// }
// return str;
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/utils/ToastUtils.java
// public class ToastUtils {
//
// /**
// * Toast
// *
// * @param content
// */
// public static void toast(final String content) {
// new Handler(Looper.getMainLooper()).post(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(DevHeadLineApplication.getInstance(), content, Toast.LENGTH_SHORT).show();
// }
// });
// }
//
// /**
// * Toast
// *
// * @param id
// */
// public static void toast(@StringRes int id) {
// toast(DevHeadLineApplication.getInstance().getResources().getString(id));
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.hhl.devheadline.R;
import com.hhl.devheadline.presenter.NoteDetailsPresenter;
import com.hhl.devheadline.ui.iview.INoteDetailsView;
import com.hhl.devheadline.utils.AppTools;
import com.hhl.devheadline.utils.ToastUtils;
import butterknife.Bind;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers; | if (newProgress > progressBar.getProgress()) {
progressBar.setProgress(newProgress);
}
}
// TODO Auto-generated method stub
super.onProgressChanged(view, newProgress);
}
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
result.confirm();
ToastUtils.toast(message);
return true;
}
@Override
public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
result.confirm();
return super.onJsConfirm(view, url, message, result);
}
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
result.confirm();
return super.onJsPrompt(view, url, message, message, result);
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title); | // Path: app/src/main/java/com/hhl/devheadline/presenter/NoteDetailsPresenter.java
// public class NoteDetailsPresenter extends BasePresenter<INoteDetailsView> {
// public NoteDetailsPresenter(INoteDetailsView view){
// super(view);
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/ui/iview/INoteDetailsView.java
// public interface INoteDetailsView extends IBaseView {
// }
//
// Path: app/src/main/java/com/hhl/devheadline/utils/AppTools.java
// public class AppTools {
// /**
// * 截取长字符
// * @param str
// * @return
// */
// public static String clipLongText(String str) {
// if (str != null) {
// final String encoding = "GBK";
// try {
// byte[] b = str.getBytes(encoding);
// if (b.length > 20) {
// int end = 16;
// String result = new String(b, 0, end, encoding);
// if (str.indexOf(result) == -1) {
// return new String(b, 0, end - 1, encoding) + "...";
// }
// return result + "...";
// }
// } catch (UnsupportedEncodingException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// }
// return str;
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/utils/ToastUtils.java
// public class ToastUtils {
//
// /**
// * Toast
// *
// * @param content
// */
// public static void toast(final String content) {
// new Handler(Looper.getMainLooper()).post(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(DevHeadLineApplication.getInstance(), content, Toast.LENGTH_SHORT).show();
// }
// });
// }
//
// /**
// * Toast
// *
// * @param id
// */
// public static void toast(@StringRes int id) {
// toast(DevHeadLineApplication.getInstance().getResources().getString(id));
// }
// }
// Path: app/src/main/java/com/hhl/devheadline/ui/activity/NoteDetailsActivity.java
import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.hhl.devheadline.R;
import com.hhl.devheadline.presenter.NoteDetailsPresenter;
import com.hhl.devheadline.ui.iview.INoteDetailsView;
import com.hhl.devheadline.utils.AppTools;
import com.hhl.devheadline.utils.ToastUtils;
import butterknife.Bind;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
if (newProgress > progressBar.getProgress()) {
progressBar.setProgress(newProgress);
}
}
// TODO Auto-generated method stub
super.onProgressChanged(view, newProgress);
}
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
result.confirm();
ToastUtils.toast(message);
return true;
}
@Override
public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
result.confirm();
return super.onJsConfirm(view, url, message, result);
}
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
result.confirm();
return super.onJsPrompt(view, url, message, message, result);
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title); | toolbar.setTitle(AppTools.clipLongText(title)); |
hanhailong/DevHeadLine | app/src/main/java/com/hhl/devheadline/core/net/RetrofitFactory.java | // Path: app/src/main/java/com/hhl/devheadline/utils/L.java
// public class L {
//
// private static final boolean DEBUG = BuildConfig.DEBUG;
//
// public static void e(String tag, String msg) {
// if (DEBUG) {
// Log.e(tag, msg);
// }
// }
//
// public static void d(String tag, String msg) {
// if (DEBUG) {
// Log.d(tag, msg);
// }
// }
//
// public static void w(String tag, String msg) {
// if (DEBUG) {
// Log.e(tag, msg);
// }
// }
//
// public static void i(String tag, String msg) {
// if (DEBUG) {
// Log.e(tag, msg);
// }
// }
//
// public static void v(String tag, String msg) {
// if (DEBUG) {
// Log.e(tag, msg);
// }
// }
// }
| import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hhl.devheadline.utils.L;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.schedulers.Schedulers; | package com.hhl.devheadline.core.net;
/**
* Created by HanHailong on 16/3/16.
*/
public class RetrofitFactory {
/**
* 开发者头条BaseUrl
*/
private static final String host = "http://api.toutiao.io/v2/";
private static final Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").serializeNulls()
.create();
private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String url = request.url().toString(); | // Path: app/src/main/java/com/hhl/devheadline/utils/L.java
// public class L {
//
// private static final boolean DEBUG = BuildConfig.DEBUG;
//
// public static void e(String tag, String msg) {
// if (DEBUG) {
// Log.e(tag, msg);
// }
// }
//
// public static void d(String tag, String msg) {
// if (DEBUG) {
// Log.d(tag, msg);
// }
// }
//
// public static void w(String tag, String msg) {
// if (DEBUG) {
// Log.e(tag, msg);
// }
// }
//
// public static void i(String tag, String msg) {
// if (DEBUG) {
// Log.e(tag, msg);
// }
// }
//
// public static void v(String tag, String msg) {
// if (DEBUG) {
// Log.e(tag, msg);
// }
// }
// }
// Path: app/src/main/java/com/hhl/devheadline/core/net/RetrofitFactory.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hhl.devheadline.utils.L;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.schedulers.Schedulers;
package com.hhl.devheadline.core.net;
/**
* Created by HanHailong on 16/3/16.
*/
public class RetrofitFactory {
/**
* 开发者头条BaseUrl
*/
private static final String host = "http://api.toutiao.io/v2/";
private static final Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").serializeNulls()
.create();
private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String url = request.url().toString(); | L.e("请求的url", url); |
hanhailong/DevHeadLine | app/src/main/java/com/hhl/devheadline/core/net/ApiService.java | // Path: app/src/main/java/com/hhl/devheadline/model/resp/ArticleResp.java
// public class ArticleResp extends BaseResp {
//
// private Data data;
//
// public Data getData() {
// return data;
// }
//
// public void setData(Data data) {
// this.data = data;
// }
//
// public static class Data {
// /**
// * date : 2016-03-17
// * pre_date : 2016-03-16
// * next_date :
// * is_today : true
// * share_url : http://toutiao.io
// */
//
// private String date;
// private String pre_date;
// private String next_date;
// private boolean is_today;
// private String share_url;
// private List<Article> article;
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// public String getPre_date() {
// return pre_date;
// }
//
// public void setPre_date(String pre_date) {
// this.pre_date = pre_date;
// }
//
// public String getNext_date() {
// return next_date;
// }
//
// public void setNext_date(String next_date) {
// this.next_date = next_date;
// }
//
// public boolean isIs_today() {
// return is_today;
// }
//
// public void setIs_today(boolean is_today) {
// this.is_today = is_today;
// }
//
// public String getShare_url() {
// return share_url;
// }
//
// public void setShare_url(String share_url) {
// this.share_url = share_url;
// }
//
// public List<Article> getArticle() {
// return article;
// }
//
// public void setArticle(List<Article> article) {
// this.article = article;
// }
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/model/resp/BannerResp.java
// public class BannerResp extends BaseResp {
//
// private List<Banner> data;
//
// public List<Banner> getData() {
// return data;
// }
//
// public void setData(List<Banner> data) {
// this.data = data;
// }
// }
| import com.hhl.devheadline.model.resp.ArticleResp;
import com.hhl.devheadline.model.resp.BannerResp;
import retrofit2.http.GET;
import rx.Observable; | package com.hhl.devheadline.core.net;
/**
* Created by HanHailong on 16/3/16.
*/
public interface ApiService {
/**
* 获取Banner列表
*/
@GET("banner?app_key=u1ntgkc99st7sdhqjo5p×tamp=1458135621&signature=de53ae34c31ce857ea881102a100c7fb2d76aa36") | // Path: app/src/main/java/com/hhl/devheadline/model/resp/ArticleResp.java
// public class ArticleResp extends BaseResp {
//
// private Data data;
//
// public Data getData() {
// return data;
// }
//
// public void setData(Data data) {
// this.data = data;
// }
//
// public static class Data {
// /**
// * date : 2016-03-17
// * pre_date : 2016-03-16
// * next_date :
// * is_today : true
// * share_url : http://toutiao.io
// */
//
// private String date;
// private String pre_date;
// private String next_date;
// private boolean is_today;
// private String share_url;
// private List<Article> article;
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// public String getPre_date() {
// return pre_date;
// }
//
// public void setPre_date(String pre_date) {
// this.pre_date = pre_date;
// }
//
// public String getNext_date() {
// return next_date;
// }
//
// public void setNext_date(String next_date) {
// this.next_date = next_date;
// }
//
// public boolean isIs_today() {
// return is_today;
// }
//
// public void setIs_today(boolean is_today) {
// this.is_today = is_today;
// }
//
// public String getShare_url() {
// return share_url;
// }
//
// public void setShare_url(String share_url) {
// this.share_url = share_url;
// }
//
// public List<Article> getArticle() {
// return article;
// }
//
// public void setArticle(List<Article> article) {
// this.article = article;
// }
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/model/resp/BannerResp.java
// public class BannerResp extends BaseResp {
//
// private List<Banner> data;
//
// public List<Banner> getData() {
// return data;
// }
//
// public void setData(List<Banner> data) {
// this.data = data;
// }
// }
// Path: app/src/main/java/com/hhl/devheadline/core/net/ApiService.java
import com.hhl.devheadline.model.resp.ArticleResp;
import com.hhl.devheadline.model.resp.BannerResp;
import retrofit2.http.GET;
import rx.Observable;
package com.hhl.devheadline.core.net;
/**
* Created by HanHailong on 16/3/16.
*/
public interface ApiService {
/**
* 获取Banner列表
*/
@GET("banner?app_key=u1ntgkc99st7sdhqjo5p×tamp=1458135621&signature=de53ae34c31ce857ea881102a100c7fb2d76aa36") | Observable<BannerResp> loadBannerList(); |
hanhailong/DevHeadLine | app/src/main/java/com/hhl/devheadline/core/net/ApiService.java | // Path: app/src/main/java/com/hhl/devheadline/model/resp/ArticleResp.java
// public class ArticleResp extends BaseResp {
//
// private Data data;
//
// public Data getData() {
// return data;
// }
//
// public void setData(Data data) {
// this.data = data;
// }
//
// public static class Data {
// /**
// * date : 2016-03-17
// * pre_date : 2016-03-16
// * next_date :
// * is_today : true
// * share_url : http://toutiao.io
// */
//
// private String date;
// private String pre_date;
// private String next_date;
// private boolean is_today;
// private String share_url;
// private List<Article> article;
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// public String getPre_date() {
// return pre_date;
// }
//
// public void setPre_date(String pre_date) {
// this.pre_date = pre_date;
// }
//
// public String getNext_date() {
// return next_date;
// }
//
// public void setNext_date(String next_date) {
// this.next_date = next_date;
// }
//
// public boolean isIs_today() {
// return is_today;
// }
//
// public void setIs_today(boolean is_today) {
// this.is_today = is_today;
// }
//
// public String getShare_url() {
// return share_url;
// }
//
// public void setShare_url(String share_url) {
// this.share_url = share_url;
// }
//
// public List<Article> getArticle() {
// return article;
// }
//
// public void setArticle(List<Article> article) {
// this.article = article;
// }
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/model/resp/BannerResp.java
// public class BannerResp extends BaseResp {
//
// private List<Banner> data;
//
// public List<Banner> getData() {
// return data;
// }
//
// public void setData(List<Banner> data) {
// this.data = data;
// }
// }
| import com.hhl.devheadline.model.resp.ArticleResp;
import com.hhl.devheadline.model.resp.BannerResp;
import retrofit2.http.GET;
import rx.Observable; | package com.hhl.devheadline.core.net;
/**
* Created by HanHailong on 16/3/16.
*/
public interface ApiService {
/**
* 获取Banner列表
*/
@GET("banner?app_key=u1ntgkc99st7sdhqjo5p×tamp=1458135621&signature=de53ae34c31ce857ea881102a100c7fb2d76aa36")
Observable<BannerResp> loadBannerList();
@GET("dailies/latest?app_key=u1ntgkc99st7sdhqjo5p×tamp=1458230053&signature=0eeb89c7d2355de81c007d74869d9567e39210f2") | // Path: app/src/main/java/com/hhl/devheadline/model/resp/ArticleResp.java
// public class ArticleResp extends BaseResp {
//
// private Data data;
//
// public Data getData() {
// return data;
// }
//
// public void setData(Data data) {
// this.data = data;
// }
//
// public static class Data {
// /**
// * date : 2016-03-17
// * pre_date : 2016-03-16
// * next_date :
// * is_today : true
// * share_url : http://toutiao.io
// */
//
// private String date;
// private String pre_date;
// private String next_date;
// private boolean is_today;
// private String share_url;
// private List<Article> article;
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// public String getPre_date() {
// return pre_date;
// }
//
// public void setPre_date(String pre_date) {
// this.pre_date = pre_date;
// }
//
// public String getNext_date() {
// return next_date;
// }
//
// public void setNext_date(String next_date) {
// this.next_date = next_date;
// }
//
// public boolean isIs_today() {
// return is_today;
// }
//
// public void setIs_today(boolean is_today) {
// this.is_today = is_today;
// }
//
// public String getShare_url() {
// return share_url;
// }
//
// public void setShare_url(String share_url) {
// this.share_url = share_url;
// }
//
// public List<Article> getArticle() {
// return article;
// }
//
// public void setArticle(List<Article> article) {
// this.article = article;
// }
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/model/resp/BannerResp.java
// public class BannerResp extends BaseResp {
//
// private List<Banner> data;
//
// public List<Banner> getData() {
// return data;
// }
//
// public void setData(List<Banner> data) {
// this.data = data;
// }
// }
// Path: app/src/main/java/com/hhl/devheadline/core/net/ApiService.java
import com.hhl.devheadline.model.resp.ArticleResp;
import com.hhl.devheadline.model.resp.BannerResp;
import retrofit2.http.GET;
import rx.Observable;
package com.hhl.devheadline.core.net;
/**
* Created by HanHailong on 16/3/16.
*/
public interface ApiService {
/**
* 获取Banner列表
*/
@GET("banner?app_key=u1ntgkc99st7sdhqjo5p×tamp=1458135621&signature=de53ae34c31ce857ea881102a100c7fb2d76aa36")
Observable<BannerResp> loadBannerList();
@GET("dailies/latest?app_key=u1ntgkc99st7sdhqjo5p×tamp=1458230053&signature=0eeb89c7d2355de81c007d74869d9567e39210f2") | Observable<ArticleResp> loadArticleList(); |
hanhailong/DevHeadLine | app/src/main/java/com/hhl/devheadline/utils/ToastUtils.java | // Path: app/src/main/java/com/hhl/devheadline/DevHeadLineApplication.java
// public class DevHeadLineApplication extends Application {
//
// private static DevHeadLineApplication mInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// Fresco.initialize(this);
// mInstance = this;
// }
//
// /**
// * 获取唯一Application
// *
// * @return
// */
// public static DevHeadLineApplication getInstance() {
// return mInstance;
// }
// }
| import android.os.Handler;
import android.os.Looper;
import android.support.annotation.StringRes;
import android.widget.Toast;
import com.hhl.devheadline.DevHeadLineApplication; | package com.hhl.devheadline.utils;
/**
* Toast工具类,可以在任何线程都可以Toast的工具类
* Created by HanHailong on 16/4/4.
*/
public class ToastUtils {
/**
* Toast
*
* @param content
*/
public static void toast(final String content) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() { | // Path: app/src/main/java/com/hhl/devheadline/DevHeadLineApplication.java
// public class DevHeadLineApplication extends Application {
//
// private static DevHeadLineApplication mInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// Fresco.initialize(this);
// mInstance = this;
// }
//
// /**
// * 获取唯一Application
// *
// * @return
// */
// public static DevHeadLineApplication getInstance() {
// return mInstance;
// }
// }
// Path: app/src/main/java/com/hhl/devheadline/utils/ToastUtils.java
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.StringRes;
import android.widget.Toast;
import com.hhl.devheadline.DevHeadLineApplication;
package com.hhl.devheadline.utils;
/**
* Toast工具类,可以在任何线程都可以Toast的工具类
* Created by HanHailong on 16/4/4.
*/
public class ToastUtils {
/**
* Toast
*
* @param content
*/
public static void toast(final String content) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() { | Toast.makeText(DevHeadLineApplication.getInstance(), content, Toast.LENGTH_SHORT).show(); |
hanhailong/DevHeadLine | app/src/main/java/com/hhl/devheadline/presenter/BasePresenter.java | // Path: app/src/main/java/com/hhl/devheadline/core/net/ApiService.java
// public interface ApiService {
//
// /**
// * 获取Banner列表
// */
// @GET("banner?app_key=u1ntgkc99st7sdhqjo5p×tamp=1458135621&signature=de53ae34c31ce857ea881102a100c7fb2d76aa36")
// Observable<BannerResp> loadBannerList();
//
// @GET("dailies/latest?app_key=u1ntgkc99st7sdhqjo5p×tamp=1458230053&signature=0eeb89c7d2355de81c007d74869d9567e39210f2")
// Observable<ArticleResp> loadArticleList();
// }
//
// Path: app/src/main/java/com/hhl/devheadline/core/net/RetrofitFactory.java
// public class RetrofitFactory {
//
// /**
// * 开发者头条BaseUrl
// */
// private static final String host = "http://api.toutiao.io/v2/";
//
// private static final Gson gson = new GsonBuilder()
// .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").serializeNulls()
// .create();
//
// private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder()
// .addInterceptor(new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// String url = request.url().toString();
// L.e("请求的url", url);
//
// // TODO: (hhl) 拦截返回的结果
// Response response = chain.proceed(chain.request());
//
//
// // TODO: (hhl) 以后优化
//
// return response;
// }
// }).build();
//
// public static ApiService getApiService() {
// return SingletonHolder.apiService;
// }
//
// /**
// * 采用精通内部类的方式来实现单例
// */
// private static class SingletonHolder {
// static Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(host)
// .client(OK_HTTP_CLIENT)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
// .build();
//
// private static final ApiService apiService = retrofit.create(ApiService.class);
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/ui/iview/IBaseView.java
// public interface IBaseView {
//
// }
| import com.hhl.devheadline.core.net.ApiService;
import com.hhl.devheadline.core.net.RetrofitFactory;
import com.hhl.devheadline.ui.iview.IBaseView;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference; | package com.hhl.devheadline.presenter;
/**
* the base presenter of all presenters
* if you use a presenter,it must be extends {@link BasePresenter}
* Created by HanHailong on 16/3/15.
*/
public abstract class BasePresenter<V extends IBaseView> {
private Reference<V> mViewRef;
protected V mView;
| // Path: app/src/main/java/com/hhl/devheadline/core/net/ApiService.java
// public interface ApiService {
//
// /**
// * 获取Banner列表
// */
// @GET("banner?app_key=u1ntgkc99st7sdhqjo5p×tamp=1458135621&signature=de53ae34c31ce857ea881102a100c7fb2d76aa36")
// Observable<BannerResp> loadBannerList();
//
// @GET("dailies/latest?app_key=u1ntgkc99st7sdhqjo5p×tamp=1458230053&signature=0eeb89c7d2355de81c007d74869d9567e39210f2")
// Observable<ArticleResp> loadArticleList();
// }
//
// Path: app/src/main/java/com/hhl/devheadline/core/net/RetrofitFactory.java
// public class RetrofitFactory {
//
// /**
// * 开发者头条BaseUrl
// */
// private static final String host = "http://api.toutiao.io/v2/";
//
// private static final Gson gson = new GsonBuilder()
// .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").serializeNulls()
// .create();
//
// private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder()
// .addInterceptor(new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// String url = request.url().toString();
// L.e("请求的url", url);
//
// // TODO: (hhl) 拦截返回的结果
// Response response = chain.proceed(chain.request());
//
//
// // TODO: (hhl) 以后优化
//
// return response;
// }
// }).build();
//
// public static ApiService getApiService() {
// return SingletonHolder.apiService;
// }
//
// /**
// * 采用精通内部类的方式来实现单例
// */
// private static class SingletonHolder {
// static Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(host)
// .client(OK_HTTP_CLIENT)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
// .build();
//
// private static final ApiService apiService = retrofit.create(ApiService.class);
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/ui/iview/IBaseView.java
// public interface IBaseView {
//
// }
// Path: app/src/main/java/com/hhl/devheadline/presenter/BasePresenter.java
import com.hhl.devheadline.core.net.ApiService;
import com.hhl.devheadline.core.net.RetrofitFactory;
import com.hhl.devheadline.ui.iview.IBaseView;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
package com.hhl.devheadline.presenter;
/**
* the base presenter of all presenters
* if you use a presenter,it must be extends {@link BasePresenter}
* Created by HanHailong on 16/3/15.
*/
public abstract class BasePresenter<V extends IBaseView> {
private Reference<V> mViewRef;
protected V mView;
| protected static final ApiService mApiService = RetrofitFactory.getApiService(); |
hanhailong/DevHeadLine | app/src/main/java/com/hhl/devheadline/presenter/BasePresenter.java | // Path: app/src/main/java/com/hhl/devheadline/core/net/ApiService.java
// public interface ApiService {
//
// /**
// * 获取Banner列表
// */
// @GET("banner?app_key=u1ntgkc99st7sdhqjo5p×tamp=1458135621&signature=de53ae34c31ce857ea881102a100c7fb2d76aa36")
// Observable<BannerResp> loadBannerList();
//
// @GET("dailies/latest?app_key=u1ntgkc99st7sdhqjo5p×tamp=1458230053&signature=0eeb89c7d2355de81c007d74869d9567e39210f2")
// Observable<ArticleResp> loadArticleList();
// }
//
// Path: app/src/main/java/com/hhl/devheadline/core/net/RetrofitFactory.java
// public class RetrofitFactory {
//
// /**
// * 开发者头条BaseUrl
// */
// private static final String host = "http://api.toutiao.io/v2/";
//
// private static final Gson gson = new GsonBuilder()
// .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").serializeNulls()
// .create();
//
// private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder()
// .addInterceptor(new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// String url = request.url().toString();
// L.e("请求的url", url);
//
// // TODO: (hhl) 拦截返回的结果
// Response response = chain.proceed(chain.request());
//
//
// // TODO: (hhl) 以后优化
//
// return response;
// }
// }).build();
//
// public static ApiService getApiService() {
// return SingletonHolder.apiService;
// }
//
// /**
// * 采用精通内部类的方式来实现单例
// */
// private static class SingletonHolder {
// static Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(host)
// .client(OK_HTTP_CLIENT)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
// .build();
//
// private static final ApiService apiService = retrofit.create(ApiService.class);
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/ui/iview/IBaseView.java
// public interface IBaseView {
//
// }
| import com.hhl.devheadline.core.net.ApiService;
import com.hhl.devheadline.core.net.RetrofitFactory;
import com.hhl.devheadline.ui.iview.IBaseView;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference; | package com.hhl.devheadline.presenter;
/**
* the base presenter of all presenters
* if you use a presenter,it must be extends {@link BasePresenter}
* Created by HanHailong on 16/3/15.
*/
public abstract class BasePresenter<V extends IBaseView> {
private Reference<V> mViewRef;
protected V mView;
| // Path: app/src/main/java/com/hhl/devheadline/core/net/ApiService.java
// public interface ApiService {
//
// /**
// * 获取Banner列表
// */
// @GET("banner?app_key=u1ntgkc99st7sdhqjo5p×tamp=1458135621&signature=de53ae34c31ce857ea881102a100c7fb2d76aa36")
// Observable<BannerResp> loadBannerList();
//
// @GET("dailies/latest?app_key=u1ntgkc99st7sdhqjo5p×tamp=1458230053&signature=0eeb89c7d2355de81c007d74869d9567e39210f2")
// Observable<ArticleResp> loadArticleList();
// }
//
// Path: app/src/main/java/com/hhl/devheadline/core/net/RetrofitFactory.java
// public class RetrofitFactory {
//
// /**
// * 开发者头条BaseUrl
// */
// private static final String host = "http://api.toutiao.io/v2/";
//
// private static final Gson gson = new GsonBuilder()
// .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").serializeNulls()
// .create();
//
// private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder()
// .addInterceptor(new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// String url = request.url().toString();
// L.e("请求的url", url);
//
// // TODO: (hhl) 拦截返回的结果
// Response response = chain.proceed(chain.request());
//
//
// // TODO: (hhl) 以后优化
//
// return response;
// }
// }).build();
//
// public static ApiService getApiService() {
// return SingletonHolder.apiService;
// }
//
// /**
// * 采用精通内部类的方式来实现单例
// */
// private static class SingletonHolder {
// static Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(host)
// .client(OK_HTTP_CLIENT)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
// .build();
//
// private static final ApiService apiService = retrofit.create(ApiService.class);
// }
// }
//
// Path: app/src/main/java/com/hhl/devheadline/ui/iview/IBaseView.java
// public interface IBaseView {
//
// }
// Path: app/src/main/java/com/hhl/devheadline/presenter/BasePresenter.java
import com.hhl.devheadline.core.net.ApiService;
import com.hhl.devheadline.core.net.RetrofitFactory;
import com.hhl.devheadline.ui.iview.IBaseView;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
package com.hhl.devheadline.presenter;
/**
* the base presenter of all presenters
* if you use a presenter,it must be extends {@link BasePresenter}
* Created by HanHailong on 16/3/15.
*/
public abstract class BasePresenter<V extends IBaseView> {
private Reference<V> mViewRef;
protected V mView;
| protected static final ApiService mApiService = RetrofitFactory.getApiService(); |
mergehez/ArgPlayer | app/src/main/java/com/arges/sepan/argmusicplayersample/LargePlayerActivity.java | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgAudioList.java
// public class ArgAudioList {
// private final ArrayList<ArgAudio> list = new ArrayList<>();
// private int currentIndex = -1;
// private boolean repeat;
//
// public ArgAudioList(boolean repeat) {
// this.repeat = repeat;
// }
//
// public boolean hasNext() {
// return !isEmpty() && size() > 1 && (repeat || size() > currentIndex + 1);
// }
//
// public int getNextIndex() {
// return hasNext() ? getProperIndex(currentIndex + 1) : getCurrentIndex();
// }
//
// public boolean goToNext() {
// if (hasNext()) {
// changeCurrentIndex(currentIndex + 1);
// return true;
// }
// return false;
// }
//
// public boolean hasPrev() {
// return !isEmpty() && size() > 1 && (repeat || currentIndex > 0);
// }
//
// public int getPrevIndex() {
// return hasPrev() ? getProperIndex(currentIndex - 1) : getCurrentIndex();
// }
//
// public boolean goToPrev() {
// if (hasPrev()) {
// changeCurrentIndex(currentIndex - 1);
// return true;
// }
// return false;
// }
//
// private int changeCurrentIndex(int newIndex) {
// return currentIndex = (newIndex + size()) % size();
// }
//
// private int getProperIndex(int i) {
// return (i + size()) % size();
// }
//
// private int idForAudios = 0;
//
// public ArgAudioList add(@NonNull ArgAudio audio) {
// ArgAudio newAudio = audio.cloneAudio();
// newAudio.setId(idForAudios++);
// list.add(newAudio.convertToPlaylist());
// if (currentIndex == -1) changeCurrentIndex(0);
// return this;
// }
//
// public void goTo(int index) {
// changeCurrentIndex(index);
// }
//
// public ArgAudio getCurrentAudio() {
// return currentIndex >= 0 ? list.get(currentIndex) : null;
// }
//
// public boolean isRepeat() {
// return this.repeat;
// }
//
// public void setRepeat(boolean repeat) {
// this.repeat = repeat;
// }
//
// public int getCurrentIndex() {
// return currentIndex;
// }
//
//
// public int size() {
// return list.size();
// }
//
// public boolean isEmpty() {
// return size() == 0;
// }
//
// public boolean contains(ArgAudio o) {
// return list.contains(o);
// }
//
// public int indexOf(ArgAudio o) {
// return list.indexOf(o);
// }
//
// public void addAll(Collection<? extends ArgAudio> c) {
// for (ArgAudio a : c) add(a);
// }
//
// public void clear() {
// list.clear();
// idForAudios = 0;
// }
//
// public ArgAudio get(int index) {
// return list.get(index);
// }
//
// @NonNull
// public Iterator<ArgAudio> iterator() {
// return list.iterator();
// }
//
// public ArgAudio set(int index, ArgAudio element) {
// return list.set(index, element);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) return false;
// else if (!(obj instanceof ArgAudioList)) return false;
// else {
// ArgAudioList a = (ArgAudioList) obj;
// return !(a.isEmpty() || this.isEmpty())
// && this.size() == a.size()
// && this.get(0).equals(a.get(0))
// && this.get(this.size() - 1).equals(a.get(a.size() - 1));
// }
// }
// }
//
// Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/PlayerViews/ArgPlayerLargeView.java
// public class ArgPlayerLargeView extends ArgPlayerLargeViewRoot {
// public ArgPlayerLargeView(Context context) {
// super(context);
// }
//
// public ArgPlayerLargeView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public ArgPlayerLargeView(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// }
//
// @Override
// protected void init(Context context, int layoutResId) {
// super.init(context, R.layout.player_large_layout);
// }
// }
| import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatTextView;
import com.arges.sepan.argmusicplayer.Models.ArgAudioList;
import com.arges.sepan.argmusicplayer.PlayerViews.ArgPlayerLargeView;
import java.util.Locale; | package com.arges.sepan.argmusicplayersample;
public class LargePlayerActivity extends AppCompatActivity {
ArgPlayerLargeView musicPlayer;
AppCompatTextView tvError, tvMusicType; | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgAudioList.java
// public class ArgAudioList {
// private final ArrayList<ArgAudio> list = new ArrayList<>();
// private int currentIndex = -1;
// private boolean repeat;
//
// public ArgAudioList(boolean repeat) {
// this.repeat = repeat;
// }
//
// public boolean hasNext() {
// return !isEmpty() && size() > 1 && (repeat || size() > currentIndex + 1);
// }
//
// public int getNextIndex() {
// return hasNext() ? getProperIndex(currentIndex + 1) : getCurrentIndex();
// }
//
// public boolean goToNext() {
// if (hasNext()) {
// changeCurrentIndex(currentIndex + 1);
// return true;
// }
// return false;
// }
//
// public boolean hasPrev() {
// return !isEmpty() && size() > 1 && (repeat || currentIndex > 0);
// }
//
// public int getPrevIndex() {
// return hasPrev() ? getProperIndex(currentIndex - 1) : getCurrentIndex();
// }
//
// public boolean goToPrev() {
// if (hasPrev()) {
// changeCurrentIndex(currentIndex - 1);
// return true;
// }
// return false;
// }
//
// private int changeCurrentIndex(int newIndex) {
// return currentIndex = (newIndex + size()) % size();
// }
//
// private int getProperIndex(int i) {
// return (i + size()) % size();
// }
//
// private int idForAudios = 0;
//
// public ArgAudioList add(@NonNull ArgAudio audio) {
// ArgAudio newAudio = audio.cloneAudio();
// newAudio.setId(idForAudios++);
// list.add(newAudio.convertToPlaylist());
// if (currentIndex == -1) changeCurrentIndex(0);
// return this;
// }
//
// public void goTo(int index) {
// changeCurrentIndex(index);
// }
//
// public ArgAudio getCurrentAudio() {
// return currentIndex >= 0 ? list.get(currentIndex) : null;
// }
//
// public boolean isRepeat() {
// return this.repeat;
// }
//
// public void setRepeat(boolean repeat) {
// this.repeat = repeat;
// }
//
// public int getCurrentIndex() {
// return currentIndex;
// }
//
//
// public int size() {
// return list.size();
// }
//
// public boolean isEmpty() {
// return size() == 0;
// }
//
// public boolean contains(ArgAudio o) {
// return list.contains(o);
// }
//
// public int indexOf(ArgAudio o) {
// return list.indexOf(o);
// }
//
// public void addAll(Collection<? extends ArgAudio> c) {
// for (ArgAudio a : c) add(a);
// }
//
// public void clear() {
// list.clear();
// idForAudios = 0;
// }
//
// public ArgAudio get(int index) {
// return list.get(index);
// }
//
// @NonNull
// public Iterator<ArgAudio> iterator() {
// return list.iterator();
// }
//
// public ArgAudio set(int index, ArgAudio element) {
// return list.set(index, element);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) return false;
// else if (!(obj instanceof ArgAudioList)) return false;
// else {
// ArgAudioList a = (ArgAudioList) obj;
// return !(a.isEmpty() || this.isEmpty())
// && this.size() == a.size()
// && this.get(0).equals(a.get(0))
// && this.get(this.size() - 1).equals(a.get(a.size() - 1));
// }
// }
// }
//
// Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/PlayerViews/ArgPlayerLargeView.java
// public class ArgPlayerLargeView extends ArgPlayerLargeViewRoot {
// public ArgPlayerLargeView(Context context) {
// super(context);
// }
//
// public ArgPlayerLargeView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public ArgPlayerLargeView(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// }
//
// @Override
// protected void init(Context context, int layoutResId) {
// super.init(context, R.layout.player_large_layout);
// }
// }
// Path: app/src/main/java/com/arges/sepan/argmusicplayersample/LargePlayerActivity.java
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatTextView;
import com.arges.sepan.argmusicplayer.Models.ArgAudioList;
import com.arges.sepan.argmusicplayer.PlayerViews.ArgPlayerLargeView;
import java.util.Locale;
package com.arges.sepan.argmusicplayersample;
public class LargePlayerActivity extends AppCompatActivity {
ArgPlayerLargeView musicPlayer;
AppCompatTextView tvError, tvMusicType; | ArgAudioList playlist = new ArgAudioList(true); |
mergehez/ArgPlayer | argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgAudio.java | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Enums/AudioType.java
// public enum AudioType {
// URL,
// RAW,
// ASSETS,
// FILE_PATH
// }
| import androidx.annotation.RawRes;
import com.arges.sepan.argmusicplayer.Enums.AudioType; | package com.arges.sepan.argmusicplayer.Models;
public class ArgAudio {
private String singer, audioName, path;
private boolean isPlaylist = false; | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Enums/AudioType.java
// public enum AudioType {
// URL,
// RAW,
// ASSETS,
// FILE_PATH
// }
// Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgAudio.java
import androidx.annotation.RawRes;
import com.arges.sepan.argmusicplayer.Enums.AudioType;
package com.arges.sepan.argmusicplayer.Models;
public class ArgAudio {
private String singer, audioName, path;
private boolean isPlaylist = false; | private AudioType type; |
mergehez/ArgPlayer | app/src/main/java/com/arges/sepan/argmusicplayersample/SmallPlayerActivity.java | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgAudioList.java
// public class ArgAudioList {
// private final ArrayList<ArgAudio> list = new ArrayList<>();
// private int currentIndex = -1;
// private boolean repeat;
//
// public ArgAudioList(boolean repeat) {
// this.repeat = repeat;
// }
//
// public boolean hasNext() {
// return !isEmpty() && size() > 1 && (repeat || size() > currentIndex + 1);
// }
//
// public int getNextIndex() {
// return hasNext() ? getProperIndex(currentIndex + 1) : getCurrentIndex();
// }
//
// public boolean goToNext() {
// if (hasNext()) {
// changeCurrentIndex(currentIndex + 1);
// return true;
// }
// return false;
// }
//
// public boolean hasPrev() {
// return !isEmpty() && size() > 1 && (repeat || currentIndex > 0);
// }
//
// public int getPrevIndex() {
// return hasPrev() ? getProperIndex(currentIndex - 1) : getCurrentIndex();
// }
//
// public boolean goToPrev() {
// if (hasPrev()) {
// changeCurrentIndex(currentIndex - 1);
// return true;
// }
// return false;
// }
//
// private int changeCurrentIndex(int newIndex) {
// return currentIndex = (newIndex + size()) % size();
// }
//
// private int getProperIndex(int i) {
// return (i + size()) % size();
// }
//
// private int idForAudios = 0;
//
// public ArgAudioList add(@NonNull ArgAudio audio) {
// ArgAudio newAudio = audio.cloneAudio();
// newAudio.setId(idForAudios++);
// list.add(newAudio.convertToPlaylist());
// if (currentIndex == -1) changeCurrentIndex(0);
// return this;
// }
//
// public void goTo(int index) {
// changeCurrentIndex(index);
// }
//
// public ArgAudio getCurrentAudio() {
// return currentIndex >= 0 ? list.get(currentIndex) : null;
// }
//
// public boolean isRepeat() {
// return this.repeat;
// }
//
// public void setRepeat(boolean repeat) {
// this.repeat = repeat;
// }
//
// public int getCurrentIndex() {
// return currentIndex;
// }
//
//
// public int size() {
// return list.size();
// }
//
// public boolean isEmpty() {
// return size() == 0;
// }
//
// public boolean contains(ArgAudio o) {
// return list.contains(o);
// }
//
// public int indexOf(ArgAudio o) {
// return list.indexOf(o);
// }
//
// public void addAll(Collection<? extends ArgAudio> c) {
// for (ArgAudio a : c) add(a);
// }
//
// public void clear() {
// list.clear();
// idForAudios = 0;
// }
//
// public ArgAudio get(int index) {
// return list.get(index);
// }
//
// @NonNull
// public Iterator<ArgAudio> iterator() {
// return list.iterator();
// }
//
// public ArgAudio set(int index, ArgAudio element) {
// return list.set(index, element);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) return false;
// else if (!(obj instanceof ArgAudioList)) return false;
// else {
// ArgAudioList a = (ArgAudioList) obj;
// return !(a.isEmpty() || this.isEmpty())
// && this.size() == a.size()
// && this.get(0).equals(a.get(0))
// && this.get(this.size() - 1).equals(a.get(a.size() - 1));
// }
// }
// }
//
// Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/PlayerViews/ArgPlayerSmallView.java
// public class ArgPlayerSmallView extends ArgPlayerSmallViewRoot {
// public ArgPlayerSmallView(Context context) {
// super(context);
// }
//
// public ArgPlayerSmallView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public ArgPlayerSmallView(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// }
//
// @Override
// protected void init(Context context, int layoutResId) {
// super.init(context, R.layout.player_small_layout);
// }
// }
| import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatTextView;
import com.arges.sepan.argmusicplayer.Models.ArgAudioList;
import com.arges.sepan.argmusicplayer.PlayerViews.ArgPlayerSmallView;
import java.util.Locale; | package com.arges.sepan.argmusicplayersample;
public class SmallPlayerActivity extends AppCompatActivity {
ArgPlayerSmallView musicPlayer;
AppCompatTextView tvError, tvMusicType; | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgAudioList.java
// public class ArgAudioList {
// private final ArrayList<ArgAudio> list = new ArrayList<>();
// private int currentIndex = -1;
// private boolean repeat;
//
// public ArgAudioList(boolean repeat) {
// this.repeat = repeat;
// }
//
// public boolean hasNext() {
// return !isEmpty() && size() > 1 && (repeat || size() > currentIndex + 1);
// }
//
// public int getNextIndex() {
// return hasNext() ? getProperIndex(currentIndex + 1) : getCurrentIndex();
// }
//
// public boolean goToNext() {
// if (hasNext()) {
// changeCurrentIndex(currentIndex + 1);
// return true;
// }
// return false;
// }
//
// public boolean hasPrev() {
// return !isEmpty() && size() > 1 && (repeat || currentIndex > 0);
// }
//
// public int getPrevIndex() {
// return hasPrev() ? getProperIndex(currentIndex - 1) : getCurrentIndex();
// }
//
// public boolean goToPrev() {
// if (hasPrev()) {
// changeCurrentIndex(currentIndex - 1);
// return true;
// }
// return false;
// }
//
// private int changeCurrentIndex(int newIndex) {
// return currentIndex = (newIndex + size()) % size();
// }
//
// private int getProperIndex(int i) {
// return (i + size()) % size();
// }
//
// private int idForAudios = 0;
//
// public ArgAudioList add(@NonNull ArgAudio audio) {
// ArgAudio newAudio = audio.cloneAudio();
// newAudio.setId(idForAudios++);
// list.add(newAudio.convertToPlaylist());
// if (currentIndex == -1) changeCurrentIndex(0);
// return this;
// }
//
// public void goTo(int index) {
// changeCurrentIndex(index);
// }
//
// public ArgAudio getCurrentAudio() {
// return currentIndex >= 0 ? list.get(currentIndex) : null;
// }
//
// public boolean isRepeat() {
// return this.repeat;
// }
//
// public void setRepeat(boolean repeat) {
// this.repeat = repeat;
// }
//
// public int getCurrentIndex() {
// return currentIndex;
// }
//
//
// public int size() {
// return list.size();
// }
//
// public boolean isEmpty() {
// return size() == 0;
// }
//
// public boolean contains(ArgAudio o) {
// return list.contains(o);
// }
//
// public int indexOf(ArgAudio o) {
// return list.indexOf(o);
// }
//
// public void addAll(Collection<? extends ArgAudio> c) {
// for (ArgAudio a : c) add(a);
// }
//
// public void clear() {
// list.clear();
// idForAudios = 0;
// }
//
// public ArgAudio get(int index) {
// return list.get(index);
// }
//
// @NonNull
// public Iterator<ArgAudio> iterator() {
// return list.iterator();
// }
//
// public ArgAudio set(int index, ArgAudio element) {
// return list.set(index, element);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) return false;
// else if (!(obj instanceof ArgAudioList)) return false;
// else {
// ArgAudioList a = (ArgAudioList) obj;
// return !(a.isEmpty() || this.isEmpty())
// && this.size() == a.size()
// && this.get(0).equals(a.get(0))
// && this.get(this.size() - 1).equals(a.get(a.size() - 1));
// }
// }
// }
//
// Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/PlayerViews/ArgPlayerSmallView.java
// public class ArgPlayerSmallView extends ArgPlayerSmallViewRoot {
// public ArgPlayerSmallView(Context context) {
// super(context);
// }
//
// public ArgPlayerSmallView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public ArgPlayerSmallView(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// }
//
// @Override
// protected void init(Context context, int layoutResId) {
// super.init(context, R.layout.player_small_layout);
// }
// }
// Path: app/src/main/java/com/arges/sepan/argmusicplayersample/SmallPlayerActivity.java
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatTextView;
import com.arges.sepan.argmusicplayer.Models.ArgAudioList;
import com.arges.sepan.argmusicplayer.PlayerViews.ArgPlayerSmallView;
import java.util.Locale;
package com.arges.sepan.argmusicplayersample;
public class SmallPlayerActivity extends AppCompatActivity {
ArgPlayerSmallView musicPlayer;
AppCompatTextView tvError, tvMusicType; | ArgAudioList playlist = new ArgAudioList(true); |
mergehez/ArgPlayer | argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgNotificationOptions.java | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Callbacks/OnBuildNotificationListener.java
// public interface OnBuildNotificationListener {
// void onBuildNotification(Notification.Builder builder);
// void onBuildNotificationChannel(NotificationChannel notificationChannel);
// }
| import static android.os.Build.VERSION_CODES.O;
import android.app.Activity;
import androidx.annotation.RequiresApi;
import com.arges.sepan.argmusicplayer.Callbacks.OnBuildNotificationListener;
import com.arges.sepan.argmusicplayer.R; | package com.arges.sepan.argmusicplayer.Models;
public class ArgNotificationOptions {
private boolean enabled = true;
private boolean progressEnabled = false;
private String channelId;
private CharSequence channelName;
private int notificationId = 548853;
private int imageResoureId = R.drawable.mergesoftlogo; | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Callbacks/OnBuildNotificationListener.java
// public interface OnBuildNotificationListener {
// void onBuildNotification(Notification.Builder builder);
// void onBuildNotificationChannel(NotificationChannel notificationChannel);
// }
// Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgNotificationOptions.java
import static android.os.Build.VERSION_CODES.O;
import android.app.Activity;
import androidx.annotation.RequiresApi;
import com.arges.sepan.argmusicplayer.Callbacks.OnBuildNotificationListener;
import com.arges.sepan.argmusicplayer.R;
package com.arges.sepan.argmusicplayer.Models;
public class ArgNotificationOptions {
private boolean enabled = true;
private boolean progressEnabled = false;
private String channelId;
private CharSequence channelName;
private int notificationId = 548853;
private int imageResoureId = R.drawable.mergesoftlogo; | private OnBuildNotificationListener listener = null; |
mergehez/ArgPlayer | argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/ArgPlayerFullScreenViewRoot.java | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgAudioList.java
// public class ArgAudioList {
// private final ArrayList<ArgAudio> list = new ArrayList<>();
// private int currentIndex = -1;
// private boolean repeat;
//
// public ArgAudioList(boolean repeat) {
// this.repeat = repeat;
// }
//
// public boolean hasNext() {
// return !isEmpty() && size() > 1 && (repeat || size() > currentIndex + 1);
// }
//
// public int getNextIndex() {
// return hasNext() ? getProperIndex(currentIndex + 1) : getCurrentIndex();
// }
//
// public boolean goToNext() {
// if (hasNext()) {
// changeCurrentIndex(currentIndex + 1);
// return true;
// }
// return false;
// }
//
// public boolean hasPrev() {
// return !isEmpty() && size() > 1 && (repeat || currentIndex > 0);
// }
//
// public int getPrevIndex() {
// return hasPrev() ? getProperIndex(currentIndex - 1) : getCurrentIndex();
// }
//
// public boolean goToPrev() {
// if (hasPrev()) {
// changeCurrentIndex(currentIndex - 1);
// return true;
// }
// return false;
// }
//
// private int changeCurrentIndex(int newIndex) {
// return currentIndex = (newIndex + size()) % size();
// }
//
// private int getProperIndex(int i) {
// return (i + size()) % size();
// }
//
// private int idForAudios = 0;
//
// public ArgAudioList add(@NonNull ArgAudio audio) {
// ArgAudio newAudio = audio.cloneAudio();
// newAudio.setId(idForAudios++);
// list.add(newAudio.convertToPlaylist());
// if (currentIndex == -1) changeCurrentIndex(0);
// return this;
// }
//
// public void goTo(int index) {
// changeCurrentIndex(index);
// }
//
// public ArgAudio getCurrentAudio() {
// return currentIndex >= 0 ? list.get(currentIndex) : null;
// }
//
// public boolean isRepeat() {
// return this.repeat;
// }
//
// public void setRepeat(boolean repeat) {
// this.repeat = repeat;
// }
//
// public int getCurrentIndex() {
// return currentIndex;
// }
//
//
// public int size() {
// return list.size();
// }
//
// public boolean isEmpty() {
// return size() == 0;
// }
//
// public boolean contains(ArgAudio o) {
// return list.contains(o);
// }
//
// public int indexOf(ArgAudio o) {
// return list.indexOf(o);
// }
//
// public void addAll(Collection<? extends ArgAudio> c) {
// for (ArgAudio a : c) add(a);
// }
//
// public void clear() {
// list.clear();
// idForAudios = 0;
// }
//
// public ArgAudio get(int index) {
// return list.get(index);
// }
//
// @NonNull
// public Iterator<ArgAudio> iterator() {
// return list.iterator();
// }
//
// public ArgAudio set(int index, ArgAudio element) {
// return list.set(index, element);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) return false;
// else if (!(obj instanceof ArgAudioList)) return false;
// else {
// ArgAudioList a = (ArgAudioList) obj;
// return !(a.isEmpty() || this.isEmpty())
// && this.size() == a.size()
// && this.get(0).equals(a.get(0))
// && this.get(this.size() - 1).equals(a.get(a.size() - 1));
// }
// }
// }
//
// Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Views/ArgPlaylistListView.java
// public class ArgPlaylistListView extends ListView {
// private Context context;
// private int selectedPosition = 0;
// private ArgPlaylistViewAdapter adapter;
//
// public ArgPlaylistListView(Context context) {
// super(context);
// init(context);
// }
//
// public ArgPlaylistListView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init(context);
// }
//
// public ArgPlaylistListView(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// init(context);
// }
//
// private void init(Context context) {
// this.context = context;
// }
//
// public void setAdapter(final ArgAudioList argAudioList) {
// adapter = new ArgPlaylistViewAdapter(this, context, argAudioList);
// setAdapter(adapter);
// }
//
// public ArgPlaylistViewAdapter getAdapter() {
// return adapter;
// }
//
// public void setSelectedPosition(int position) {
// selectedPosition = position;
// }
//
// public int getSelectedPosition() {
// return selectedPosition;
// }
//
// public void scrollToSelected() {
// new Handler().post(() -> setSelection(getSelectedItemPosition()));
// }
// }
| import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.appcompat.widget.AppCompatTextView;
import com.arges.sepan.argmusicplayer.Models.ArgAudioList;
import com.arges.sepan.argmusicplayer.Views.ArgPlaylistListView;
import java.util.Locale; | package com.arges.sepan.argmusicplayer;
public abstract class ArgPlayerFullScreenViewRoot extends ArgPlayerLargeViewRoot {
LinearLayout layPanelPlaylist; | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgAudioList.java
// public class ArgAudioList {
// private final ArrayList<ArgAudio> list = new ArrayList<>();
// private int currentIndex = -1;
// private boolean repeat;
//
// public ArgAudioList(boolean repeat) {
// this.repeat = repeat;
// }
//
// public boolean hasNext() {
// return !isEmpty() && size() > 1 && (repeat || size() > currentIndex + 1);
// }
//
// public int getNextIndex() {
// return hasNext() ? getProperIndex(currentIndex + 1) : getCurrentIndex();
// }
//
// public boolean goToNext() {
// if (hasNext()) {
// changeCurrentIndex(currentIndex + 1);
// return true;
// }
// return false;
// }
//
// public boolean hasPrev() {
// return !isEmpty() && size() > 1 && (repeat || currentIndex > 0);
// }
//
// public int getPrevIndex() {
// return hasPrev() ? getProperIndex(currentIndex - 1) : getCurrentIndex();
// }
//
// public boolean goToPrev() {
// if (hasPrev()) {
// changeCurrentIndex(currentIndex - 1);
// return true;
// }
// return false;
// }
//
// private int changeCurrentIndex(int newIndex) {
// return currentIndex = (newIndex + size()) % size();
// }
//
// private int getProperIndex(int i) {
// return (i + size()) % size();
// }
//
// private int idForAudios = 0;
//
// public ArgAudioList add(@NonNull ArgAudio audio) {
// ArgAudio newAudio = audio.cloneAudio();
// newAudio.setId(idForAudios++);
// list.add(newAudio.convertToPlaylist());
// if (currentIndex == -1) changeCurrentIndex(0);
// return this;
// }
//
// public void goTo(int index) {
// changeCurrentIndex(index);
// }
//
// public ArgAudio getCurrentAudio() {
// return currentIndex >= 0 ? list.get(currentIndex) : null;
// }
//
// public boolean isRepeat() {
// return this.repeat;
// }
//
// public void setRepeat(boolean repeat) {
// this.repeat = repeat;
// }
//
// public int getCurrentIndex() {
// return currentIndex;
// }
//
//
// public int size() {
// return list.size();
// }
//
// public boolean isEmpty() {
// return size() == 0;
// }
//
// public boolean contains(ArgAudio o) {
// return list.contains(o);
// }
//
// public int indexOf(ArgAudio o) {
// return list.indexOf(o);
// }
//
// public void addAll(Collection<? extends ArgAudio> c) {
// for (ArgAudio a : c) add(a);
// }
//
// public void clear() {
// list.clear();
// idForAudios = 0;
// }
//
// public ArgAudio get(int index) {
// return list.get(index);
// }
//
// @NonNull
// public Iterator<ArgAudio> iterator() {
// return list.iterator();
// }
//
// public ArgAudio set(int index, ArgAudio element) {
// return list.set(index, element);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) return false;
// else if (!(obj instanceof ArgAudioList)) return false;
// else {
// ArgAudioList a = (ArgAudioList) obj;
// return !(a.isEmpty() || this.isEmpty())
// && this.size() == a.size()
// && this.get(0).equals(a.get(0))
// && this.get(this.size() - 1).equals(a.get(a.size() - 1));
// }
// }
// }
//
// Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Views/ArgPlaylistListView.java
// public class ArgPlaylistListView extends ListView {
// private Context context;
// private int selectedPosition = 0;
// private ArgPlaylistViewAdapter adapter;
//
// public ArgPlaylistListView(Context context) {
// super(context);
// init(context);
// }
//
// public ArgPlaylistListView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init(context);
// }
//
// public ArgPlaylistListView(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// init(context);
// }
//
// private void init(Context context) {
// this.context = context;
// }
//
// public void setAdapter(final ArgAudioList argAudioList) {
// adapter = new ArgPlaylistViewAdapter(this, context, argAudioList);
// setAdapter(adapter);
// }
//
// public ArgPlaylistViewAdapter getAdapter() {
// return adapter;
// }
//
// public void setSelectedPosition(int position) {
// selectedPosition = position;
// }
//
// public int getSelectedPosition() {
// return selectedPosition;
// }
//
// public void scrollToSelected() {
// new Handler().post(() -> setSelection(getSelectedItemPosition()));
// }
// }
// Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/ArgPlayerFullScreenViewRoot.java
import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.appcompat.widget.AppCompatTextView;
import com.arges.sepan.argmusicplayer.Models.ArgAudioList;
import com.arges.sepan.argmusicplayer.Views.ArgPlaylistListView;
import java.util.Locale;
package com.arges.sepan.argmusicplayer;
public abstract class ArgPlayerFullScreenViewRoot extends ArgPlayerLargeViewRoot {
LinearLayout layPanelPlaylist; | ArgPlaylistListView listView; |
mergehez/ArgPlayer | argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/ArgPlayerFullScreenViewRoot.java | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgAudioList.java
// public class ArgAudioList {
// private final ArrayList<ArgAudio> list = new ArrayList<>();
// private int currentIndex = -1;
// private boolean repeat;
//
// public ArgAudioList(boolean repeat) {
// this.repeat = repeat;
// }
//
// public boolean hasNext() {
// return !isEmpty() && size() > 1 && (repeat || size() > currentIndex + 1);
// }
//
// public int getNextIndex() {
// return hasNext() ? getProperIndex(currentIndex + 1) : getCurrentIndex();
// }
//
// public boolean goToNext() {
// if (hasNext()) {
// changeCurrentIndex(currentIndex + 1);
// return true;
// }
// return false;
// }
//
// public boolean hasPrev() {
// return !isEmpty() && size() > 1 && (repeat || currentIndex > 0);
// }
//
// public int getPrevIndex() {
// return hasPrev() ? getProperIndex(currentIndex - 1) : getCurrentIndex();
// }
//
// public boolean goToPrev() {
// if (hasPrev()) {
// changeCurrentIndex(currentIndex - 1);
// return true;
// }
// return false;
// }
//
// private int changeCurrentIndex(int newIndex) {
// return currentIndex = (newIndex + size()) % size();
// }
//
// private int getProperIndex(int i) {
// return (i + size()) % size();
// }
//
// private int idForAudios = 0;
//
// public ArgAudioList add(@NonNull ArgAudio audio) {
// ArgAudio newAudio = audio.cloneAudio();
// newAudio.setId(idForAudios++);
// list.add(newAudio.convertToPlaylist());
// if (currentIndex == -1) changeCurrentIndex(0);
// return this;
// }
//
// public void goTo(int index) {
// changeCurrentIndex(index);
// }
//
// public ArgAudio getCurrentAudio() {
// return currentIndex >= 0 ? list.get(currentIndex) : null;
// }
//
// public boolean isRepeat() {
// return this.repeat;
// }
//
// public void setRepeat(boolean repeat) {
// this.repeat = repeat;
// }
//
// public int getCurrentIndex() {
// return currentIndex;
// }
//
//
// public int size() {
// return list.size();
// }
//
// public boolean isEmpty() {
// return size() == 0;
// }
//
// public boolean contains(ArgAudio o) {
// return list.contains(o);
// }
//
// public int indexOf(ArgAudio o) {
// return list.indexOf(o);
// }
//
// public void addAll(Collection<? extends ArgAudio> c) {
// for (ArgAudio a : c) add(a);
// }
//
// public void clear() {
// list.clear();
// idForAudios = 0;
// }
//
// public ArgAudio get(int index) {
// return list.get(index);
// }
//
// @NonNull
// public Iterator<ArgAudio> iterator() {
// return list.iterator();
// }
//
// public ArgAudio set(int index, ArgAudio element) {
// return list.set(index, element);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) return false;
// else if (!(obj instanceof ArgAudioList)) return false;
// else {
// ArgAudioList a = (ArgAudioList) obj;
// return !(a.isEmpty() || this.isEmpty())
// && this.size() == a.size()
// && this.get(0).equals(a.get(0))
// && this.get(this.size() - 1).equals(a.get(a.size() - 1));
// }
// }
// }
//
// Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Views/ArgPlaylistListView.java
// public class ArgPlaylistListView extends ListView {
// private Context context;
// private int selectedPosition = 0;
// private ArgPlaylistViewAdapter adapter;
//
// public ArgPlaylistListView(Context context) {
// super(context);
// init(context);
// }
//
// public ArgPlaylistListView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init(context);
// }
//
// public ArgPlaylistListView(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// init(context);
// }
//
// private void init(Context context) {
// this.context = context;
// }
//
// public void setAdapter(final ArgAudioList argAudioList) {
// adapter = new ArgPlaylistViewAdapter(this, context, argAudioList);
// setAdapter(adapter);
// }
//
// public ArgPlaylistViewAdapter getAdapter() {
// return adapter;
// }
//
// public void setSelectedPosition(int position) {
// selectedPosition = position;
// }
//
// public int getSelectedPosition() {
// return selectedPosition;
// }
//
// public void scrollToSelected() {
// new Handler().post(() -> setSelection(getSelectedItemPosition()));
// }
// }
| import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.appcompat.widget.AppCompatTextView;
import com.arges.sepan.argmusicplayer.Models.ArgAudioList;
import com.arges.sepan.argmusicplayer.Views.ArgPlaylistListView;
import java.util.Locale; | package com.arges.sepan.argmusicplayer;
public abstract class ArgPlayerFullScreenViewRoot extends ArgPlayerLargeViewRoot {
LinearLayout layPanelPlaylist;
ArgPlaylistListView listView;
AppCompatImageButton btnViewFlipper;
byte[] byteArray;
AppCompatTextView tvAudioCount, tvAudioPosition;
boolean isFlipped = false; | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgAudioList.java
// public class ArgAudioList {
// private final ArrayList<ArgAudio> list = new ArrayList<>();
// private int currentIndex = -1;
// private boolean repeat;
//
// public ArgAudioList(boolean repeat) {
// this.repeat = repeat;
// }
//
// public boolean hasNext() {
// return !isEmpty() && size() > 1 && (repeat || size() > currentIndex + 1);
// }
//
// public int getNextIndex() {
// return hasNext() ? getProperIndex(currentIndex + 1) : getCurrentIndex();
// }
//
// public boolean goToNext() {
// if (hasNext()) {
// changeCurrentIndex(currentIndex + 1);
// return true;
// }
// return false;
// }
//
// public boolean hasPrev() {
// return !isEmpty() && size() > 1 && (repeat || currentIndex > 0);
// }
//
// public int getPrevIndex() {
// return hasPrev() ? getProperIndex(currentIndex - 1) : getCurrentIndex();
// }
//
// public boolean goToPrev() {
// if (hasPrev()) {
// changeCurrentIndex(currentIndex - 1);
// return true;
// }
// return false;
// }
//
// private int changeCurrentIndex(int newIndex) {
// return currentIndex = (newIndex + size()) % size();
// }
//
// private int getProperIndex(int i) {
// return (i + size()) % size();
// }
//
// private int idForAudios = 0;
//
// public ArgAudioList add(@NonNull ArgAudio audio) {
// ArgAudio newAudio = audio.cloneAudio();
// newAudio.setId(idForAudios++);
// list.add(newAudio.convertToPlaylist());
// if (currentIndex == -1) changeCurrentIndex(0);
// return this;
// }
//
// public void goTo(int index) {
// changeCurrentIndex(index);
// }
//
// public ArgAudio getCurrentAudio() {
// return currentIndex >= 0 ? list.get(currentIndex) : null;
// }
//
// public boolean isRepeat() {
// return this.repeat;
// }
//
// public void setRepeat(boolean repeat) {
// this.repeat = repeat;
// }
//
// public int getCurrentIndex() {
// return currentIndex;
// }
//
//
// public int size() {
// return list.size();
// }
//
// public boolean isEmpty() {
// return size() == 0;
// }
//
// public boolean contains(ArgAudio o) {
// return list.contains(o);
// }
//
// public int indexOf(ArgAudio o) {
// return list.indexOf(o);
// }
//
// public void addAll(Collection<? extends ArgAudio> c) {
// for (ArgAudio a : c) add(a);
// }
//
// public void clear() {
// list.clear();
// idForAudios = 0;
// }
//
// public ArgAudio get(int index) {
// return list.get(index);
// }
//
// @NonNull
// public Iterator<ArgAudio> iterator() {
// return list.iterator();
// }
//
// public ArgAudio set(int index, ArgAudio element) {
// return list.set(index, element);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) return false;
// else if (!(obj instanceof ArgAudioList)) return false;
// else {
// ArgAudioList a = (ArgAudioList) obj;
// return !(a.isEmpty() || this.isEmpty())
// && this.size() == a.size()
// && this.get(0).equals(a.get(0))
// && this.get(this.size() - 1).equals(a.get(a.size() - 1));
// }
// }
// }
//
// Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Views/ArgPlaylistListView.java
// public class ArgPlaylistListView extends ListView {
// private Context context;
// private int selectedPosition = 0;
// private ArgPlaylistViewAdapter adapter;
//
// public ArgPlaylistListView(Context context) {
// super(context);
// init(context);
// }
//
// public ArgPlaylistListView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init(context);
// }
//
// public ArgPlaylistListView(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// init(context);
// }
//
// private void init(Context context) {
// this.context = context;
// }
//
// public void setAdapter(final ArgAudioList argAudioList) {
// adapter = new ArgPlaylistViewAdapter(this, context, argAudioList);
// setAdapter(adapter);
// }
//
// public ArgPlaylistViewAdapter getAdapter() {
// return adapter;
// }
//
// public void setSelectedPosition(int position) {
// selectedPosition = position;
// }
//
// public int getSelectedPosition() {
// return selectedPosition;
// }
//
// public void scrollToSelected() {
// new Handler().post(() -> setSelection(getSelectedItemPosition()));
// }
// }
// Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/ArgPlayerFullScreenViewRoot.java
import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.appcompat.widget.AppCompatTextView;
import com.arges.sepan.argmusicplayer.Models.ArgAudioList;
import com.arges.sepan.argmusicplayer.Views.ArgPlaylistListView;
import java.util.Locale;
package com.arges.sepan.argmusicplayer;
public abstract class ArgPlayerFullScreenViewRoot extends ArgPlayerLargeViewRoot {
LinearLayout layPanelPlaylist;
ArgPlaylistListView listView;
AppCompatImageButton btnViewFlipper;
byte[] byteArray;
AppCompatTextView tvAudioCount, tvAudioPosition;
boolean isFlipped = false; | ArgAudioList currentAudioList; |
mergehez/ArgPlayer | argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/ArgPlayerLargeViewRoot.java | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgAudio.java
// public class ArgAudio {
// private String singer, audioName, path;
// private boolean isPlaylist = false;
// private AudioType type;
// private int id = -1;
//
// public ArgAudio(String singer, String audioName, String path, AudioType type) {
// this.singer = singer;
// this.audioName = audioName;
// this.path = path;
// this.type = type;
// }
//
// public ArgAudio(int id, String singer, String audioName, String path, AudioType type) {
// this.singer = singer;
// this.audioName = audioName;
// this.path = path;
// this.type = type;
// this.id = id;
// }
//
// public static ArgAudio createFromRaw(String singer, String audioName, @RawRes int rawId) {
// return new ArgAudio(singer, audioName, String.valueOf(rawId), AudioType.RAW);
// }
//
// public static ArgAudio createFromAssets(String singer, String audioName, String assetName) {
// return new ArgAudio(singer, audioName, assetName, AudioType.ASSETS);
// }
//
// public static ArgAudio createFromURL(String singer, String audioName, String url) {
// return new ArgAudio(singer, audioName, url, AudioType.URL);
// }
//
// public static ArgAudio createFromFilePath(String singer, String audioName, String filePath) {
// return new ArgAudio(singer, audioName, filePath, AudioType.FILE_PATH);
// }
//
// public ArgAudio cloneAudio() {
// return new ArgAudio(id, singer, audioName, path, type);
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public int getId() {
// return id;
// }
//
// public String getTitle() {
// return singer + " - " + audioName;
// }
//
// public void setSinger(String singer) {
// this.singer = singer;
// }
//
// public String getSinger() {
// return singer;
// }
//
// public void setAudioName(String name) {
// this.audioName = name;
// }
//
// public String getAudioName() {
// return path;
// }
//
// public String getPath() {
// return path;
// }
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public AudioType getType() {
// return type;
// }
//
// public void setType(AudioType type) {
// this.type = type;
// }
//
// public boolean isPlaylist() {
// return isPlaylist;
// }
//
// public ArgAudio convertToPlaylist() {
// isPlaylist = true;
// return this;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) return false;
// else if (!(obj instanceof ArgAudio)) return false;
// else {
// ArgAudio a = (ArgAudio) obj;
// return this.getTitle().equals(a.getTitle())
// && this.getType() == a.getType()
// && this.getPath().equals(a.getPath())
// && this.getId() == a.getId();
// }
// }
// }
| import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import com.arges.sepan.argmusicplayer.Models.ArgAudio; | package com.arges.sepan.argmusicplayer;
public abstract class ArgPlayerLargeViewRoot extends ArgPlayerSmallViewRoot {
protected AppCompatImageView imageView;
protected AppCompatTextView tvAudioName;
public ArgPlayerLargeViewRoot(Context context) {
super(context);
}
public ArgPlayerLargeViewRoot(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ArgPlayerLargeViewRoot(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void init(Context context, int layoutResId) {
super.init(context, layoutResId);
imageView = findViewById(R.id.imageViewAudio);
tvAudioName = findViewById(R.id.tvAudioName);
}
@Override
protected void setEmbeddedImageBitmap(byte[] byteArray) {
if(byteArray!=null)
imageView.setImageBitmap(BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length));
else
imageView.setImageResource(R.drawable.mergesoft);
}
@Override | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgAudio.java
// public class ArgAudio {
// private String singer, audioName, path;
// private boolean isPlaylist = false;
// private AudioType type;
// private int id = -1;
//
// public ArgAudio(String singer, String audioName, String path, AudioType type) {
// this.singer = singer;
// this.audioName = audioName;
// this.path = path;
// this.type = type;
// }
//
// public ArgAudio(int id, String singer, String audioName, String path, AudioType type) {
// this.singer = singer;
// this.audioName = audioName;
// this.path = path;
// this.type = type;
// this.id = id;
// }
//
// public static ArgAudio createFromRaw(String singer, String audioName, @RawRes int rawId) {
// return new ArgAudio(singer, audioName, String.valueOf(rawId), AudioType.RAW);
// }
//
// public static ArgAudio createFromAssets(String singer, String audioName, String assetName) {
// return new ArgAudio(singer, audioName, assetName, AudioType.ASSETS);
// }
//
// public static ArgAudio createFromURL(String singer, String audioName, String url) {
// return new ArgAudio(singer, audioName, url, AudioType.URL);
// }
//
// public static ArgAudio createFromFilePath(String singer, String audioName, String filePath) {
// return new ArgAudio(singer, audioName, filePath, AudioType.FILE_PATH);
// }
//
// public ArgAudio cloneAudio() {
// return new ArgAudio(id, singer, audioName, path, type);
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public int getId() {
// return id;
// }
//
// public String getTitle() {
// return singer + " - " + audioName;
// }
//
// public void setSinger(String singer) {
// this.singer = singer;
// }
//
// public String getSinger() {
// return singer;
// }
//
// public void setAudioName(String name) {
// this.audioName = name;
// }
//
// public String getAudioName() {
// return path;
// }
//
// public String getPath() {
// return path;
// }
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public AudioType getType() {
// return type;
// }
//
// public void setType(AudioType type) {
// this.type = type;
// }
//
// public boolean isPlaylist() {
// return isPlaylist;
// }
//
// public ArgAudio convertToPlaylist() {
// isPlaylist = true;
// return this;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) return false;
// else if (!(obj instanceof ArgAudio)) return false;
// else {
// ArgAudio a = (ArgAudio) obj;
// return this.getTitle().equals(a.getTitle())
// && this.getType() == a.getType()
// && this.getPath().equals(a.getPath())
// && this.getId() == a.getId();
// }
// }
// }
// Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/ArgPlayerLargeViewRoot.java
import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import com.arges.sepan.argmusicplayer.Models.ArgAudio;
package com.arges.sepan.argmusicplayer;
public abstract class ArgPlayerLargeViewRoot extends ArgPlayerSmallViewRoot {
protected AppCompatImageView imageView;
protected AppCompatTextView tvAudioName;
public ArgPlayerLargeViewRoot(Context context) {
super(context);
}
public ArgPlayerLargeViewRoot(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ArgPlayerLargeViewRoot(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void init(Context context, int layoutResId) {
super.init(context, layoutResId);
imageView = findViewById(R.id.imageViewAudio);
tvAudioName = findViewById(R.id.tvAudioName);
}
@Override
protected void setEmbeddedImageBitmap(byte[] byteArray) {
if(byteArray!=null)
imageView.setImageBitmap(BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length));
else
imageView.setImageResource(R.drawable.mergesoft);
}
@Override | protected void onAudioNameChanged(ArgAudio audio) { |
mergehez/ArgPlayer | argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Views/ArgPlaylistListView.java | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgAudioList.java
// public class ArgAudioList {
// private final ArrayList<ArgAudio> list = new ArrayList<>();
// private int currentIndex = -1;
// private boolean repeat;
//
// public ArgAudioList(boolean repeat) {
// this.repeat = repeat;
// }
//
// public boolean hasNext() {
// return !isEmpty() && size() > 1 && (repeat || size() > currentIndex + 1);
// }
//
// public int getNextIndex() {
// return hasNext() ? getProperIndex(currentIndex + 1) : getCurrentIndex();
// }
//
// public boolean goToNext() {
// if (hasNext()) {
// changeCurrentIndex(currentIndex + 1);
// return true;
// }
// return false;
// }
//
// public boolean hasPrev() {
// return !isEmpty() && size() > 1 && (repeat || currentIndex > 0);
// }
//
// public int getPrevIndex() {
// return hasPrev() ? getProperIndex(currentIndex - 1) : getCurrentIndex();
// }
//
// public boolean goToPrev() {
// if (hasPrev()) {
// changeCurrentIndex(currentIndex - 1);
// return true;
// }
// return false;
// }
//
// private int changeCurrentIndex(int newIndex) {
// return currentIndex = (newIndex + size()) % size();
// }
//
// private int getProperIndex(int i) {
// return (i + size()) % size();
// }
//
// private int idForAudios = 0;
//
// public ArgAudioList add(@NonNull ArgAudio audio) {
// ArgAudio newAudio = audio.cloneAudio();
// newAudio.setId(idForAudios++);
// list.add(newAudio.convertToPlaylist());
// if (currentIndex == -1) changeCurrentIndex(0);
// return this;
// }
//
// public void goTo(int index) {
// changeCurrentIndex(index);
// }
//
// public ArgAudio getCurrentAudio() {
// return currentIndex >= 0 ? list.get(currentIndex) : null;
// }
//
// public boolean isRepeat() {
// return this.repeat;
// }
//
// public void setRepeat(boolean repeat) {
// this.repeat = repeat;
// }
//
// public int getCurrentIndex() {
// return currentIndex;
// }
//
//
// public int size() {
// return list.size();
// }
//
// public boolean isEmpty() {
// return size() == 0;
// }
//
// public boolean contains(ArgAudio o) {
// return list.contains(o);
// }
//
// public int indexOf(ArgAudio o) {
// return list.indexOf(o);
// }
//
// public void addAll(Collection<? extends ArgAudio> c) {
// for (ArgAudio a : c) add(a);
// }
//
// public void clear() {
// list.clear();
// idForAudios = 0;
// }
//
// public ArgAudio get(int index) {
// return list.get(index);
// }
//
// @NonNull
// public Iterator<ArgAudio> iterator() {
// return list.iterator();
// }
//
// public ArgAudio set(int index, ArgAudio element) {
// return list.set(index, element);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) return false;
// else if (!(obj instanceof ArgAudioList)) return false;
// else {
// ArgAudioList a = (ArgAudioList) obj;
// return !(a.isEmpty() || this.isEmpty())
// && this.size() == a.size()
// && this.get(0).equals(a.get(0))
// && this.get(this.size() - 1).equals(a.get(a.size() - 1));
// }
// }
// }
| import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.ListView;
import com.arges.sepan.argmusicplayer.Models.ArgAudioList; | package com.arges.sepan.argmusicplayer.Views;
public class ArgPlaylistListView extends ListView {
private Context context;
private int selectedPosition = 0;
private ArgPlaylistViewAdapter adapter;
public ArgPlaylistListView(Context context) {
super(context);
init(context);
}
public ArgPlaylistListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public ArgPlaylistListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
this.context = context;
}
| // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgAudioList.java
// public class ArgAudioList {
// private final ArrayList<ArgAudio> list = new ArrayList<>();
// private int currentIndex = -1;
// private boolean repeat;
//
// public ArgAudioList(boolean repeat) {
// this.repeat = repeat;
// }
//
// public boolean hasNext() {
// return !isEmpty() && size() > 1 && (repeat || size() > currentIndex + 1);
// }
//
// public int getNextIndex() {
// return hasNext() ? getProperIndex(currentIndex + 1) : getCurrentIndex();
// }
//
// public boolean goToNext() {
// if (hasNext()) {
// changeCurrentIndex(currentIndex + 1);
// return true;
// }
// return false;
// }
//
// public boolean hasPrev() {
// return !isEmpty() && size() > 1 && (repeat || currentIndex > 0);
// }
//
// public int getPrevIndex() {
// return hasPrev() ? getProperIndex(currentIndex - 1) : getCurrentIndex();
// }
//
// public boolean goToPrev() {
// if (hasPrev()) {
// changeCurrentIndex(currentIndex - 1);
// return true;
// }
// return false;
// }
//
// private int changeCurrentIndex(int newIndex) {
// return currentIndex = (newIndex + size()) % size();
// }
//
// private int getProperIndex(int i) {
// return (i + size()) % size();
// }
//
// private int idForAudios = 0;
//
// public ArgAudioList add(@NonNull ArgAudio audio) {
// ArgAudio newAudio = audio.cloneAudio();
// newAudio.setId(idForAudios++);
// list.add(newAudio.convertToPlaylist());
// if (currentIndex == -1) changeCurrentIndex(0);
// return this;
// }
//
// public void goTo(int index) {
// changeCurrentIndex(index);
// }
//
// public ArgAudio getCurrentAudio() {
// return currentIndex >= 0 ? list.get(currentIndex) : null;
// }
//
// public boolean isRepeat() {
// return this.repeat;
// }
//
// public void setRepeat(boolean repeat) {
// this.repeat = repeat;
// }
//
// public int getCurrentIndex() {
// return currentIndex;
// }
//
//
// public int size() {
// return list.size();
// }
//
// public boolean isEmpty() {
// return size() == 0;
// }
//
// public boolean contains(ArgAudio o) {
// return list.contains(o);
// }
//
// public int indexOf(ArgAudio o) {
// return list.indexOf(o);
// }
//
// public void addAll(Collection<? extends ArgAudio> c) {
// for (ArgAudio a : c) add(a);
// }
//
// public void clear() {
// list.clear();
// idForAudios = 0;
// }
//
// public ArgAudio get(int index) {
// return list.get(index);
// }
//
// @NonNull
// public Iterator<ArgAudio> iterator() {
// return list.iterator();
// }
//
// public ArgAudio set(int index, ArgAudio element) {
// return list.set(index, element);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) return false;
// else if (!(obj instanceof ArgAudioList)) return false;
// else {
// ArgAudioList a = (ArgAudioList) obj;
// return !(a.isEmpty() || this.isEmpty())
// && this.size() == a.size()
// && this.get(0).equals(a.get(0))
// && this.get(this.size() - 1).equals(a.get(a.size() - 1));
// }
// }
// }
// Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Views/ArgPlaylistListView.java
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.ListView;
import com.arges.sepan.argmusicplayer.Models.ArgAudioList;
package com.arges.sepan.argmusicplayer.Views;
public class ArgPlaylistListView extends ListView {
private Context context;
private int selectedPosition = 0;
private ArgPlaylistViewAdapter adapter;
public ArgPlaylistListView(Context context) {
super(context);
init(context);
}
public ArgPlaylistListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public ArgPlaylistListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
this.context = context;
}
| public void setAdapter(final ArgAudioList argAudioList) { |
mergehez/ArgPlayer | argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Notification/ArgNotification.java | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgNotificationOptions.java
// public class ArgNotificationOptions {
//
// private boolean enabled = true;
// private boolean progressEnabled = false;
// private String channelId;
// private CharSequence channelName;
// private int notificationId = 548853;
// private int imageResoureId = R.drawable.mergesoftlogo;
// private OnBuildNotificationListener listener = null;
// private final Activity activity;
//
// public ArgNotificationOptions(Activity activity){
// this.activity = activity;
// }
//
// //region getter setters
// public OnBuildNotificationListener getListener() {
// return listener;
// }
//
// public ArgNotificationOptions setListener(OnBuildNotificationListener listener) {
// this.listener = listener;
// return this;
// }
//
// public boolean isProgressEnabled() {
// return progressEnabled;
// }
//
// public ArgNotificationOptions setProgressEnabled(boolean progressEnabled) {
// this.progressEnabled = progressEnabled;
// return this;
// }
//
// @RequiresApi(O)
// public String getChannelId() {
// return channelId;
// }
// @RequiresApi(O)
// public ArgNotificationOptions setChannelId(String channelId) {
// this.channelId = channelId;
// return this;
// }
//
// @RequiresApi(O)
// public CharSequence getChannelName() {
// return channelName;
// }
//
// @RequiresApi(O)
// public ArgNotificationOptions setChannelName(CharSequence channelName) {
// this.channelName = channelName;
// return this;
// }
//
// public int getImageResoureId() {
// return imageResoureId;
// }
//
// public ArgNotificationOptions setImageResoureId(int imageResoureId) {
// this.imageResoureId = imageResoureId;
// return this;
// }
//
// public int getNotificationId() {
// return notificationId;
// }
//
// public ArgNotificationOptions setNotificationId(int notificationId) {
// this.notificationId = notificationId;
// return this;
// }
//
// public Activity getActivity() {
// return activity;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public ArgNotificationOptions setEnabled(boolean enabled) {
// this.enabled = enabled;
// return this;
// }
// //endregion getter setters
// }
| import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.annotation.NonNull;
import com.arges.sepan.argmusicplayer.Models.ArgNotificationOptions;
import com.arges.sepan.argmusicplayer.R; | package com.arges.sepan.argmusicplayer.Notification;
public class ArgNotification extends Notification {
private static int notificationId;
protected final Notification notification;
private final ArgRemoteView contentView, bigContentView;
private final NotificationManager mNotificationManager; | // Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Models/ArgNotificationOptions.java
// public class ArgNotificationOptions {
//
// private boolean enabled = true;
// private boolean progressEnabled = false;
// private String channelId;
// private CharSequence channelName;
// private int notificationId = 548853;
// private int imageResoureId = R.drawable.mergesoftlogo;
// private OnBuildNotificationListener listener = null;
// private final Activity activity;
//
// public ArgNotificationOptions(Activity activity){
// this.activity = activity;
// }
//
// //region getter setters
// public OnBuildNotificationListener getListener() {
// return listener;
// }
//
// public ArgNotificationOptions setListener(OnBuildNotificationListener listener) {
// this.listener = listener;
// return this;
// }
//
// public boolean isProgressEnabled() {
// return progressEnabled;
// }
//
// public ArgNotificationOptions setProgressEnabled(boolean progressEnabled) {
// this.progressEnabled = progressEnabled;
// return this;
// }
//
// @RequiresApi(O)
// public String getChannelId() {
// return channelId;
// }
// @RequiresApi(O)
// public ArgNotificationOptions setChannelId(String channelId) {
// this.channelId = channelId;
// return this;
// }
//
// @RequiresApi(O)
// public CharSequence getChannelName() {
// return channelName;
// }
//
// @RequiresApi(O)
// public ArgNotificationOptions setChannelName(CharSequence channelName) {
// this.channelName = channelName;
// return this;
// }
//
// public int getImageResoureId() {
// return imageResoureId;
// }
//
// public ArgNotificationOptions setImageResoureId(int imageResoureId) {
// this.imageResoureId = imageResoureId;
// return this;
// }
//
// public int getNotificationId() {
// return notificationId;
// }
//
// public ArgNotificationOptions setNotificationId(int notificationId) {
// this.notificationId = notificationId;
// return this;
// }
//
// public Activity getActivity() {
// return activity;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public ArgNotificationOptions setEnabled(boolean enabled) {
// this.enabled = enabled;
// return this;
// }
// //endregion getter setters
// }
// Path: argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Notification/ArgNotification.java
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.annotation.NonNull;
import com.arges.sepan.argmusicplayer.Models.ArgNotificationOptions;
import com.arges.sepan.argmusicplayer.R;
package com.arges.sepan.argmusicplayer.Notification;
public class ArgNotification extends Notification {
private static int notificationId;
protected final Notification notification;
private final ArgRemoteView contentView, bigContentView;
private final NotificationManager mNotificationManager; | protected ArgNotificationOptions options; |
mammothcm/mammoth | src/org/apache/hadoop/mapred/CacheFile.java | // Path: src/org/apache/hadoop/fs/FSDataOutputStream.java
// public class FSDataOutputStream extends DataOutputStream implements Syncable {
// private OutputStream wrappedStream;
//
// private static class PositionCache extends FilterOutputStream {
// private FileSystem.Statistics statistics;
// long position;
//
// public PositionCache(OutputStream out,
// FileSystem.Statistics stats,
// long pos) throws IOException {
// super(out);
// statistics = stats;
// position = pos;
// }
//
// public void write(int b) throws IOException {
// out.write(b);
// position++;
// if (statistics != null) {
// statistics.incrementBytesWritten(1);
// }
// }
//
// public void write(byte b[], int off, int len) throws IOException {
// out.write(b, off, len);
// position += len; // update position
// if (statistics != null) {
// statistics.incrementBytesWritten(len);
// }
// }
//
// public long getPos() throws IOException {
// return position; // return cached position
// }
//
// public void close() throws IOException {
// out.close();
// }
// }
//
// @Deprecated
// public FSDataOutputStream(OutputStream out) throws IOException {
// this(out, null);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats)
// throws IOException {
// this(out, stats, 0);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats,
// long startPosition) throws IOException {
// super(new PositionCache(out, stats, startPosition));
// wrappedStream = out;
// }
//
// public long getPos() throws IOException {
// return ((PositionCache)out).getPos();
// }
//
// public void close() throws IOException {
// out.close(); // This invokes PositionCache.close()
// }
//
// // Returns the underlying output stream. This is used by unit tests.
// public OutputStream getWrappedStream() {
// return wrappedStream;
// }
//
// /** {@inheritDoc} */
// public void sync() throws IOException {
// if (wrappedStream instanceof Syncable) {
// ((Syncable)wrappedStream).sync();
// }
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CachePoolFullException extends IOException {
// CachePoolFullException(String s) {
// super(s);
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CacheUnit extends ByteArrayInputStream {
// static int cap = 0;
// private boolean isLast = false;
// public CacheUnit() {
// super(new byte[cap]);
// count = 0;
// }
// public int write(InputStream in) throws IOException {
// if (count >= buf.length) {
// return 0;
// }
// int res = in.read(buf, count, buf.length - count);
// if (res < 0) {
// return res;
// }
// count += res;
// return res;
// }
// public int write(byte b[], int off, int len){
// len = Math.min(len, buf.length - count);
// System.arraycopy(b, off, buf, count, len);
// count += len;
// return len;
// }
// public void writeFile(OutputStream out) throws IOException {
// out.write(buf, mark, count);
// }
// public boolean write(int b){
// if (count >= buf.length) {
// return false;
// }
// buf[count++] = (byte)b;
// return true;
// }
// public int getPos() {
// return pos;
// }
// public int getLen() {
// return count;
// }
// public void reinit(){
// count = 0;
// mark = 0;
// pos = 0;
// isLast = false;
// }
// public boolean isLast() {
// return isLast;
// }
// public void setLast() {
// isLast = true;
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.mapred.CachePool.CachePoolFullException;
import org.apache.hadoop.mapred.CachePool.CacheUnit; | package org.apache.hadoop.mapred;
public class CacheFile extends InputStream {
private static final Log LOG = LogFactory.getLog(CacheFile.class.getName()); | // Path: src/org/apache/hadoop/fs/FSDataOutputStream.java
// public class FSDataOutputStream extends DataOutputStream implements Syncable {
// private OutputStream wrappedStream;
//
// private static class PositionCache extends FilterOutputStream {
// private FileSystem.Statistics statistics;
// long position;
//
// public PositionCache(OutputStream out,
// FileSystem.Statistics stats,
// long pos) throws IOException {
// super(out);
// statistics = stats;
// position = pos;
// }
//
// public void write(int b) throws IOException {
// out.write(b);
// position++;
// if (statistics != null) {
// statistics.incrementBytesWritten(1);
// }
// }
//
// public void write(byte b[], int off, int len) throws IOException {
// out.write(b, off, len);
// position += len; // update position
// if (statistics != null) {
// statistics.incrementBytesWritten(len);
// }
// }
//
// public long getPos() throws IOException {
// return position; // return cached position
// }
//
// public void close() throws IOException {
// out.close();
// }
// }
//
// @Deprecated
// public FSDataOutputStream(OutputStream out) throws IOException {
// this(out, null);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats)
// throws IOException {
// this(out, stats, 0);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats,
// long startPosition) throws IOException {
// super(new PositionCache(out, stats, startPosition));
// wrappedStream = out;
// }
//
// public long getPos() throws IOException {
// return ((PositionCache)out).getPos();
// }
//
// public void close() throws IOException {
// out.close(); // This invokes PositionCache.close()
// }
//
// // Returns the underlying output stream. This is used by unit tests.
// public OutputStream getWrappedStream() {
// return wrappedStream;
// }
//
// /** {@inheritDoc} */
// public void sync() throws IOException {
// if (wrappedStream instanceof Syncable) {
// ((Syncable)wrappedStream).sync();
// }
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CachePoolFullException extends IOException {
// CachePoolFullException(String s) {
// super(s);
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CacheUnit extends ByteArrayInputStream {
// static int cap = 0;
// private boolean isLast = false;
// public CacheUnit() {
// super(new byte[cap]);
// count = 0;
// }
// public int write(InputStream in) throws IOException {
// if (count >= buf.length) {
// return 0;
// }
// int res = in.read(buf, count, buf.length - count);
// if (res < 0) {
// return res;
// }
// count += res;
// return res;
// }
// public int write(byte b[], int off, int len){
// len = Math.min(len, buf.length - count);
// System.arraycopy(b, off, buf, count, len);
// count += len;
// return len;
// }
// public void writeFile(OutputStream out) throws IOException {
// out.write(buf, mark, count);
// }
// public boolean write(int b){
// if (count >= buf.length) {
// return false;
// }
// buf[count++] = (byte)b;
// return true;
// }
// public int getPos() {
// return pos;
// }
// public int getLen() {
// return count;
// }
// public void reinit(){
// count = 0;
// mark = 0;
// pos = 0;
// isLast = false;
// }
// public boolean isLast() {
// return isLast;
// }
// public void setLast() {
// isLast = true;
// }
// }
// Path: src/org/apache/hadoop/mapred/CacheFile.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.mapred.CachePool.CachePoolFullException;
import org.apache.hadoop.mapred.CachePool.CacheUnit;
package org.apache.hadoop.mapred;
public class CacheFile extends InputStream {
private static final Log LOG = LogFactory.getLog(CacheFile.class.getName()); | private List<CacheUnit> content; |
mammothcm/mammoth | src/org/apache/hadoop/mapred/CacheFile.java | // Path: src/org/apache/hadoop/fs/FSDataOutputStream.java
// public class FSDataOutputStream extends DataOutputStream implements Syncable {
// private OutputStream wrappedStream;
//
// private static class PositionCache extends FilterOutputStream {
// private FileSystem.Statistics statistics;
// long position;
//
// public PositionCache(OutputStream out,
// FileSystem.Statistics stats,
// long pos) throws IOException {
// super(out);
// statistics = stats;
// position = pos;
// }
//
// public void write(int b) throws IOException {
// out.write(b);
// position++;
// if (statistics != null) {
// statistics.incrementBytesWritten(1);
// }
// }
//
// public void write(byte b[], int off, int len) throws IOException {
// out.write(b, off, len);
// position += len; // update position
// if (statistics != null) {
// statistics.incrementBytesWritten(len);
// }
// }
//
// public long getPos() throws IOException {
// return position; // return cached position
// }
//
// public void close() throws IOException {
// out.close();
// }
// }
//
// @Deprecated
// public FSDataOutputStream(OutputStream out) throws IOException {
// this(out, null);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats)
// throws IOException {
// this(out, stats, 0);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats,
// long startPosition) throws IOException {
// super(new PositionCache(out, stats, startPosition));
// wrappedStream = out;
// }
//
// public long getPos() throws IOException {
// return ((PositionCache)out).getPos();
// }
//
// public void close() throws IOException {
// out.close(); // This invokes PositionCache.close()
// }
//
// // Returns the underlying output stream. This is used by unit tests.
// public OutputStream getWrappedStream() {
// return wrappedStream;
// }
//
// /** {@inheritDoc} */
// public void sync() throws IOException {
// if (wrappedStream instanceof Syncable) {
// ((Syncable)wrappedStream).sync();
// }
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CachePoolFullException extends IOException {
// CachePoolFullException(String s) {
// super(s);
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CacheUnit extends ByteArrayInputStream {
// static int cap = 0;
// private boolean isLast = false;
// public CacheUnit() {
// super(new byte[cap]);
// count = 0;
// }
// public int write(InputStream in) throws IOException {
// if (count >= buf.length) {
// return 0;
// }
// int res = in.read(buf, count, buf.length - count);
// if (res < 0) {
// return res;
// }
// count += res;
// return res;
// }
// public int write(byte b[], int off, int len){
// len = Math.min(len, buf.length - count);
// System.arraycopy(b, off, buf, count, len);
// count += len;
// return len;
// }
// public void writeFile(OutputStream out) throws IOException {
// out.write(buf, mark, count);
// }
// public boolean write(int b){
// if (count >= buf.length) {
// return false;
// }
// buf[count++] = (byte)b;
// return true;
// }
// public int getPos() {
// return pos;
// }
// public int getLen() {
// return count;
// }
// public void reinit(){
// count = 0;
// mark = 0;
// pos = 0;
// isLast = false;
// }
// public boolean isLast() {
// return isLast;
// }
// public void setLast() {
// isLast = true;
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.mapred.CachePool.CachePoolFullException;
import org.apache.hadoop.mapred.CachePool.CacheUnit; | package org.apache.hadoop.mapred;
public class CacheFile extends InputStream {
private static final Log LOG = LogFactory.getLog(CacheFile.class.getName());
private List<CacheUnit> content;
private List<CacheUnit> rcontent;
private final CachePool pool;
private CacheUnit curCU = null;
private long cursor = 0; //for read
private long len = 0;
private boolean delete = false; //true: delete CU after read, but cannot skip
private boolean isWriteDone = false;
int maxSpills = 0;
//private List<CacheUnit> spills = new LinkedList<CacheUnit>(); | // Path: src/org/apache/hadoop/fs/FSDataOutputStream.java
// public class FSDataOutputStream extends DataOutputStream implements Syncable {
// private OutputStream wrappedStream;
//
// private static class PositionCache extends FilterOutputStream {
// private FileSystem.Statistics statistics;
// long position;
//
// public PositionCache(OutputStream out,
// FileSystem.Statistics stats,
// long pos) throws IOException {
// super(out);
// statistics = stats;
// position = pos;
// }
//
// public void write(int b) throws IOException {
// out.write(b);
// position++;
// if (statistics != null) {
// statistics.incrementBytesWritten(1);
// }
// }
//
// public void write(byte b[], int off, int len) throws IOException {
// out.write(b, off, len);
// position += len; // update position
// if (statistics != null) {
// statistics.incrementBytesWritten(len);
// }
// }
//
// public long getPos() throws IOException {
// return position; // return cached position
// }
//
// public void close() throws IOException {
// out.close();
// }
// }
//
// @Deprecated
// public FSDataOutputStream(OutputStream out) throws IOException {
// this(out, null);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats)
// throws IOException {
// this(out, stats, 0);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats,
// long startPosition) throws IOException {
// super(new PositionCache(out, stats, startPosition));
// wrappedStream = out;
// }
//
// public long getPos() throws IOException {
// return ((PositionCache)out).getPos();
// }
//
// public void close() throws IOException {
// out.close(); // This invokes PositionCache.close()
// }
//
// // Returns the underlying output stream. This is used by unit tests.
// public OutputStream getWrappedStream() {
// return wrappedStream;
// }
//
// /** {@inheritDoc} */
// public void sync() throws IOException {
// if (wrappedStream instanceof Syncable) {
// ((Syncable)wrappedStream).sync();
// }
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CachePoolFullException extends IOException {
// CachePoolFullException(String s) {
// super(s);
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CacheUnit extends ByteArrayInputStream {
// static int cap = 0;
// private boolean isLast = false;
// public CacheUnit() {
// super(new byte[cap]);
// count = 0;
// }
// public int write(InputStream in) throws IOException {
// if (count >= buf.length) {
// return 0;
// }
// int res = in.read(buf, count, buf.length - count);
// if (res < 0) {
// return res;
// }
// count += res;
// return res;
// }
// public int write(byte b[], int off, int len){
// len = Math.min(len, buf.length - count);
// System.arraycopy(b, off, buf, count, len);
// count += len;
// return len;
// }
// public void writeFile(OutputStream out) throws IOException {
// out.write(buf, mark, count);
// }
// public boolean write(int b){
// if (count >= buf.length) {
// return false;
// }
// buf[count++] = (byte)b;
// return true;
// }
// public int getPos() {
// return pos;
// }
// public int getLen() {
// return count;
// }
// public void reinit(){
// count = 0;
// mark = 0;
// pos = 0;
// isLast = false;
// }
// public boolean isLast() {
// return isLast;
// }
// public void setLast() {
// isLast = true;
// }
// }
// Path: src/org/apache/hadoop/mapred/CacheFile.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.mapred.CachePool.CachePoolFullException;
import org.apache.hadoop.mapred.CachePool.CacheUnit;
package org.apache.hadoop.mapred;
public class CacheFile extends InputStream {
private static final Log LOG = LogFactory.getLog(CacheFile.class.getName());
private List<CacheUnit> content;
private List<CacheUnit> rcontent;
private final CachePool pool;
private CacheUnit curCU = null;
private long cursor = 0; //for read
private long len = 0;
private boolean delete = false; //true: delete CU after read, but cannot skip
private boolean isWriteDone = false;
int maxSpills = 0;
//private List<CacheUnit> spills = new LinkedList<CacheUnit>(); | FSDataOutputStream output; |
mammothcm/mammoth | src/org/apache/hadoop/mapred/CacheFile.java | // Path: src/org/apache/hadoop/fs/FSDataOutputStream.java
// public class FSDataOutputStream extends DataOutputStream implements Syncable {
// private OutputStream wrappedStream;
//
// private static class PositionCache extends FilterOutputStream {
// private FileSystem.Statistics statistics;
// long position;
//
// public PositionCache(OutputStream out,
// FileSystem.Statistics stats,
// long pos) throws IOException {
// super(out);
// statistics = stats;
// position = pos;
// }
//
// public void write(int b) throws IOException {
// out.write(b);
// position++;
// if (statistics != null) {
// statistics.incrementBytesWritten(1);
// }
// }
//
// public void write(byte b[], int off, int len) throws IOException {
// out.write(b, off, len);
// position += len; // update position
// if (statistics != null) {
// statistics.incrementBytesWritten(len);
// }
// }
//
// public long getPos() throws IOException {
// return position; // return cached position
// }
//
// public void close() throws IOException {
// out.close();
// }
// }
//
// @Deprecated
// public FSDataOutputStream(OutputStream out) throws IOException {
// this(out, null);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats)
// throws IOException {
// this(out, stats, 0);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats,
// long startPosition) throws IOException {
// super(new PositionCache(out, stats, startPosition));
// wrappedStream = out;
// }
//
// public long getPos() throws IOException {
// return ((PositionCache)out).getPos();
// }
//
// public void close() throws IOException {
// out.close(); // This invokes PositionCache.close()
// }
//
// // Returns the underlying output stream. This is used by unit tests.
// public OutputStream getWrappedStream() {
// return wrappedStream;
// }
//
// /** {@inheritDoc} */
// public void sync() throws IOException {
// if (wrappedStream instanceof Syncable) {
// ((Syncable)wrappedStream).sync();
// }
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CachePoolFullException extends IOException {
// CachePoolFullException(String s) {
// super(s);
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CacheUnit extends ByteArrayInputStream {
// static int cap = 0;
// private boolean isLast = false;
// public CacheUnit() {
// super(new byte[cap]);
// count = 0;
// }
// public int write(InputStream in) throws IOException {
// if (count >= buf.length) {
// return 0;
// }
// int res = in.read(buf, count, buf.length - count);
// if (res < 0) {
// return res;
// }
// count += res;
// return res;
// }
// public int write(byte b[], int off, int len){
// len = Math.min(len, buf.length - count);
// System.arraycopy(b, off, buf, count, len);
// count += len;
// return len;
// }
// public void writeFile(OutputStream out) throws IOException {
// out.write(buf, mark, count);
// }
// public boolean write(int b){
// if (count >= buf.length) {
// return false;
// }
// buf[count++] = (byte)b;
// return true;
// }
// public int getPos() {
// return pos;
// }
// public int getLen() {
// return count;
// }
// public void reinit(){
// count = 0;
// mark = 0;
// pos = 0;
// isLast = false;
// }
// public boolean isLast() {
// return isLast;
// }
// public void setLast() {
// isLast = true;
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.mapred.CachePool.CachePoolFullException;
import org.apache.hadoop.mapred.CachePool.CacheUnit; | private long len = 0;
private boolean delete = false; //true: delete CU after read, but cannot skip
private boolean isWriteDone = false;
int maxSpills = 0;
//private List<CacheUnit> spills = new LinkedList<CacheUnit>();
FSDataOutputStream output;
private TaskAttemptID taskid;
private static long DEFAULTRLENGTH = 0;
private long rlen = 0;
CacheFile(CachePool p, long rlength) throws IOException {
this(p, rlength, null, false, null, -1);
}
CacheFile(CachePool p, long rlength, FSDataOutputStream out, boolean asyn,
TaskAttemptID tid, int priority) throws IOException{
if (rlength != DEFAULTRLENGTH) {
rlength = size2Cap(rlength);
content = new ArrayList<CacheUnit>((int)(rlength / CacheUnit.cap) + 1);
rcontent = new ArrayList<CacheUnit>((int)(rlength / CacheUnit.cap) + 1);
rcontent.addAll(p.getUnits((int)(rlength/CacheUnit.cap)));
} else {
content = new LinkedList<CacheUnit>();
rcontent = new LinkedList<CacheUnit>();
}
rlen = rlength;
pool = p;
output = out;
taskid = tid;
} | // Path: src/org/apache/hadoop/fs/FSDataOutputStream.java
// public class FSDataOutputStream extends DataOutputStream implements Syncable {
// private OutputStream wrappedStream;
//
// private static class PositionCache extends FilterOutputStream {
// private FileSystem.Statistics statistics;
// long position;
//
// public PositionCache(OutputStream out,
// FileSystem.Statistics stats,
// long pos) throws IOException {
// super(out);
// statistics = stats;
// position = pos;
// }
//
// public void write(int b) throws IOException {
// out.write(b);
// position++;
// if (statistics != null) {
// statistics.incrementBytesWritten(1);
// }
// }
//
// public void write(byte b[], int off, int len) throws IOException {
// out.write(b, off, len);
// position += len; // update position
// if (statistics != null) {
// statistics.incrementBytesWritten(len);
// }
// }
//
// public long getPos() throws IOException {
// return position; // return cached position
// }
//
// public void close() throws IOException {
// out.close();
// }
// }
//
// @Deprecated
// public FSDataOutputStream(OutputStream out) throws IOException {
// this(out, null);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats)
// throws IOException {
// this(out, stats, 0);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats,
// long startPosition) throws IOException {
// super(new PositionCache(out, stats, startPosition));
// wrappedStream = out;
// }
//
// public long getPos() throws IOException {
// return ((PositionCache)out).getPos();
// }
//
// public void close() throws IOException {
// out.close(); // This invokes PositionCache.close()
// }
//
// // Returns the underlying output stream. This is used by unit tests.
// public OutputStream getWrappedStream() {
// return wrappedStream;
// }
//
// /** {@inheritDoc} */
// public void sync() throws IOException {
// if (wrappedStream instanceof Syncable) {
// ((Syncable)wrappedStream).sync();
// }
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CachePoolFullException extends IOException {
// CachePoolFullException(String s) {
// super(s);
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CacheUnit extends ByteArrayInputStream {
// static int cap = 0;
// private boolean isLast = false;
// public CacheUnit() {
// super(new byte[cap]);
// count = 0;
// }
// public int write(InputStream in) throws IOException {
// if (count >= buf.length) {
// return 0;
// }
// int res = in.read(buf, count, buf.length - count);
// if (res < 0) {
// return res;
// }
// count += res;
// return res;
// }
// public int write(byte b[], int off, int len){
// len = Math.min(len, buf.length - count);
// System.arraycopy(b, off, buf, count, len);
// count += len;
// return len;
// }
// public void writeFile(OutputStream out) throws IOException {
// out.write(buf, mark, count);
// }
// public boolean write(int b){
// if (count >= buf.length) {
// return false;
// }
// buf[count++] = (byte)b;
// return true;
// }
// public int getPos() {
// return pos;
// }
// public int getLen() {
// return count;
// }
// public void reinit(){
// count = 0;
// mark = 0;
// pos = 0;
// isLast = false;
// }
// public boolean isLast() {
// return isLast;
// }
// public void setLast() {
// isLast = true;
// }
// }
// Path: src/org/apache/hadoop/mapred/CacheFile.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.mapred.CachePool.CachePoolFullException;
import org.apache.hadoop.mapred.CachePool.CacheUnit;
private long len = 0;
private boolean delete = false; //true: delete CU after read, but cannot skip
private boolean isWriteDone = false;
int maxSpills = 0;
//private List<CacheUnit> spills = new LinkedList<CacheUnit>();
FSDataOutputStream output;
private TaskAttemptID taskid;
private static long DEFAULTRLENGTH = 0;
private long rlen = 0;
CacheFile(CachePool p, long rlength) throws IOException {
this(p, rlength, null, false, null, -1);
}
CacheFile(CachePool p, long rlength, FSDataOutputStream out, boolean asyn,
TaskAttemptID tid, int priority) throws IOException{
if (rlength != DEFAULTRLENGTH) {
rlength = size2Cap(rlength);
content = new ArrayList<CacheUnit>((int)(rlength / CacheUnit.cap) + 1);
rcontent = new ArrayList<CacheUnit>((int)(rlength / CacheUnit.cap) + 1);
rcontent.addAll(p.getUnits((int)(rlength/CacheUnit.cap)));
} else {
content = new LinkedList<CacheUnit>();
rcontent = new LinkedList<CacheUnit>();
}
rlen = rlength;
pool = p;
output = out;
taskid = tid;
} | private CacheUnit getUnit() throws CachePoolFullException { |
mammothcm/mammoth | src/org/apache/hadoop/mapred/TaskTrackerStatus.java | // Path: src/org/apache/hadoop/mapred/TaskStatus.java
// public static enum State {RUNNING, SUCCEEDED, FAILED, UNASSIGNED, KILLED,
// COMMIT_PENDING, FAILED_UNCLEAN, KILLED_UNCLEAN}
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.TaskStatus.State;
import java.io.*;
import java.util.*; | */
public int getHttpPort() {
return httpPort;
}
/**
* Get the number of tasks that have failed on this tracker.
* @return The number of failed tasks
*/
public int getFailures() {
return failures;
}
/**
* Get the current tasks at the TaskTracker.
* Tasks are tracked by a {@link TaskStatus} object.
*
* @return a list of {@link TaskStatus} representing
* the current tasks at the TaskTracker.
*/
public List<TaskStatus> getTaskReports() {
return taskReports;
}
/**
* Is the given task considered as 'running' ?
* @param taskStatus
* @return
*/
private boolean isTaskRunning(TaskStatus taskStatus) { | // Path: src/org/apache/hadoop/mapred/TaskStatus.java
// public static enum State {RUNNING, SUCCEEDED, FAILED, UNASSIGNED, KILLED,
// COMMIT_PENDING, FAILED_UNCLEAN, KILLED_UNCLEAN}
// Path: src/org/apache/hadoop/mapred/TaskTrackerStatus.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.TaskStatus.State;
import java.io.*;
import java.util.*;
*/
public int getHttpPort() {
return httpPort;
}
/**
* Get the number of tasks that have failed on this tracker.
* @return The number of failed tasks
*/
public int getFailures() {
return failures;
}
/**
* Get the current tasks at the TaskTracker.
* Tasks are tracked by a {@link TaskStatus} object.
*
* @return a list of {@link TaskStatus} representing
* the current tasks at the TaskTracker.
*/
public List<TaskStatus> getTaskReports() {
return taskReports;
}
/**
* Is the given task considered as 'running' ?
* @param taskStatus
* @return
*/
private boolean isTaskRunning(TaskStatus taskStatus) { | TaskStatus.State state = taskStatus.getRunState(); |
mammothcm/mammoth | src/org/apache/hadoop/mapred/CacheOutputStream.java | // Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CachePoolFullException extends IOException {
// CachePoolFullException(String s) {
// super(s);
// }
// }
| import java.io.IOException;
import java.io.OutputStream;
import org.apache.hadoop.mapred.CachePool.CachePoolFullException; | package org.apache.hadoop.mapred;
public class CacheOutputStream extends OutputStream{
protected CacheFile file;
public CacheOutputStream(CacheFile f){
file = f;
}
public void write(byte b[], int off, int len) | // Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CachePoolFullException extends IOException {
// CachePoolFullException(String s) {
// super(s);
// }
// }
// Path: src/org/apache/hadoop/mapred/CacheOutputStream.java
import java.io.IOException;
import java.io.OutputStream;
import org.apache.hadoop.mapred.CachePool.CachePoolFullException;
package org.apache.hadoop.mapred;
public class CacheOutputStream extends OutputStream{
protected CacheFile file;
public CacheOutputStream(CacheFile f){
file = f;
}
public void write(byte b[], int off, int len) | throws CachePoolFullException { |
mammothcm/mammoth | src/org/apache/hadoop/mapred/JobQueueJobInProgressListener.java | // Path: src/org/apache/hadoop/mapred/JobStatusChangeEvent.java
// static enum EventType {RUN_STATE_CHANGED, START_TIME_CHANGED, PRIORITY_CHANGED}
| import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import org.apache.hadoop.mapred.JobStatusChangeEvent.EventType; |
/**
* Returns a synchronized view of the job queue.
*/
public Collection<JobInProgress> getJobQueue() {
return jobQueue.values();
}
@Override
public void jobAdded(JobInProgress job) {
jobQueue.put(new JobSchedulingInfo(job.getStatus()), job);
}
// Job will be removed once the job completes
@Override
public void jobRemoved(JobInProgress job) {}
private void jobCompleted(JobSchedulingInfo oldInfo) {
jobQueue.remove(oldInfo);
}
@Override
public synchronized void jobUpdated(JobChangeEvent event) {
JobInProgress job = event.getJobInProgress();
if (event instanceof JobStatusChangeEvent) {
// Check if the ordering of the job has changed
// For now priority and start-time can change the job ordering
JobStatusChangeEvent statusEvent = (JobStatusChangeEvent)event;
JobSchedulingInfo oldInfo =
new JobSchedulingInfo(statusEvent.getOldStatus()); | // Path: src/org/apache/hadoop/mapred/JobStatusChangeEvent.java
// static enum EventType {RUN_STATE_CHANGED, START_TIME_CHANGED, PRIORITY_CHANGED}
// Path: src/org/apache/hadoop/mapred/JobQueueJobInProgressListener.java
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import org.apache.hadoop.mapred.JobStatusChangeEvent.EventType;
/**
* Returns a synchronized view of the job queue.
*/
public Collection<JobInProgress> getJobQueue() {
return jobQueue.values();
}
@Override
public void jobAdded(JobInProgress job) {
jobQueue.put(new JobSchedulingInfo(job.getStatus()), job);
}
// Job will be removed once the job completes
@Override
public void jobRemoved(JobInProgress job) {}
private void jobCompleted(JobSchedulingInfo oldInfo) {
jobQueue.remove(oldInfo);
}
@Override
public synchronized void jobUpdated(JobChangeEvent event) {
JobInProgress job = event.getJobInProgress();
if (event instanceof JobStatusChangeEvent) {
// Check if the ordering of the job has changed
// For now priority and start-time can change the job ordering
JobStatusChangeEvent statusEvent = (JobStatusChangeEvent)event;
JobSchedulingInfo oldInfo =
new JobSchedulingInfo(statusEvent.getOldStatus()); | if (statusEvent.getEventType() == EventType.PRIORITY_CHANGED |
mammothcm/mammoth | src/org/apache/hadoop/mapred/TaskUmbilicalProtocol.java | // Path: src/org/apache/hadoop/mapred/JvmTask.java
// public class JvmTask implements Writable {
// Task t;
// boolean shouldDie;
// public JvmTask(Task t, boolean shouldDie) {
// this.t = t;
// this.shouldDie = shouldDie;
// }
// public JvmTask() {}
// public Task getTask() {
// return t;
// }
// public boolean shouldDie() {
// return shouldDie;
// }
// public void write(DataOutput out) throws IOException {
// out.writeBoolean(shouldDie);
// if (t != null) {
// out.writeBoolean(true);
// out.writeBoolean(t.isMapTask());
// t.write(out);
// } else {
// out.writeBoolean(false);
// }
// }
// public void readFields(DataInput in) throws IOException {
// shouldDie = in.readBoolean();
// boolean taskComing = in.readBoolean();
// if (taskComing) {
// boolean isMap = in.readBoolean();
// if (isMap) {
// t = new MapTask();
// } else {
// t = new ReduceTask();
// }
// t.readFields(in);
// }
// }
// }
| import java.io.IOException;
import org.apache.hadoop.ipc.VersionedProtocol;
import org.apache.hadoop.mapred.JvmTask;
import org.apache.hadoop.mapreduce.security.token.JobTokenSelector;
import org.apache.hadoop.security.token.TokenInfo; | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
/** Protocol that task child process uses to contact its parent process. The
* parent is a daemon which which polls the central master for a new map or
* reduce task and runs it as a child process. All communication between child
* and parent is via this protocol. */
@TokenInfo(JobTokenSelector.class)
public interface TaskUmbilicalProtocol extends VersionedProtocol {
/**
* Changed the version to 2, since we have a new method getMapOutputs
* Changed version to 3 to have progress() return a boolean
* Changed the version to 4, since we have replaced
* TaskUmbilicalProtocol.progress(String, float, String,
* org.apache.hadoop.mapred.TaskStatus.Phase, Counters)
* with statusUpdate(String, TaskStatus)
*
* Version 5 changed counters representation for HADOOP-2248
* Version 6 changes the TaskStatus representation for HADOOP-2208
* Version 7 changes the done api (via HADOOP-3140). It now expects whether
* or not the task's output needs to be promoted.
* Version 8 changes {job|tip|task}id's to use their corresponding
* objects rather than strings.
* Version 9 changes the counter representation for HADOOP-1915
* Version 10 changed the TaskStatus format and added reportNextRecordRange
* for HADOOP-153
* Version 11 Adds RPCs for task commit as part of HADOOP-3150
* Version 12 getMapCompletionEvents() now also indicates if the events are
* stale or not. Hence the return type is a class that
* encapsulates the events and whether to reset events index.
* Version 13 changed the getTask method signature for HADOOP-249
* Version 14 changed the getTask method signature for HADOOP-4232
* Version 15 Adds FAILED_UNCLEAN and KILLED_UNCLEAN states for HADOOP-4759
* Version 16 Added numRequiredSlots to TaskStatus for MAPREDUCE-516
* Version 17 Change in signature of getTask() for HADOOP-5488
* Version 18 Added fatalError for child to communicate fatal errors to TT
* Version 19 Added jvmContext to most method signatures for MAPREDUCE-2429
* */
public static final long versionID = 19L;
/**
* Called when a child task process starts, to get its task.
* @param context the JvmContext of the JVM w.r.t the TaskTracker that
* launched it
* @return Task object
* @throws IOException
*/ | // Path: src/org/apache/hadoop/mapred/JvmTask.java
// public class JvmTask implements Writable {
// Task t;
// boolean shouldDie;
// public JvmTask(Task t, boolean shouldDie) {
// this.t = t;
// this.shouldDie = shouldDie;
// }
// public JvmTask() {}
// public Task getTask() {
// return t;
// }
// public boolean shouldDie() {
// return shouldDie;
// }
// public void write(DataOutput out) throws IOException {
// out.writeBoolean(shouldDie);
// if (t != null) {
// out.writeBoolean(true);
// out.writeBoolean(t.isMapTask());
// t.write(out);
// } else {
// out.writeBoolean(false);
// }
// }
// public void readFields(DataInput in) throws IOException {
// shouldDie = in.readBoolean();
// boolean taskComing = in.readBoolean();
// if (taskComing) {
// boolean isMap = in.readBoolean();
// if (isMap) {
// t = new MapTask();
// } else {
// t = new ReduceTask();
// }
// t.readFields(in);
// }
// }
// }
// Path: src/org/apache/hadoop/mapred/TaskUmbilicalProtocol.java
import java.io.IOException;
import org.apache.hadoop.ipc.VersionedProtocol;
import org.apache.hadoop.mapred.JvmTask;
import org.apache.hadoop.mapreduce.security.token.JobTokenSelector;
import org.apache.hadoop.security.token.TokenInfo;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
/** Protocol that task child process uses to contact its parent process. The
* parent is a daemon which which polls the central master for a new map or
* reduce task and runs it as a child process. All communication between child
* and parent is via this protocol. */
@TokenInfo(JobTokenSelector.class)
public interface TaskUmbilicalProtocol extends VersionedProtocol {
/**
* Changed the version to 2, since we have a new method getMapOutputs
* Changed version to 3 to have progress() return a boolean
* Changed the version to 4, since we have replaced
* TaskUmbilicalProtocol.progress(String, float, String,
* org.apache.hadoop.mapred.TaskStatus.Phase, Counters)
* with statusUpdate(String, TaskStatus)
*
* Version 5 changed counters representation for HADOOP-2248
* Version 6 changes the TaskStatus representation for HADOOP-2208
* Version 7 changes the done api (via HADOOP-3140). It now expects whether
* or not the task's output needs to be promoted.
* Version 8 changes {job|tip|task}id's to use their corresponding
* objects rather than strings.
* Version 9 changes the counter representation for HADOOP-1915
* Version 10 changed the TaskStatus format and added reportNextRecordRange
* for HADOOP-153
* Version 11 Adds RPCs for task commit as part of HADOOP-3150
* Version 12 getMapCompletionEvents() now also indicates if the events are
* stale or not. Hence the return type is a class that
* encapsulates the events and whether to reset events index.
* Version 13 changed the getTask method signature for HADOOP-249
* Version 14 changed the getTask method signature for HADOOP-4232
* Version 15 Adds FAILED_UNCLEAN and KILLED_UNCLEAN states for HADOOP-4759
* Version 16 Added numRequiredSlots to TaskStatus for MAPREDUCE-516
* Version 17 Change in signature of getTask() for HADOOP-5488
* Version 18 Added fatalError for child to communicate fatal errors to TT
* Version 19 Added jvmContext to most method signatures for MAPREDUCE-2429
* */
public static final long versionID = 19L;
/**
* Called when a child task process starts, to get its task.
* @param context the JvmContext of the JVM w.r.t the TaskTracker that
* launched it
* @return Task object
* @throws IOException
*/ | JvmTask getTask(JvmContext context) throws IOException; |
mammothcm/mammoth | src/org/apache/hadoop/mapred/SpillOutputStream.java | // Path: src/org/apache/hadoop/fs/FSDataOutputStream.java
// public class FSDataOutputStream extends DataOutputStream implements Syncable {
// private OutputStream wrappedStream;
//
// private static class PositionCache extends FilterOutputStream {
// private FileSystem.Statistics statistics;
// long position;
//
// public PositionCache(OutputStream out,
// FileSystem.Statistics stats,
// long pos) throws IOException {
// super(out);
// statistics = stats;
// position = pos;
// }
//
// public void write(int b) throws IOException {
// out.write(b);
// position++;
// if (statistics != null) {
// statistics.incrementBytesWritten(1);
// }
// }
//
// public void write(byte b[], int off, int len) throws IOException {
// out.write(b, off, len);
// position += len; // update position
// if (statistics != null) {
// statistics.incrementBytesWritten(len);
// }
// }
//
// public long getPos() throws IOException {
// return position; // return cached position
// }
//
// public void close() throws IOException {
// out.close();
// }
// }
//
// @Deprecated
// public FSDataOutputStream(OutputStream out) throws IOException {
// this(out, null);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats)
// throws IOException {
// this(out, stats, 0);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats,
// long startPosition) throws IOException {
// super(new PositionCache(out, stats, startPosition));
// wrappedStream = out;
// }
//
// public long getPos() throws IOException {
// return ((PositionCache)out).getPos();
// }
//
// public void close() throws IOException {
// out.close(); // This invokes PositionCache.close()
// }
//
// // Returns the underlying output stream. This is used by unit tests.
// public OutputStream getWrappedStream() {
// return wrappedStream;
// }
//
// /** {@inheritDoc} */
// public void sync() throws IOException {
// if (wrappedStream instanceof Syncable) {
// ((Syncable)wrappedStream).sync();
// }
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CachePoolFullException extends IOException {
// CachePoolFullException(String s) {
// super(s);
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CacheUnit extends ByteArrayInputStream {
// static int cap = 0;
// private boolean isLast = false;
// public CacheUnit() {
// super(new byte[cap]);
// count = 0;
// }
// public int write(InputStream in) throws IOException {
// if (count >= buf.length) {
// return 0;
// }
// int res = in.read(buf, count, buf.length - count);
// if (res < 0) {
// return res;
// }
// count += res;
// return res;
// }
// public int write(byte b[], int off, int len){
// len = Math.min(len, buf.length - count);
// System.arraycopy(b, off, buf, count, len);
// count += len;
// return len;
// }
// public void writeFile(OutputStream out) throws IOException {
// out.write(buf, mark, count);
// }
// public boolean write(int b){
// if (count >= buf.length) {
// return false;
// }
// buf[count++] = (byte)b;
// return true;
// }
// public int getPos() {
// return pos;
// }
// public int getLen() {
// return count;
// }
// public void reinit(){
// count = 0;
// mark = 0;
// pos = 0;
// isLast = false;
// }
// public boolean isLast() {
// return isLast;
// }
// public void setLast() {
// isLast = true;
// }
// }
| import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.mapred.CachePool.CachePoolFullException;
import org.apache.hadoop.mapred.CachePool.CacheUnit; | package org.apache.hadoop.mapred;
public class SpillOutputStream extends OutputStream{
private static final Log LOG = LogFactory.getLog(SpillOutputStream.class.getName()); | // Path: src/org/apache/hadoop/fs/FSDataOutputStream.java
// public class FSDataOutputStream extends DataOutputStream implements Syncable {
// private OutputStream wrappedStream;
//
// private static class PositionCache extends FilterOutputStream {
// private FileSystem.Statistics statistics;
// long position;
//
// public PositionCache(OutputStream out,
// FileSystem.Statistics stats,
// long pos) throws IOException {
// super(out);
// statistics = stats;
// position = pos;
// }
//
// public void write(int b) throws IOException {
// out.write(b);
// position++;
// if (statistics != null) {
// statistics.incrementBytesWritten(1);
// }
// }
//
// public void write(byte b[], int off, int len) throws IOException {
// out.write(b, off, len);
// position += len; // update position
// if (statistics != null) {
// statistics.incrementBytesWritten(len);
// }
// }
//
// public long getPos() throws IOException {
// return position; // return cached position
// }
//
// public void close() throws IOException {
// out.close();
// }
// }
//
// @Deprecated
// public FSDataOutputStream(OutputStream out) throws IOException {
// this(out, null);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats)
// throws IOException {
// this(out, stats, 0);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats,
// long startPosition) throws IOException {
// super(new PositionCache(out, stats, startPosition));
// wrappedStream = out;
// }
//
// public long getPos() throws IOException {
// return ((PositionCache)out).getPos();
// }
//
// public void close() throws IOException {
// out.close(); // This invokes PositionCache.close()
// }
//
// // Returns the underlying output stream. This is used by unit tests.
// public OutputStream getWrappedStream() {
// return wrappedStream;
// }
//
// /** {@inheritDoc} */
// public void sync() throws IOException {
// if (wrappedStream instanceof Syncable) {
// ((Syncable)wrappedStream).sync();
// }
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CachePoolFullException extends IOException {
// CachePoolFullException(String s) {
// super(s);
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CacheUnit extends ByteArrayInputStream {
// static int cap = 0;
// private boolean isLast = false;
// public CacheUnit() {
// super(new byte[cap]);
// count = 0;
// }
// public int write(InputStream in) throws IOException {
// if (count >= buf.length) {
// return 0;
// }
// int res = in.read(buf, count, buf.length - count);
// if (res < 0) {
// return res;
// }
// count += res;
// return res;
// }
// public int write(byte b[], int off, int len){
// len = Math.min(len, buf.length - count);
// System.arraycopy(b, off, buf, count, len);
// count += len;
// return len;
// }
// public void writeFile(OutputStream out) throws IOException {
// out.write(buf, mark, count);
// }
// public boolean write(int b){
// if (count >= buf.length) {
// return false;
// }
// buf[count++] = (byte)b;
// return true;
// }
// public int getPos() {
// return pos;
// }
// public int getLen() {
// return count;
// }
// public void reinit(){
// count = 0;
// mark = 0;
// pos = 0;
// isLast = false;
// }
// public boolean isLast() {
// return isLast;
// }
// public void setLast() {
// isLast = true;
// }
// }
// Path: src/org/apache/hadoop/mapred/SpillOutputStream.java
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.mapred.CachePool.CachePoolFullException;
import org.apache.hadoop.mapred.CachePool.CacheUnit;
package org.apache.hadoop.mapred;
public class SpillOutputStream extends OutputStream{
private static final Log LOG = LogFactory.getLog(SpillOutputStream.class.getName()); | private List<CacheUnit> content; |
mammothcm/mammoth | src/org/apache/hadoop/mapred/SpillOutputStream.java | // Path: src/org/apache/hadoop/fs/FSDataOutputStream.java
// public class FSDataOutputStream extends DataOutputStream implements Syncable {
// private OutputStream wrappedStream;
//
// private static class PositionCache extends FilterOutputStream {
// private FileSystem.Statistics statistics;
// long position;
//
// public PositionCache(OutputStream out,
// FileSystem.Statistics stats,
// long pos) throws IOException {
// super(out);
// statistics = stats;
// position = pos;
// }
//
// public void write(int b) throws IOException {
// out.write(b);
// position++;
// if (statistics != null) {
// statistics.incrementBytesWritten(1);
// }
// }
//
// public void write(byte b[], int off, int len) throws IOException {
// out.write(b, off, len);
// position += len; // update position
// if (statistics != null) {
// statistics.incrementBytesWritten(len);
// }
// }
//
// public long getPos() throws IOException {
// return position; // return cached position
// }
//
// public void close() throws IOException {
// out.close();
// }
// }
//
// @Deprecated
// public FSDataOutputStream(OutputStream out) throws IOException {
// this(out, null);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats)
// throws IOException {
// this(out, stats, 0);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats,
// long startPosition) throws IOException {
// super(new PositionCache(out, stats, startPosition));
// wrappedStream = out;
// }
//
// public long getPos() throws IOException {
// return ((PositionCache)out).getPos();
// }
//
// public void close() throws IOException {
// out.close(); // This invokes PositionCache.close()
// }
//
// // Returns the underlying output stream. This is used by unit tests.
// public OutputStream getWrappedStream() {
// return wrappedStream;
// }
//
// /** {@inheritDoc} */
// public void sync() throws IOException {
// if (wrappedStream instanceof Syncable) {
// ((Syncable)wrappedStream).sync();
// }
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CachePoolFullException extends IOException {
// CachePoolFullException(String s) {
// super(s);
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CacheUnit extends ByteArrayInputStream {
// static int cap = 0;
// private boolean isLast = false;
// public CacheUnit() {
// super(new byte[cap]);
// count = 0;
// }
// public int write(InputStream in) throws IOException {
// if (count >= buf.length) {
// return 0;
// }
// int res = in.read(buf, count, buf.length - count);
// if (res < 0) {
// return res;
// }
// count += res;
// return res;
// }
// public int write(byte b[], int off, int len){
// len = Math.min(len, buf.length - count);
// System.arraycopy(b, off, buf, count, len);
// count += len;
// return len;
// }
// public void writeFile(OutputStream out) throws IOException {
// out.write(buf, mark, count);
// }
// public boolean write(int b){
// if (count >= buf.length) {
// return false;
// }
// buf[count++] = (byte)b;
// return true;
// }
// public int getPos() {
// return pos;
// }
// public int getLen() {
// return count;
// }
// public void reinit(){
// count = 0;
// mark = 0;
// pos = 0;
// isLast = false;
// }
// public boolean isLast() {
// return isLast;
// }
// public void setLast() {
// isLast = true;
// }
// }
| import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.mapred.CachePool.CachePoolFullException;
import org.apache.hadoop.mapred.CachePool.CacheUnit; | package org.apache.hadoop.mapred;
public class SpillOutputStream extends OutputStream{
private static final Log LOG = LogFactory.getLog(SpillOutputStream.class.getName());
private List<CacheUnit> content;
private final CachePool pool;
private CacheUnit curCU = null;
private long len = 0;
private boolean isWriteDone = false;
int maxCus = 0; | // Path: src/org/apache/hadoop/fs/FSDataOutputStream.java
// public class FSDataOutputStream extends DataOutputStream implements Syncable {
// private OutputStream wrappedStream;
//
// private static class PositionCache extends FilterOutputStream {
// private FileSystem.Statistics statistics;
// long position;
//
// public PositionCache(OutputStream out,
// FileSystem.Statistics stats,
// long pos) throws IOException {
// super(out);
// statistics = stats;
// position = pos;
// }
//
// public void write(int b) throws IOException {
// out.write(b);
// position++;
// if (statistics != null) {
// statistics.incrementBytesWritten(1);
// }
// }
//
// public void write(byte b[], int off, int len) throws IOException {
// out.write(b, off, len);
// position += len; // update position
// if (statistics != null) {
// statistics.incrementBytesWritten(len);
// }
// }
//
// public long getPos() throws IOException {
// return position; // return cached position
// }
//
// public void close() throws IOException {
// out.close();
// }
// }
//
// @Deprecated
// public FSDataOutputStream(OutputStream out) throws IOException {
// this(out, null);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats)
// throws IOException {
// this(out, stats, 0);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats,
// long startPosition) throws IOException {
// super(new PositionCache(out, stats, startPosition));
// wrappedStream = out;
// }
//
// public long getPos() throws IOException {
// return ((PositionCache)out).getPos();
// }
//
// public void close() throws IOException {
// out.close(); // This invokes PositionCache.close()
// }
//
// // Returns the underlying output stream. This is used by unit tests.
// public OutputStream getWrappedStream() {
// return wrappedStream;
// }
//
// /** {@inheritDoc} */
// public void sync() throws IOException {
// if (wrappedStream instanceof Syncable) {
// ((Syncable)wrappedStream).sync();
// }
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CachePoolFullException extends IOException {
// CachePoolFullException(String s) {
// super(s);
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CacheUnit extends ByteArrayInputStream {
// static int cap = 0;
// private boolean isLast = false;
// public CacheUnit() {
// super(new byte[cap]);
// count = 0;
// }
// public int write(InputStream in) throws IOException {
// if (count >= buf.length) {
// return 0;
// }
// int res = in.read(buf, count, buf.length - count);
// if (res < 0) {
// return res;
// }
// count += res;
// return res;
// }
// public int write(byte b[], int off, int len){
// len = Math.min(len, buf.length - count);
// System.arraycopy(b, off, buf, count, len);
// count += len;
// return len;
// }
// public void writeFile(OutputStream out) throws IOException {
// out.write(buf, mark, count);
// }
// public boolean write(int b){
// if (count >= buf.length) {
// return false;
// }
// buf[count++] = (byte)b;
// return true;
// }
// public int getPos() {
// return pos;
// }
// public int getLen() {
// return count;
// }
// public void reinit(){
// count = 0;
// mark = 0;
// pos = 0;
// isLast = false;
// }
// public boolean isLast() {
// return isLast;
// }
// public void setLast() {
// isLast = true;
// }
// }
// Path: src/org/apache/hadoop/mapred/SpillOutputStream.java
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.mapred.CachePool.CachePoolFullException;
import org.apache.hadoop.mapred.CachePool.CacheUnit;
package org.apache.hadoop.mapred;
public class SpillOutputStream extends OutputStream{
private static final Log LOG = LogFactory.getLog(SpillOutputStream.class.getName());
private List<CacheUnit> content;
private final CachePool pool;
private CacheUnit curCU = null;
private long len = 0;
private boolean isWriteDone = false;
int maxCus = 0; | FSDataOutputStream output; |
mammothcm/mammoth | src/org/apache/hadoop/mapred/SpillOutputStream.java | // Path: src/org/apache/hadoop/fs/FSDataOutputStream.java
// public class FSDataOutputStream extends DataOutputStream implements Syncable {
// private OutputStream wrappedStream;
//
// private static class PositionCache extends FilterOutputStream {
// private FileSystem.Statistics statistics;
// long position;
//
// public PositionCache(OutputStream out,
// FileSystem.Statistics stats,
// long pos) throws IOException {
// super(out);
// statistics = stats;
// position = pos;
// }
//
// public void write(int b) throws IOException {
// out.write(b);
// position++;
// if (statistics != null) {
// statistics.incrementBytesWritten(1);
// }
// }
//
// public void write(byte b[], int off, int len) throws IOException {
// out.write(b, off, len);
// position += len; // update position
// if (statistics != null) {
// statistics.incrementBytesWritten(len);
// }
// }
//
// public long getPos() throws IOException {
// return position; // return cached position
// }
//
// public void close() throws IOException {
// out.close();
// }
// }
//
// @Deprecated
// public FSDataOutputStream(OutputStream out) throws IOException {
// this(out, null);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats)
// throws IOException {
// this(out, stats, 0);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats,
// long startPosition) throws IOException {
// super(new PositionCache(out, stats, startPosition));
// wrappedStream = out;
// }
//
// public long getPos() throws IOException {
// return ((PositionCache)out).getPos();
// }
//
// public void close() throws IOException {
// out.close(); // This invokes PositionCache.close()
// }
//
// // Returns the underlying output stream. This is used by unit tests.
// public OutputStream getWrappedStream() {
// return wrappedStream;
// }
//
// /** {@inheritDoc} */
// public void sync() throws IOException {
// if (wrappedStream instanceof Syncable) {
// ((Syncable)wrappedStream).sync();
// }
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CachePoolFullException extends IOException {
// CachePoolFullException(String s) {
// super(s);
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CacheUnit extends ByteArrayInputStream {
// static int cap = 0;
// private boolean isLast = false;
// public CacheUnit() {
// super(new byte[cap]);
// count = 0;
// }
// public int write(InputStream in) throws IOException {
// if (count >= buf.length) {
// return 0;
// }
// int res = in.read(buf, count, buf.length - count);
// if (res < 0) {
// return res;
// }
// count += res;
// return res;
// }
// public int write(byte b[], int off, int len){
// len = Math.min(len, buf.length - count);
// System.arraycopy(b, off, buf, count, len);
// count += len;
// return len;
// }
// public void writeFile(OutputStream out) throws IOException {
// out.write(buf, mark, count);
// }
// public boolean write(int b){
// if (count >= buf.length) {
// return false;
// }
// buf[count++] = (byte)b;
// return true;
// }
// public int getPos() {
// return pos;
// }
// public int getLen() {
// return count;
// }
// public void reinit(){
// count = 0;
// mark = 0;
// pos = 0;
// isLast = false;
// }
// public boolean isLast() {
// return isLast;
// }
// public void setLast() {
// isLast = true;
// }
// }
| import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.mapred.CachePool.CachePoolFullException;
import org.apache.hadoop.mapred.CachePool.CacheUnit; | package org.apache.hadoop.mapred;
public class SpillOutputStream extends OutputStream{
private static final Log LOG = LogFactory.getLog(SpillOutputStream.class.getName());
private List<CacheUnit> content;
private final CachePool pool;
private CacheUnit curCU = null;
private long len = 0;
private boolean isWriteDone = false;
int maxCus = 0;
FSDataOutputStream output;
private TaskAttemptID taskid;
SpillOutputStream(CachePool p, long rlength, FSDataOutputStream out,
TaskAttemptID tid, int priority) throws IOException{
maxCus = SpillScheduler.get().getMaxPerFileUpCus();
content = new ArrayList<CacheUnit>(maxCus);
pool = p;
output = out;
taskid = tid;
if (output == null) {
throw new IOException("asynchronized write outputstream null!");
}
SpillScheduler.get().registerSpill(output, priority, this);
content.addAll(pool.getUnits(maxCus));
curCU = content.remove(0);
}
| // Path: src/org/apache/hadoop/fs/FSDataOutputStream.java
// public class FSDataOutputStream extends DataOutputStream implements Syncable {
// private OutputStream wrappedStream;
//
// private static class PositionCache extends FilterOutputStream {
// private FileSystem.Statistics statistics;
// long position;
//
// public PositionCache(OutputStream out,
// FileSystem.Statistics stats,
// long pos) throws IOException {
// super(out);
// statistics = stats;
// position = pos;
// }
//
// public void write(int b) throws IOException {
// out.write(b);
// position++;
// if (statistics != null) {
// statistics.incrementBytesWritten(1);
// }
// }
//
// public void write(byte b[], int off, int len) throws IOException {
// out.write(b, off, len);
// position += len; // update position
// if (statistics != null) {
// statistics.incrementBytesWritten(len);
// }
// }
//
// public long getPos() throws IOException {
// return position; // return cached position
// }
//
// public void close() throws IOException {
// out.close();
// }
// }
//
// @Deprecated
// public FSDataOutputStream(OutputStream out) throws IOException {
// this(out, null);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats)
// throws IOException {
// this(out, stats, 0);
// }
//
// public FSDataOutputStream(OutputStream out, FileSystem.Statistics stats,
// long startPosition) throws IOException {
// super(new PositionCache(out, stats, startPosition));
// wrappedStream = out;
// }
//
// public long getPos() throws IOException {
// return ((PositionCache)out).getPos();
// }
//
// public void close() throws IOException {
// out.close(); // This invokes PositionCache.close()
// }
//
// // Returns the underlying output stream. This is used by unit tests.
// public OutputStream getWrappedStream() {
// return wrappedStream;
// }
//
// /** {@inheritDoc} */
// public void sync() throws IOException {
// if (wrappedStream instanceof Syncable) {
// ((Syncable)wrappedStream).sync();
// }
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CachePoolFullException extends IOException {
// CachePoolFullException(String s) {
// super(s);
// }
// }
//
// Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CacheUnit extends ByteArrayInputStream {
// static int cap = 0;
// private boolean isLast = false;
// public CacheUnit() {
// super(new byte[cap]);
// count = 0;
// }
// public int write(InputStream in) throws IOException {
// if (count >= buf.length) {
// return 0;
// }
// int res = in.read(buf, count, buf.length - count);
// if (res < 0) {
// return res;
// }
// count += res;
// return res;
// }
// public int write(byte b[], int off, int len){
// len = Math.min(len, buf.length - count);
// System.arraycopy(b, off, buf, count, len);
// count += len;
// return len;
// }
// public void writeFile(OutputStream out) throws IOException {
// out.write(buf, mark, count);
// }
// public boolean write(int b){
// if (count >= buf.length) {
// return false;
// }
// buf[count++] = (byte)b;
// return true;
// }
// public int getPos() {
// return pos;
// }
// public int getLen() {
// return count;
// }
// public void reinit(){
// count = 0;
// mark = 0;
// pos = 0;
// isLast = false;
// }
// public boolean isLast() {
// return isLast;
// }
// public void setLast() {
// isLast = true;
// }
// }
// Path: src/org/apache/hadoop/mapred/SpillOutputStream.java
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.mapred.CachePool.CachePoolFullException;
import org.apache.hadoop.mapred.CachePool.CacheUnit;
package org.apache.hadoop.mapred;
public class SpillOutputStream extends OutputStream{
private static final Log LOG = LogFactory.getLog(SpillOutputStream.class.getName());
private List<CacheUnit> content;
private final CachePool pool;
private CacheUnit curCU = null;
private long len = 0;
private boolean isWriteDone = false;
int maxCus = 0;
FSDataOutputStream output;
private TaskAttemptID taskid;
SpillOutputStream(CachePool p, long rlength, FSDataOutputStream out,
TaskAttemptID tid, int priority) throws IOException{
maxCus = SpillScheduler.get().getMaxPerFileUpCus();
content = new ArrayList<CacheUnit>(maxCus);
pool = p;
output = out;
taskid = tid;
if (output == null) {
throw new IOException("asynchronized write outputstream null!");
}
SpillScheduler.get().registerSpill(output, priority, this);
content.addAll(pool.getUnits(maxCus));
curCU = content.remove(0);
}
| public synchronized void write(byte b[], int off, int length) throws CachePoolFullException { |
mammothcm/mammoth | src/org/apache/hadoop/mapred/SpillScheduler.java | // Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CacheUnit extends ByteArrayInputStream {
// static int cap = 0;
// private boolean isLast = false;
// public CacheUnit() {
// super(new byte[cap]);
// count = 0;
// }
// public int write(InputStream in) throws IOException {
// if (count >= buf.length) {
// return 0;
// }
// int res = in.read(buf, count, buf.length - count);
// if (res < 0) {
// return res;
// }
// count += res;
// return res;
// }
// public int write(byte b[], int off, int len){
// len = Math.min(len, buf.length - count);
// System.arraycopy(b, off, buf, count, len);
// count += len;
// return len;
// }
// public void writeFile(OutputStream out) throws IOException {
// out.write(buf, mark, count);
// }
// public boolean write(int b){
// if (count >= buf.length) {
// return false;
// }
// buf[count++] = (byte)b;
// return true;
// }
// public int getPos() {
// return pos;
// }
// public int getLen() {
// return count;
// }
// public void reinit(){
// count = 0;
// mark = 0;
// pos = 0;
// isLast = false;
// }
// public boolean isLast() {
// return isLast;
// }
// public void setLast() {
// isLast = true;
// }
// }
| import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapred.CachePool.CacheUnit;
import org.apache.hadoop.util.StringUtils; | package org.apache.hadoop.mapred;
public class SpillScheduler extends Thread {
public static final int RECEIVE=0;
public static final int SEND=1;
public static final int SORT=2;
private static final Log LOG = LogFactory.getLog(SpillScheduler.class.getName());
class SpillFile{
int priority;
boolean finished; | // Path: src/org/apache/hadoop/mapred/CachePool.java
// public static class CacheUnit extends ByteArrayInputStream {
// static int cap = 0;
// private boolean isLast = false;
// public CacheUnit() {
// super(new byte[cap]);
// count = 0;
// }
// public int write(InputStream in) throws IOException {
// if (count >= buf.length) {
// return 0;
// }
// int res = in.read(buf, count, buf.length - count);
// if (res < 0) {
// return res;
// }
// count += res;
// return res;
// }
// public int write(byte b[], int off, int len){
// len = Math.min(len, buf.length - count);
// System.arraycopy(b, off, buf, count, len);
// count += len;
// return len;
// }
// public void writeFile(OutputStream out) throws IOException {
// out.write(buf, mark, count);
// }
// public boolean write(int b){
// if (count >= buf.length) {
// return false;
// }
// buf[count++] = (byte)b;
// return true;
// }
// public int getPos() {
// return pos;
// }
// public int getLen() {
// return count;
// }
// public void reinit(){
// count = 0;
// mark = 0;
// pos = 0;
// isLast = false;
// }
// public boolean isLast() {
// return isLast;
// }
// public void setLast() {
// isLast = true;
// }
// }
// Path: src/org/apache/hadoop/mapred/SpillScheduler.java
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapred.CachePool.CacheUnit;
import org.apache.hadoop.util.StringUtils;
package org.apache.hadoop.mapred;
public class SpillScheduler extends Thread {
public static final int RECEIVE=0;
public static final int SEND=1;
public static final int SORT=2;
private static final Log LOG = LogFactory.getLog(SpillScheduler.class.getName());
class SpillFile{
int priority;
boolean finished; | List<CacheUnit> cus; |
ae6623/Zebra | zebra4j/zebra-boot/src/test/java/com58/zhl/concurrent/Cptt13_DBNonblock.java | // Path: zebra4j/zebra-boot/src/test/java/com58/zhl/util/DatabaseConnection.java
// public class DatabaseConnection {
//
// private static final String DRIVER="oracle.jdbc.driver.OracleDriver";
//
// private static final String URL="jdbc:oracle:thin:@localhost:1521:orcl";
//
// private static final String pwd="scott";
//
// private static final String name="scott";
//
// public static Connection getConnection(){
// try {
// Class.forName(DRIVER);
// Connection conn=DriverManager.getConnection(URL, name, pwd);
// return conn;
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static void closeConnection(Connection conn){
// try {
// conn.close();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
//
// }
| import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.concurrent.CountDownLatch;
import com58.zhl.util.DatabaseConnection; | package com58.zhl.concurrent;
/**
* 打造基于数据库操作的非阻塞算法
* @author 58_zhl
*
*/
public class Cptt13_DBNonblock {
/**
* 并发数量
*/
private static int count=10;
private static CountDownLatch latch=new CountDownLatch(count);
public static void testConcurrent() throws InterruptedException{
for(int i=0;i<count;i++){
Thread th=new AccessDB(i+1);
th.start();
if(i+1==count){ //最后一个线程启动完毕
System.out.println("======================");
}else{
Thread.sleep(500);
}
}
}
private static class AccessDB extends Thread{
private int id;
public AccessDB(int id){
this.id=id;
}
public void run(){ | // Path: zebra4j/zebra-boot/src/test/java/com58/zhl/util/DatabaseConnection.java
// public class DatabaseConnection {
//
// private static final String DRIVER="oracle.jdbc.driver.OracleDriver";
//
// private static final String URL="jdbc:oracle:thin:@localhost:1521:orcl";
//
// private static final String pwd="scott";
//
// private static final String name="scott";
//
// public static Connection getConnection(){
// try {
// Class.forName(DRIVER);
// Connection conn=DriverManager.getConnection(URL, name, pwd);
// return conn;
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static void closeConnection(Connection conn){
// try {
// conn.close();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
//
// }
// Path: zebra4j/zebra-boot/src/test/java/com58/zhl/concurrent/Cptt13_DBNonblock.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.concurrent.CountDownLatch;
import com58.zhl.util.DatabaseConnection;
package com58.zhl.concurrent;
/**
* 打造基于数据库操作的非阻塞算法
* @author 58_zhl
*
*/
public class Cptt13_DBNonblock {
/**
* 并发数量
*/
private static int count=10;
private static CountDownLatch latch=new CountDownLatch(count);
public static void testConcurrent() throws InterruptedException{
for(int i=0;i<count;i++){
Thread th=new AccessDB(i+1);
th.start();
if(i+1==count){ //最后一个线程启动完毕
System.out.println("======================");
}else{
Thread.sleep(500);
}
}
}
private static class AccessDB extends Thread{
private int id;
public AccessDB(int id){
this.id=id;
}
public void run(){ | Connection conn=DatabaseConnection.getConnection(); |
ae6623/Zebra | zebra4j/zebra-boot/src/main/java/com/zebra/boot/listener/ZebraListener.java | // Path: zebra4j/zebra-boot/src/main/java/com/zebra/boot/registry/IRegistry.java
// public interface IRegistry {
//
// /**
// * 服务注册信息
// *
// * @param serviceName 服务名称 比如 zebra/service
// * @param address 服务真实地址 比如 ip:port
// */
// void register(String serviceName, String address);
//
// /**
// * 服务卸载
// * @param serviceName
// * @param address
// */
// void unRegister(String serviceName, String address);
// }
| import com.zebra.boot.registry.IRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.Map; | package com.zebra.boot.listener;
/**
* Created by js-dev.cn on 2016/11/24.
* 监听器:当服务启动之后,立即监听并开始向注册中心Registry注册服务,告诉注册中心,自己是一个服务节点
*/
@Component
@ComponentScan
@WebListener
public class ZebraListener implements ServletContextListener{
private static Logger logger = LoggerFactory.getLogger(ZebraListener.class);
@Value("${server.address}")
private String serverAddress;
@Value("${server.port}")
private int serverPort;
@Autowired | // Path: zebra4j/zebra-boot/src/main/java/com/zebra/boot/registry/IRegistry.java
// public interface IRegistry {
//
// /**
// * 服务注册信息
// *
// * @param serviceName 服务名称 比如 zebra/service
// * @param address 服务真实地址 比如 ip:port
// */
// void register(String serviceName, String address);
//
// /**
// * 服务卸载
// * @param serviceName
// * @param address
// */
// void unRegister(String serviceName, String address);
// }
// Path: zebra4j/zebra-boot/src/main/java/com/zebra/boot/listener/ZebraListener.java
import com.zebra.boot.registry.IRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.Map;
package com.zebra.boot.listener;
/**
* Created by js-dev.cn on 2016/11/24.
* 监听器:当服务启动之后,立即监听并开始向注册中心Registry注册服务,告诉注册中心,自己是一个服务节点
*/
@Component
@ComponentScan
@WebListener
public class ZebraListener implements ServletContextListener{
private static Logger logger = LoggerFactory.getLogger(ZebraListener.class);
@Value("${server.address}")
private String serverAddress;
@Value("${server.port}")
private int serverPort;
@Autowired | private IRegistry registry; |
vznet/mongo-jackson-mapper | src/main/java/net/vz/mongodb/jackson/internal/MongoJacksonMapperModule.java | // Path: src/main/java/net/vz/mongodb/jackson/internal/stream/ServerErrorProblemHandler.java
// public class ServerErrorProblemHandler extends DeserializationProblemHandler {
// @Override
// public boolean handleUnknownProperty(DeserializationContext ctxt, JsonDeserializer<?> deserializer,
// Object beanOrClass, String propertyName) throws IOException, JsonProcessingException {
// if (ctxt.getParser() instanceof DBDecoderBsonParser) {
// return ((DBDecoderBsonParser) ctxt.getParser()).handleUnknownProperty(ctxt, deserializer, beanOrClass, propertyName);
// }
// return false;
// }
// }
| import net.vz.mongodb.jackson.internal.stream.ServerErrorProblemHandler;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.Module;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize; | /*
* Copyright 2011 VZ Netzwerke Ltd
*
* 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 net.vz.mongodb.jackson.internal;
/**
* The ObjectID serialising module
*
* @author James Roper
* @since 1.0
*/
public class MongoJacksonMapperModule extends Module {
public static final Module INSTANCE = new MongoJacksonMapperModule();
/**
* Configure the given object mapper to be used with the Mongo Jackson Mapper. Please call this method rather than
* calling objectMapper.with(MongoJacksonMapperModule.INSTANCE), because Jacksons module system doesn't allow the
* mongo jackson mapper to do all the configuration it needs to do. This method will do that configuration though.
*
* @param objectMapper The object mapper to configure
* @return This object mapper (for chaining)
*/
public static ObjectMapper configure(ObjectMapper objectMapper) {
objectMapper.registerModule(INSTANCE);
objectMapper.setHandlerInstantiator(new MongoJacksonHandlerInstantiator(
new MongoAnnotationIntrospector(objectMapper.getDeserializationConfig())));
return objectMapper;
}
@Override
public String getModuleName() {
return "Object ID Module";
}
@Override
public Version version() {
return new Version(1, 0, 0, null);
}
@Override
public void setupModule(SetupContext context) {
MongoAnnotationIntrospector annotationIntrospector = new MongoAnnotationIntrospector(context.getDeserializationConfig());
context.insertAnnotationIntrospector(annotationIntrospector);
// Only include non null properties, this makes it possible to use object templates for querying and
// partial object retrieving
context.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); | // Path: src/main/java/net/vz/mongodb/jackson/internal/stream/ServerErrorProblemHandler.java
// public class ServerErrorProblemHandler extends DeserializationProblemHandler {
// @Override
// public boolean handleUnknownProperty(DeserializationContext ctxt, JsonDeserializer<?> deserializer,
// Object beanOrClass, String propertyName) throws IOException, JsonProcessingException {
// if (ctxt.getParser() instanceof DBDecoderBsonParser) {
// return ((DBDecoderBsonParser) ctxt.getParser()).handleUnknownProperty(ctxt, deserializer, beanOrClass, propertyName);
// }
// return false;
// }
// }
// Path: src/main/java/net/vz/mongodb/jackson/internal/MongoJacksonMapperModule.java
import net.vz.mongodb.jackson.internal.stream.ServerErrorProblemHandler;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.Module;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/*
* Copyright 2011 VZ Netzwerke Ltd
*
* 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 net.vz.mongodb.jackson.internal;
/**
* The ObjectID serialising module
*
* @author James Roper
* @since 1.0
*/
public class MongoJacksonMapperModule extends Module {
public static final Module INSTANCE = new MongoJacksonMapperModule();
/**
* Configure the given object mapper to be used with the Mongo Jackson Mapper. Please call this method rather than
* calling objectMapper.with(MongoJacksonMapperModule.INSTANCE), because Jacksons module system doesn't allow the
* mongo jackson mapper to do all the configuration it needs to do. This method will do that configuration though.
*
* @param objectMapper The object mapper to configure
* @return This object mapper (for chaining)
*/
public static ObjectMapper configure(ObjectMapper objectMapper) {
objectMapper.registerModule(INSTANCE);
objectMapper.setHandlerInstantiator(new MongoJacksonHandlerInstantiator(
new MongoAnnotationIntrospector(objectMapper.getDeserializationConfig())));
return objectMapper;
}
@Override
public String getModuleName() {
return "Object ID Module";
}
@Override
public Version version() {
return new Version(1, 0, 0, null);
}
@Override
public void setupModule(SetupContext context) {
MongoAnnotationIntrospector annotationIntrospector = new MongoAnnotationIntrospector(context.getDeserializationConfig());
context.insertAnnotationIntrospector(annotationIntrospector);
// Only include non null properties, this makes it possible to use object templates for querying and
// partial object retrieving
context.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); | context.getDeserializationConfig().addHandler(new ServerErrorProblemHandler()); |
vznet/mongo-jackson-mapper | src/test/java/net/vz/mongodb/jackson/TestWriteResult.java | // Path: src/test/java/net/vz/mongodb/jackson/mock/MockObject.java
// public class MockObject {
// public String _id;
// public String string;
// public Integer integer;
// public Long longs;
// public BigInteger bigInteger;
// public Float floats;
// public Double doubles;
// public BigDecimal bigDecimal;
// public Boolean booleans;
// public Date date;
//
// public List<String> simpleList;
// public List<MockEmbeddedObject> complexList;
// public MockEmbeddedObject object;
//
// public MockObject() {
// }
//
// public MockObject(String _id, String string, Integer integer) {
// this._id = _id;
// this.string = string;
// this.integer = integer;
// }
//
// public MockObject(String string, Integer integer) {
// this.string = string;
// this.integer = integer;
// }
//
// @Override
// public String toString() {
// return "MockObject{" +
// "_id='" + _id + '\'' +
// ", string='" + string + '\'' +
// ", integer=" + integer +
// ", longs=" + longs +
// ", bigInteger=" + bigInteger +
// ", floats=" + floats +
// ", doubles=" + doubles +
// ", bigDecimal=" + bigDecimal +
// ", booleans=" + booleans +
// ", date=" + date +
// ", simpleList=" + simpleList +
// ", complexList=" + complexList +
// ", object=" + object +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// MockObject that = (MockObject) o;
//
// if (_id != null ? !_id.equals(that._id) : that._id != null) return false;
// if (bigDecimal != null ? !bigDecimal.equals(that.bigDecimal) : that.bigDecimal != null) return false;
// if (bigInteger != null ? !bigInteger.equals(that.bigInteger) : that.bigInteger != null) return false;
// if (booleans != null ? !booleans.equals(that.booleans) : that.booleans != null) return false;
// if (complexList != null ? !complexList.equals(that.complexList) : that.complexList != null) return false;
// if (doubles != null ? !doubles.equals(that.doubles) : that.doubles != null) return false;
// if (floats != null ? !floats.equals(that.floats) : that.floats != null) return false;
// if (integer != null ? !integer.equals(that.integer) : that.integer != null) return false;
// if (longs != null ? !longs.equals(that.longs) : that.longs != null) return false;
// if (date != null ? !date.equals(that.date) : that.date != null) return false;
// if (object != null ? !object.equals(that.object) : that.object != null) return false;
// if (simpleList != null ? !simpleList.equals(that.simpleList) : that.simpleList != null) return false;
// if (string != null ? !string.equals(that.string) : that.string != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = _id != null ? _id.hashCode() : 0;
// result = 31 * result + (string != null ? string.hashCode() : 0);
// result = 31 * result + (integer != null ? integer.hashCode() : 0);
// result = 31 * result + (longs != null ? longs.hashCode() : 0);
// result = 31 * result + (bigInteger != null ? bigInteger.hashCode() : 0);
// result = 31 * result + (floats != null ? floats.hashCode() : 0);
// result = 31 * result + (doubles != null ? doubles.hashCode() : 0);
// result = 31 * result + (bigDecimal != null ? bigDecimal.hashCode() : 0);
// result = 31 * result + (booleans != null ? booleans.hashCode() : 0);
// result = 31 * result + (date != null ? date.hashCode() : 0);
// result = 31 * result + (simpleList != null ? simpleList.hashCode() : 0);
// result = 31 * result + (complexList != null ? complexList.hashCode() : 0);
// result = 31 * result + (object != null ? object.hashCode() : 0);
// return result;
// }
// }
| import net.vz.mongodb.jackson.mock.MockObject;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat; | /*
* Copyright 2011 VZ Netzwerke Ltd
*
* 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 net.vz.mongodb.jackson;
@MongoTestParams(serializerType = MongoTestParams.SerializationType.OBJECT)
public class TestWriteResult extends MongoDBTestBase { | // Path: src/test/java/net/vz/mongodb/jackson/mock/MockObject.java
// public class MockObject {
// public String _id;
// public String string;
// public Integer integer;
// public Long longs;
// public BigInteger bigInteger;
// public Float floats;
// public Double doubles;
// public BigDecimal bigDecimal;
// public Boolean booleans;
// public Date date;
//
// public List<String> simpleList;
// public List<MockEmbeddedObject> complexList;
// public MockEmbeddedObject object;
//
// public MockObject() {
// }
//
// public MockObject(String _id, String string, Integer integer) {
// this._id = _id;
// this.string = string;
// this.integer = integer;
// }
//
// public MockObject(String string, Integer integer) {
// this.string = string;
// this.integer = integer;
// }
//
// @Override
// public String toString() {
// return "MockObject{" +
// "_id='" + _id + '\'' +
// ", string='" + string + '\'' +
// ", integer=" + integer +
// ", longs=" + longs +
// ", bigInteger=" + bigInteger +
// ", floats=" + floats +
// ", doubles=" + doubles +
// ", bigDecimal=" + bigDecimal +
// ", booleans=" + booleans +
// ", date=" + date +
// ", simpleList=" + simpleList +
// ", complexList=" + complexList +
// ", object=" + object +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// MockObject that = (MockObject) o;
//
// if (_id != null ? !_id.equals(that._id) : that._id != null) return false;
// if (bigDecimal != null ? !bigDecimal.equals(that.bigDecimal) : that.bigDecimal != null) return false;
// if (bigInteger != null ? !bigInteger.equals(that.bigInteger) : that.bigInteger != null) return false;
// if (booleans != null ? !booleans.equals(that.booleans) : that.booleans != null) return false;
// if (complexList != null ? !complexList.equals(that.complexList) : that.complexList != null) return false;
// if (doubles != null ? !doubles.equals(that.doubles) : that.doubles != null) return false;
// if (floats != null ? !floats.equals(that.floats) : that.floats != null) return false;
// if (integer != null ? !integer.equals(that.integer) : that.integer != null) return false;
// if (longs != null ? !longs.equals(that.longs) : that.longs != null) return false;
// if (date != null ? !date.equals(that.date) : that.date != null) return false;
// if (object != null ? !object.equals(that.object) : that.object != null) return false;
// if (simpleList != null ? !simpleList.equals(that.simpleList) : that.simpleList != null) return false;
// if (string != null ? !string.equals(that.string) : that.string != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = _id != null ? _id.hashCode() : 0;
// result = 31 * result + (string != null ? string.hashCode() : 0);
// result = 31 * result + (integer != null ? integer.hashCode() : 0);
// result = 31 * result + (longs != null ? longs.hashCode() : 0);
// result = 31 * result + (bigInteger != null ? bigInteger.hashCode() : 0);
// result = 31 * result + (floats != null ? floats.hashCode() : 0);
// result = 31 * result + (doubles != null ? doubles.hashCode() : 0);
// result = 31 * result + (bigDecimal != null ? bigDecimal.hashCode() : 0);
// result = 31 * result + (booleans != null ? booleans.hashCode() : 0);
// result = 31 * result + (date != null ? date.hashCode() : 0);
// result = 31 * result + (simpleList != null ? simpleList.hashCode() : 0);
// result = 31 * result + (complexList != null ? complexList.hashCode() : 0);
// result = 31 * result + (object != null ? object.hashCode() : 0);
// return result;
// }
// }
// Path: src/test/java/net/vz/mongodb/jackson/TestWriteResult.java
import net.vz.mongodb.jackson.mock.MockObject;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
/*
* Copyright 2011 VZ Netzwerke Ltd
*
* 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 net.vz.mongodb.jackson;
@MongoTestParams(serializerType = MongoTestParams.SerializationType.OBJECT)
public class TestWriteResult extends MongoDBTestBase { | private JacksonDBCollection<MockObject, String> coll; |
vznet/mongo-jackson-mapper | src/main/java/net/vz/mongodb/jackson/WriteResult.java | // Path: src/main/java/net/vz/mongodb/jackson/internal/stream/JacksonDBObject.java
// public class JacksonDBObject<T> extends BasicDBObject {
// public JacksonDBObject() {
// }
//
// public JacksonDBObject(T object) {
// this.object = object;
// }
//
// private T object;
//
// public T getObject() {
// return object;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// @Override
// public Object get(String key) {
// if ("_id".equals(key)) {
// return "Generated _id retrieval not supported when using stream serialization";
// }
// return super.get(key);
// }
// }
| import java.util.ArrayList;
import java.util.List;
import com.mongodb.CommandResult;
import com.mongodb.DBObject;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import net.vz.mongodb.jackson.internal.stream.JacksonDBObject; | /*
* Copyright 2011 VZ Netzwerke Ltd
*
* 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 net.vz.mongodb.jackson;
/**
* This class lets you access the results of the previous write.
* if you have STRICT mode on, this just stores the result of that getLastError call
* if you don't, then this will actually do the getlasterror call.
* if another operation has been done on this connection in the interim, calls will fail
*
* This class also gives you access to the saved objects, for the purposes of finding out the objects ids, if they were
* generated by MongoDB.
*
* @author James Roper
* @since 1.0
*/
public class WriteResult<T, K> {
private final JacksonDBCollection<T, K> jacksonDBCollection;
private final DBObject[] dbObjects;
private final com.mongodb.WriteResult writeResult;
private List<T> objects;
protected WriteResult(JacksonDBCollection<T, K> jacksonDBCollection, com.mongodb.WriteResult writeResult, DBObject... dbObjects) {
this.jacksonDBCollection = jacksonDBCollection;
this.writeResult = writeResult;
this.dbObjects = dbObjects;
}
/**
* Get the object that was saved. This will contain the updated ID if the ID was generated.
* <p/>
* Note, this operation is a little expensive because it has to deserialise the object. If you just want the ID,
* call getSavedId() instead.
*
* @return The saved object
* @throws MongoException If no objects were saved
*/
public T getSavedObject() {
if (dbObjects.length == 0) {
throw new MongoException("No objects to return");
}
return getSavedObjects().get(0);
}
/**
* Get the objects that were saved. These will contain the updated IDs if the IDs were generated.
* <p/>
* This operation only works if object serialization is used. If stream serialization is used, the IDs are
* generated by the database, and cannot be known.
* <p/>
* Note, this operation is a little expensive because it has to deserialise the objects. If you just want the IDs,
* call getSavedIds() instead.
*
* @return The saved objects
*/
public List<T> getSavedObjects() {
// Lazily generate the object, in case it's not needed.
if (objects == null) {
if (dbObjects.length > 0) { | // Path: src/main/java/net/vz/mongodb/jackson/internal/stream/JacksonDBObject.java
// public class JacksonDBObject<T> extends BasicDBObject {
// public JacksonDBObject() {
// }
//
// public JacksonDBObject(T object) {
// this.object = object;
// }
//
// private T object;
//
// public T getObject() {
// return object;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// @Override
// public Object get(String key) {
// if ("_id".equals(key)) {
// return "Generated _id retrieval not supported when using stream serialization";
// }
// return super.get(key);
// }
// }
// Path: src/main/java/net/vz/mongodb/jackson/WriteResult.java
import java.util.ArrayList;
import java.util.List;
import com.mongodb.CommandResult;
import com.mongodb.DBObject;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import net.vz.mongodb.jackson.internal.stream.JacksonDBObject;
/*
* Copyright 2011 VZ Netzwerke Ltd
*
* 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 net.vz.mongodb.jackson;
/**
* This class lets you access the results of the previous write.
* if you have STRICT mode on, this just stores the result of that getLastError call
* if you don't, then this will actually do the getlasterror call.
* if another operation has been done on this connection in the interim, calls will fail
*
* This class also gives you access to the saved objects, for the purposes of finding out the objects ids, if they were
* generated by MongoDB.
*
* @author James Roper
* @since 1.0
*/
public class WriteResult<T, K> {
private final JacksonDBCollection<T, K> jacksonDBCollection;
private final DBObject[] dbObjects;
private final com.mongodb.WriteResult writeResult;
private List<T> objects;
protected WriteResult(JacksonDBCollection<T, K> jacksonDBCollection, com.mongodb.WriteResult writeResult, DBObject... dbObjects) {
this.jacksonDBCollection = jacksonDBCollection;
this.writeResult = writeResult;
this.dbObjects = dbObjects;
}
/**
* Get the object that was saved. This will contain the updated ID if the ID was generated.
* <p/>
* Note, this operation is a little expensive because it has to deserialise the object. If you just want the ID,
* call getSavedId() instead.
*
* @return The saved object
* @throws MongoException If no objects were saved
*/
public T getSavedObject() {
if (dbObjects.length == 0) {
throw new MongoException("No objects to return");
}
return getSavedObjects().get(0);
}
/**
* Get the objects that were saved. These will contain the updated IDs if the IDs were generated.
* <p/>
* This operation only works if object serialization is used. If stream serialization is used, the IDs are
* generated by the database, and cannot be known.
* <p/>
* Note, this operation is a little expensive because it has to deserialise the objects. If you just want the IDs,
* call getSavedIds() instead.
*
* @return The saved objects
*/
public List<T> getSavedObjects() {
// Lazily generate the object, in case it's not needed.
if (objects == null) {
if (dbObjects.length > 0) { | if (dbObjects[0] instanceof JacksonDBObject) { |
vznet/mongo-jackson-mapper | src/main/java/net/vz/mongodb/jackson/internal/MongoJacksonDeserializers.java | // Path: src/main/java/net/vz/mongodb/jackson/DBRef.java
// public class DBRef<T, K> {
// private final K id;
// private final String collectionName;
//
// /**
// * Construct a new database reference with the given id and collection name
// *
// * @param id The id of the database reference to construct
// * @param collectionName The name of the collection
// */
// public DBRef(K id, String collectionName) {
// this.id = id;
// this.collectionName = collectionName;
// }
//
// /**
// * Construct a new database reference with the given id and type. The type must be annotated with
// * {@link MongoCollection}, so that the name can be worked out.
// *
// * @param id The id of the database reference to construct
// * @param type The type of the object
// * @throws MongoJsonMappingException If no MongoCollection annotation is found on the type
// */
// public DBRef(K id, Class<T> type) throws MongoJsonMappingException {
// this.id = id;
// MongoCollection collection = type.getAnnotation(MongoCollection.class);
// if (collection == null) {
// throw new MongoJsonMappingException("Only types that have the @MongoCollection annotation on them can be used with this constructor");
// }
// this.collectionName = collection.name();
// }
//
// /**
// * Get the ID of this object
// *
// * @return The ID of this object
// */
// public K getId() {
// return id;
// }
//
// /**
// * Get the name of the collection this object lives in
// *
// * @return The name of the collection this object lives in
// */
// public String getCollectionName() {
// return collectionName;
// }
//
// /**
// * Fetch the object. Should only be called for references that have been returned by the mapper, will return null
// * otherwise.
// * <p/>
// * Deserialisation is done by the ObjectMapper that fetched the object that this reference belongs to.
// *
// * @return If this DBRef was returned by the mapper, the referenced object, if it exists, or null
// */
// public T fetch() {
// return null;
// }
//
// /**
// * Fetch only the given fields of the object. Should only be called for references that have been returned by the
// * mapper, will return null otherwise.
// * <p/>
// * Deserialisation is done by the ObjectMapper that fetched the object that this reference belongs to.
// * <p/>
// * Unlike the <code>fetch()</code> method, calls to this are not cached.
// *
// * @param fields The fields to fetch
// * @return If this DBRef was returned by the mapper, the referenced object, if it exists, or null
// */
// public T fetch(DBObject fields) {
// return null;
// }
// }
| import net.vz.mongodb.jackson.DBRef;
import org.codehaus.jackson.map.BeanDescription;
import org.codehaus.jackson.map.BeanProperty;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.DeserializerProvider;
import org.codehaus.jackson.map.JsonDeserializer;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.module.SimpleDeserializers;
import org.codehaus.jackson.type.JavaType;
import java.util.Calendar;
import java.util.Date; | /*
* Copyright 2011 VZ Netzwerke Ltd
*
* 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 net.vz.mongodb.jackson.internal;
/**
* Deserializers for Mongo Jackson Mapper
*
* @author James Roper
* @since 1.2
*/
public class MongoJacksonDeserializers extends SimpleDeserializers {
public MongoJacksonDeserializers() {
addDeserializer(Date.class, new DateDeserializer());
addDeserializer(Calendar.class, new CalendarDeserializer());
}
public JsonDeserializer<?> findBeanDeserializer(JavaType type, DeserializationConfig config, DeserializerProvider provider, BeanDescription beanDesc, BeanProperty property) throws JsonMappingException { | // Path: src/main/java/net/vz/mongodb/jackson/DBRef.java
// public class DBRef<T, K> {
// private final K id;
// private final String collectionName;
//
// /**
// * Construct a new database reference with the given id and collection name
// *
// * @param id The id of the database reference to construct
// * @param collectionName The name of the collection
// */
// public DBRef(K id, String collectionName) {
// this.id = id;
// this.collectionName = collectionName;
// }
//
// /**
// * Construct a new database reference with the given id and type. The type must be annotated with
// * {@link MongoCollection}, so that the name can be worked out.
// *
// * @param id The id of the database reference to construct
// * @param type The type of the object
// * @throws MongoJsonMappingException If no MongoCollection annotation is found on the type
// */
// public DBRef(K id, Class<T> type) throws MongoJsonMappingException {
// this.id = id;
// MongoCollection collection = type.getAnnotation(MongoCollection.class);
// if (collection == null) {
// throw new MongoJsonMappingException("Only types that have the @MongoCollection annotation on them can be used with this constructor");
// }
// this.collectionName = collection.name();
// }
//
// /**
// * Get the ID of this object
// *
// * @return The ID of this object
// */
// public K getId() {
// return id;
// }
//
// /**
// * Get the name of the collection this object lives in
// *
// * @return The name of the collection this object lives in
// */
// public String getCollectionName() {
// return collectionName;
// }
//
// /**
// * Fetch the object. Should only be called for references that have been returned by the mapper, will return null
// * otherwise.
// * <p/>
// * Deserialisation is done by the ObjectMapper that fetched the object that this reference belongs to.
// *
// * @return If this DBRef was returned by the mapper, the referenced object, if it exists, or null
// */
// public T fetch() {
// return null;
// }
//
// /**
// * Fetch only the given fields of the object. Should only be called for references that have been returned by the
// * mapper, will return null otherwise.
// * <p/>
// * Deserialisation is done by the ObjectMapper that fetched the object that this reference belongs to.
// * <p/>
// * Unlike the <code>fetch()</code> method, calls to this are not cached.
// *
// * @param fields The fields to fetch
// * @return If this DBRef was returned by the mapper, the referenced object, if it exists, or null
// */
// public T fetch(DBObject fields) {
// return null;
// }
// }
// Path: src/main/java/net/vz/mongodb/jackson/internal/MongoJacksonDeserializers.java
import net.vz.mongodb.jackson.DBRef;
import org.codehaus.jackson.map.BeanDescription;
import org.codehaus.jackson.map.BeanProperty;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.DeserializerProvider;
import org.codehaus.jackson.map.JsonDeserializer;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.module.SimpleDeserializers;
import org.codehaus.jackson.type.JavaType;
import java.util.Calendar;
import java.util.Date;
/*
* Copyright 2011 VZ Netzwerke Ltd
*
* 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 net.vz.mongodb.jackson.internal;
/**
* Deserializers for Mongo Jackson Mapper
*
* @author James Roper
* @since 1.2
*/
public class MongoJacksonDeserializers extends SimpleDeserializers {
public MongoJacksonDeserializers() {
addDeserializer(Date.class, new DateDeserializer());
addDeserializer(Calendar.class, new CalendarDeserializer());
}
public JsonDeserializer<?> findBeanDeserializer(JavaType type, DeserializationConfig config, DeserializerProvider provider, BeanDescription beanDesc, BeanProperty property) throws JsonMappingException { | if (type.getRawClass() == DBRef.class) { |
vznet/mongo-jackson-mapper | src/main/java/net/vz/mongodb/jackson/internal/stream/JacksonDBEncoder.java | // Path: src/main/java/net/vz/mongodb/jackson/MongoJsonMappingException.java
// public class MongoJsonMappingException extends MongoException {
//
// public MongoJsonMappingException(String msg) {
// super(msg);
// }
//
// public MongoJsonMappingException(JsonMappingException e) {
// super("Error mapping BSON to POJOs", e);
// }
//
// public MongoJsonMappingException(String msg, JsonMappingException e) {
// super(msg, e);
// }
// }
| import com.mongodb.DBEncoder;
import com.mongodb.MongoException;
import de.undercouch.bson4jackson.BsonGenerator;
import net.vz.mongodb.jackson.MongoJsonMappingException;
import org.bson.BSONObject;
import org.bson.io.OutputBuffer;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException; | /*
* Copyright 2011 VZ Netzwerke Ltd
*
* 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 net.vz.mongodb.jackson.internal.stream;
/**
* DBEncoder that uses bson4jackson if the object is a JacksonDBObject
*/
public class JacksonDBEncoder implements DBEncoder {
private final ObjectMapper objectMapper;
private final DBEncoder defaultDBEncoder;
public JacksonDBEncoder(ObjectMapper objectMapper, DBEncoder defaultDBEncoder) {
this.objectMapper = objectMapper;
this.defaultDBEncoder = defaultDBEncoder;
}
public int writeObject(OutputBuffer buf, BSONObject object) {
if (object instanceof JacksonDBObject) {
Object actualObject = ((JacksonDBObject) object).getObject();
OutputBufferOutputStream stream = new OutputBufferOutputStream(buf);
BsonGenerator generator = new DBEncoderBsonGenerator(JsonGenerator.Feature.collectDefaults(), stream);
try {
objectMapper.writeValue(generator, actualObject);
// The generator buffers everything so that it can write the number of bytes to the stream
generator.close();
} catch (JsonMappingException e) { | // Path: src/main/java/net/vz/mongodb/jackson/MongoJsonMappingException.java
// public class MongoJsonMappingException extends MongoException {
//
// public MongoJsonMappingException(String msg) {
// super(msg);
// }
//
// public MongoJsonMappingException(JsonMappingException e) {
// super("Error mapping BSON to POJOs", e);
// }
//
// public MongoJsonMappingException(String msg, JsonMappingException e) {
// super(msg, e);
// }
// }
// Path: src/main/java/net/vz/mongodb/jackson/internal/stream/JacksonDBEncoder.java
import com.mongodb.DBEncoder;
import com.mongodb.MongoException;
import de.undercouch.bson4jackson.BsonGenerator;
import net.vz.mongodb.jackson.MongoJsonMappingException;
import org.bson.BSONObject;
import org.bson.io.OutputBuffer;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
/*
* Copyright 2011 VZ Netzwerke Ltd
*
* 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 net.vz.mongodb.jackson.internal.stream;
/**
* DBEncoder that uses bson4jackson if the object is a JacksonDBObject
*/
public class JacksonDBEncoder implements DBEncoder {
private final ObjectMapper objectMapper;
private final DBEncoder defaultDBEncoder;
public JacksonDBEncoder(ObjectMapper objectMapper, DBEncoder defaultDBEncoder) {
this.objectMapper = objectMapper;
this.defaultDBEncoder = defaultDBEncoder;
}
public int writeObject(OutputBuffer buf, BSONObject object) {
if (object instanceof JacksonDBObject) {
Object actualObject = ((JacksonDBObject) object).getObject();
OutputBufferOutputStream stream = new OutputBufferOutputStream(buf);
BsonGenerator generator = new DBEncoderBsonGenerator(JsonGenerator.Feature.collectDefaults(), stream);
try {
objectMapper.writeValue(generator, actualObject);
// The generator buffers everything so that it can write the number of bytes to the stream
generator.close();
} catch (JsonMappingException e) { | throw new MongoJsonMappingException(e); |
vznet/mongo-jackson-mapper | src/main/java/net/vz/mongodb/jackson/internal/MongoAnnotationIntrospector.java | // Path: src/main/java/net/vz/mongodb/jackson/DBRef.java
// public class DBRef<T, K> {
// private final K id;
// private final String collectionName;
//
// /**
// * Construct a new database reference with the given id and collection name
// *
// * @param id The id of the database reference to construct
// * @param collectionName The name of the collection
// */
// public DBRef(K id, String collectionName) {
// this.id = id;
// this.collectionName = collectionName;
// }
//
// /**
// * Construct a new database reference with the given id and type. The type must be annotated with
// * {@link MongoCollection}, so that the name can be worked out.
// *
// * @param id The id of the database reference to construct
// * @param type The type of the object
// * @throws MongoJsonMappingException If no MongoCollection annotation is found on the type
// */
// public DBRef(K id, Class<T> type) throws MongoJsonMappingException {
// this.id = id;
// MongoCollection collection = type.getAnnotation(MongoCollection.class);
// if (collection == null) {
// throw new MongoJsonMappingException("Only types that have the @MongoCollection annotation on them can be used with this constructor");
// }
// this.collectionName = collection.name();
// }
//
// /**
// * Get the ID of this object
// *
// * @return The ID of this object
// */
// public K getId() {
// return id;
// }
//
// /**
// * Get the name of the collection this object lives in
// *
// * @return The name of the collection this object lives in
// */
// public String getCollectionName() {
// return collectionName;
// }
//
// /**
// * Fetch the object. Should only be called for references that have been returned by the mapper, will return null
// * otherwise.
// * <p/>
// * Deserialisation is done by the ObjectMapper that fetched the object that this reference belongs to.
// *
// * @return If this DBRef was returned by the mapper, the referenced object, if it exists, or null
// */
// public T fetch() {
// return null;
// }
//
// /**
// * Fetch only the given fields of the object. Should only be called for references that have been returned by the
// * mapper, will return null otherwise.
// * <p/>
// * Deserialisation is done by the ObjectMapper that fetched the object that this reference belongs to.
// * <p/>
// * Unlike the <code>fetch()</code> method, calls to this are not cached.
// *
// * @param fields The fields to fetch
// * @return If this DBRef was returned by the mapper, the referenced object, if it exists, or null
// */
// public T fetch(DBObject fields) {
// return null;
// }
// }
| import net.vz.mongodb.jackson.DBRef;
import net.vz.mongodb.jackson.Id;
import net.vz.mongodb.jackson.ObjectId;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.introspect.*;
import org.codehaus.jackson.type.JavaType;
import java.lang.annotation.Annotation; | }
return null;
}
@Override
public Object findDeserializer(Annotated am) {
if (am.hasAnnotation(ObjectId.class)) {
return findObjectIdDeserializer(deserializationConfig.getTypeFactory().constructType(am.getGenericType()));
}
return null;
}
@Override
public Class findContentDeserializer(Annotated am) {
if (am.hasAnnotation(ObjectId.class)) {
JavaType type = deserializationConfig.getTypeFactory().constructType(am.getGenericType());
if (type.isCollectionLikeType()) {
return findObjectIdDeserializer(type.containedType(0));
} else if (type.isMapLikeType()) {
return findObjectIdDeserializer(type.containedType(1));
}
}
return null;
}
public Class findObjectIdDeserializer(JavaType type) {
if (type.getRawClass() == String.class) {
return ObjectIdDeserializers.ToStringDeserializer.class;
} else if (type.getRawClass() == byte[].class) {
return ObjectIdDeserializers.ToByteArrayDeserializer.class; | // Path: src/main/java/net/vz/mongodb/jackson/DBRef.java
// public class DBRef<T, K> {
// private final K id;
// private final String collectionName;
//
// /**
// * Construct a new database reference with the given id and collection name
// *
// * @param id The id of the database reference to construct
// * @param collectionName The name of the collection
// */
// public DBRef(K id, String collectionName) {
// this.id = id;
// this.collectionName = collectionName;
// }
//
// /**
// * Construct a new database reference with the given id and type. The type must be annotated with
// * {@link MongoCollection}, so that the name can be worked out.
// *
// * @param id The id of the database reference to construct
// * @param type The type of the object
// * @throws MongoJsonMappingException If no MongoCollection annotation is found on the type
// */
// public DBRef(K id, Class<T> type) throws MongoJsonMappingException {
// this.id = id;
// MongoCollection collection = type.getAnnotation(MongoCollection.class);
// if (collection == null) {
// throw new MongoJsonMappingException("Only types that have the @MongoCollection annotation on them can be used with this constructor");
// }
// this.collectionName = collection.name();
// }
//
// /**
// * Get the ID of this object
// *
// * @return The ID of this object
// */
// public K getId() {
// return id;
// }
//
// /**
// * Get the name of the collection this object lives in
// *
// * @return The name of the collection this object lives in
// */
// public String getCollectionName() {
// return collectionName;
// }
//
// /**
// * Fetch the object. Should only be called for references that have been returned by the mapper, will return null
// * otherwise.
// * <p/>
// * Deserialisation is done by the ObjectMapper that fetched the object that this reference belongs to.
// *
// * @return If this DBRef was returned by the mapper, the referenced object, if it exists, or null
// */
// public T fetch() {
// return null;
// }
//
// /**
// * Fetch only the given fields of the object. Should only be called for references that have been returned by the
// * mapper, will return null otherwise.
// * <p/>
// * Deserialisation is done by the ObjectMapper that fetched the object that this reference belongs to.
// * <p/>
// * Unlike the <code>fetch()</code> method, calls to this are not cached.
// *
// * @param fields The fields to fetch
// * @return If this DBRef was returned by the mapper, the referenced object, if it exists, or null
// */
// public T fetch(DBObject fields) {
// return null;
// }
// }
// Path: src/main/java/net/vz/mongodb/jackson/internal/MongoAnnotationIntrospector.java
import net.vz.mongodb.jackson.DBRef;
import net.vz.mongodb.jackson.Id;
import net.vz.mongodb.jackson.ObjectId;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.introspect.*;
import org.codehaus.jackson.type.JavaType;
import java.lang.annotation.Annotation;
}
return null;
}
@Override
public Object findDeserializer(Annotated am) {
if (am.hasAnnotation(ObjectId.class)) {
return findObjectIdDeserializer(deserializationConfig.getTypeFactory().constructType(am.getGenericType()));
}
return null;
}
@Override
public Class findContentDeserializer(Annotated am) {
if (am.hasAnnotation(ObjectId.class)) {
JavaType type = deserializationConfig.getTypeFactory().constructType(am.getGenericType());
if (type.isCollectionLikeType()) {
return findObjectIdDeserializer(type.containedType(0));
} else if (type.isMapLikeType()) {
return findObjectIdDeserializer(type.containedType(1));
}
}
return null;
}
public Class findObjectIdDeserializer(JavaType type) {
if (type.getRawClass() == String.class) {
return ObjectIdDeserializers.ToStringDeserializer.class;
} else if (type.getRawClass() == byte[].class) {
return ObjectIdDeserializers.ToByteArrayDeserializer.class; | } else if (type.getRawClass() == DBRef.class) { |
vznet/mongo-jackson-mapper | src/main/java/net/vz/mongodb/jackson/internal/ObjectIdSerializer.java | // Path: src/main/java/net/vz/mongodb/jackson/DBRef.java
// public class DBRef<T, K> {
// private final K id;
// private final String collectionName;
//
// /**
// * Construct a new database reference with the given id and collection name
// *
// * @param id The id of the database reference to construct
// * @param collectionName The name of the collection
// */
// public DBRef(K id, String collectionName) {
// this.id = id;
// this.collectionName = collectionName;
// }
//
// /**
// * Construct a new database reference with the given id and type. The type must be annotated with
// * {@link MongoCollection}, so that the name can be worked out.
// *
// * @param id The id of the database reference to construct
// * @param type The type of the object
// * @throws MongoJsonMappingException If no MongoCollection annotation is found on the type
// */
// public DBRef(K id, Class<T> type) throws MongoJsonMappingException {
// this.id = id;
// MongoCollection collection = type.getAnnotation(MongoCollection.class);
// if (collection == null) {
// throw new MongoJsonMappingException("Only types that have the @MongoCollection annotation on them can be used with this constructor");
// }
// this.collectionName = collection.name();
// }
//
// /**
// * Get the ID of this object
// *
// * @return The ID of this object
// */
// public K getId() {
// return id;
// }
//
// /**
// * Get the name of the collection this object lives in
// *
// * @return The name of the collection this object lives in
// */
// public String getCollectionName() {
// return collectionName;
// }
//
// /**
// * Fetch the object. Should only be called for references that have been returned by the mapper, will return null
// * otherwise.
// * <p/>
// * Deserialisation is done by the ObjectMapper that fetched the object that this reference belongs to.
// *
// * @return If this DBRef was returned by the mapper, the referenced object, if it exists, or null
// */
// public T fetch() {
// return null;
// }
//
// /**
// * Fetch only the given fields of the object. Should only be called for references that have been returned by the
// * mapper, will return null otherwise.
// * <p/>
// * Deserialisation is done by the ObjectMapper that fetched the object that this reference belongs to.
// * <p/>
// * Unlike the <code>fetch()</code> method, calls to this are not cached.
// *
// * @param fields The fields to fetch
// * @return If this DBRef was returned by the mapper, the referenced object, if it exists, or null
// */
// public T fetch(DBObject fields) {
// return null;
// }
// }
| import net.vz.mongodb.jackson.DBRef;
import org.bson.types.ObjectId;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import java.io.IOException; | /*
* Copyright 2011 VZ Netzwerke Ltd
*
* 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 net.vz.mongodb.jackson.internal;
/**
* Serializer for object ids, serialises strings or byte arrays to an ObjectId class
*
* @author James Roper
* @since 1.0
*/
public class ObjectIdSerializer extends JsonSerializer {
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
if (value instanceof Iterable) {
jgen.writeStartArray();
for (Object item : (Iterable) value) {
jgen.writeObject(serialiseObject(item));
}
jgen.writeEndArray();
} else {
jgen.writeObject(serialiseObject(value));
}
}
private Object serialiseObject(Object value) throws JsonMappingException {
if (value == null) {
return null;
} else if (value instanceof String) {
return new ObjectId((String) value);
} else if (value instanceof byte[]) {
return new ObjectId((byte[]) value); | // Path: src/main/java/net/vz/mongodb/jackson/DBRef.java
// public class DBRef<T, K> {
// private final K id;
// private final String collectionName;
//
// /**
// * Construct a new database reference with the given id and collection name
// *
// * @param id The id of the database reference to construct
// * @param collectionName The name of the collection
// */
// public DBRef(K id, String collectionName) {
// this.id = id;
// this.collectionName = collectionName;
// }
//
// /**
// * Construct a new database reference with the given id and type. The type must be annotated with
// * {@link MongoCollection}, so that the name can be worked out.
// *
// * @param id The id of the database reference to construct
// * @param type The type of the object
// * @throws MongoJsonMappingException If no MongoCollection annotation is found on the type
// */
// public DBRef(K id, Class<T> type) throws MongoJsonMappingException {
// this.id = id;
// MongoCollection collection = type.getAnnotation(MongoCollection.class);
// if (collection == null) {
// throw new MongoJsonMappingException("Only types that have the @MongoCollection annotation on them can be used with this constructor");
// }
// this.collectionName = collection.name();
// }
//
// /**
// * Get the ID of this object
// *
// * @return The ID of this object
// */
// public K getId() {
// return id;
// }
//
// /**
// * Get the name of the collection this object lives in
// *
// * @return The name of the collection this object lives in
// */
// public String getCollectionName() {
// return collectionName;
// }
//
// /**
// * Fetch the object. Should only be called for references that have been returned by the mapper, will return null
// * otherwise.
// * <p/>
// * Deserialisation is done by the ObjectMapper that fetched the object that this reference belongs to.
// *
// * @return If this DBRef was returned by the mapper, the referenced object, if it exists, or null
// */
// public T fetch() {
// return null;
// }
//
// /**
// * Fetch only the given fields of the object. Should only be called for references that have been returned by the
// * mapper, will return null otherwise.
// * <p/>
// * Deserialisation is done by the ObjectMapper that fetched the object that this reference belongs to.
// * <p/>
// * Unlike the <code>fetch()</code> method, calls to this are not cached.
// *
// * @param fields The fields to fetch
// * @return If this DBRef was returned by the mapper, the referenced object, if it exists, or null
// */
// public T fetch(DBObject fields) {
// return null;
// }
// }
// Path: src/main/java/net/vz/mongodb/jackson/internal/ObjectIdSerializer.java
import net.vz.mongodb.jackson.DBRef;
import org.bson.types.ObjectId;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import java.io.IOException;
/*
* Copyright 2011 VZ Netzwerke Ltd
*
* 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 net.vz.mongodb.jackson.internal;
/**
* Serializer for object ids, serialises strings or byte arrays to an ObjectId class
*
* @author James Roper
* @since 1.0
*/
public class ObjectIdSerializer extends JsonSerializer {
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
if (value instanceof Iterable) {
jgen.writeStartArray();
for (Object item : (Iterable) value) {
jgen.writeObject(serialiseObject(item));
}
jgen.writeEndArray();
} else {
jgen.writeObject(serialiseObject(value));
}
}
private Object serialiseObject(Object value) throws JsonMappingException {
if (value == null) {
return null;
} else if (value instanceof String) {
return new ObjectId((String) value);
} else if (value instanceof byte[]) {
return new ObjectId((byte[]) value); | } else if (value instanceof DBRef) { |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/master/text/MessageTextItem.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/TextMessage.java
// public class TextMessage extends Message {
// private String text;
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context){
// if (this.source == MessageSource.EXTERNAL_USER)
// return new MessageExternalUserTextItem(this, context);
// else
// return new MessageInternalUserTextItem(this, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/utils/DateUtils.java
// public class DateUtils {
//
// public static String getTimestamp(Context context, long then) {
// long now = System.currentTimeMillis();
//
// // convert to seconds
// long nowSeconds = now / 1000;
// long thenSeconds = then / 1000;
//
// int minutesAgo = ((int) (nowSeconds - thenSeconds)) / (60);
// if (minutesAgo < 1)
// return context.getString(R.string.date_now);
// else if (minutesAgo == 1)
// return context.getString(R.string.date_a_minute_ago);
// else if (minutesAgo < 60)
// return minutesAgo + " " + context.getString(R.string.date_minutes_ago);
//
// // convert to minutes
// long nowMinutes = nowSeconds / 60;
// long thenMinutes = thenSeconds / 60;
//
// int hoursAgo = (int) (nowMinutes - thenMinutes) / 60;
// int thenDayOfMonth = getDayOfMonth(then);
// int nowDayOfMonth = getDayOfMonth(now);
// if (hoursAgo < 7 && thenDayOfMonth == nowDayOfMonth) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
// return simpleDateFormat.format(date);
// }
//
// // convert to hours
// long nowHours = nowMinutes / 60;
// long thenHours = thenMinutes / 60;
//
// int daysAgo = (int) (nowHours - thenHours) / 24;
// if (daysAgo == 1) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
// String yesterdayString = context.getString(R.string.date_yesterday);
// return yesterdayString + " " + simpleDateFormat.format(date);
// } else if (daysAgo < 7) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE h:mm a");
// return simpleDateFormat.format(date);
// }
//
// int thenYear = getYear(then);
// int nowYear = getYear(now);
// if (thenYear == nowYear) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d, h:mm a");
// return simpleDateFormat.format(date);
// } else {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d, h:mm a");
// return simpleDateFormat.format(date);
// }
// }
//
// private static int getDayOfMonth(long time) {
// Date date = new Date(time);
// SimpleDateFormat simpleDateFormate = new SimpleDateFormat("d");
// return Integer.parseInt(simpleDateFormate.format(date));
// }
//
// private static int getYear(long time) {
// Date date = new Date(time);
// SimpleDateFormat simpleDateFormate = new SimpleDateFormat("yyyy");
// return Integer.parseInt(simpleDateFormate.format(date));
// }
//
// public static boolean dateNeedsUpdated(Context context, long time, String date) {
// return date == null || date.equals(getTimestamp(context, time));
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
| import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import it.slyce.messaging.R;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.TextMessage;
import it.slyce.messaging.utils.DateUtils;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder; | package it.slyce.messaging.message.messageItem.master.text;
/**
* Created by matthewpage on 6/27/16.
*/
public class MessageTextItem extends MessageItem {
private Context context;
private String avatarUrl;
| // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/TextMessage.java
// public class TextMessage extends Message {
// private String text;
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context){
// if (this.source == MessageSource.EXTERNAL_USER)
// return new MessageExternalUserTextItem(this, context);
// else
// return new MessageInternalUserTextItem(this, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/utils/DateUtils.java
// public class DateUtils {
//
// public static String getTimestamp(Context context, long then) {
// long now = System.currentTimeMillis();
//
// // convert to seconds
// long nowSeconds = now / 1000;
// long thenSeconds = then / 1000;
//
// int minutesAgo = ((int) (nowSeconds - thenSeconds)) / (60);
// if (minutesAgo < 1)
// return context.getString(R.string.date_now);
// else if (minutesAgo == 1)
// return context.getString(R.string.date_a_minute_ago);
// else if (minutesAgo < 60)
// return minutesAgo + " " + context.getString(R.string.date_minutes_ago);
//
// // convert to minutes
// long nowMinutes = nowSeconds / 60;
// long thenMinutes = thenSeconds / 60;
//
// int hoursAgo = (int) (nowMinutes - thenMinutes) / 60;
// int thenDayOfMonth = getDayOfMonth(then);
// int nowDayOfMonth = getDayOfMonth(now);
// if (hoursAgo < 7 && thenDayOfMonth == nowDayOfMonth) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
// return simpleDateFormat.format(date);
// }
//
// // convert to hours
// long nowHours = nowMinutes / 60;
// long thenHours = thenMinutes / 60;
//
// int daysAgo = (int) (nowHours - thenHours) / 24;
// if (daysAgo == 1) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
// String yesterdayString = context.getString(R.string.date_yesterday);
// return yesterdayString + " " + simpleDateFormat.format(date);
// } else if (daysAgo < 7) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE h:mm a");
// return simpleDateFormat.format(date);
// }
//
// int thenYear = getYear(then);
// int nowYear = getYear(now);
// if (thenYear == nowYear) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d, h:mm a");
// return simpleDateFormat.format(date);
// } else {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d, h:mm a");
// return simpleDateFormat.format(date);
// }
// }
//
// private static int getDayOfMonth(long time) {
// Date date = new Date(time);
// SimpleDateFormat simpleDateFormate = new SimpleDateFormat("d");
// return Integer.parseInt(simpleDateFormate.format(date));
// }
//
// private static int getYear(long time) {
// Date date = new Date(time);
// SimpleDateFormat simpleDateFormate = new SimpleDateFormat("yyyy");
// return Integer.parseInt(simpleDateFormate.format(date));
// }
//
// public static boolean dateNeedsUpdated(Context context, long time, String date) {
// return date == null || date.equals(getTimestamp(context, time));
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/master/text/MessageTextItem.java
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import it.slyce.messaging.R;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.TextMessage;
import it.slyce.messaging.utils.DateUtils;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder;
package it.slyce.messaging.message.messageItem.master.text;
/**
* Created by matthewpage on 6/27/16.
*/
public class MessageTextItem extends MessageItem {
private Context context;
private String avatarUrl;
| public MessageTextItem(TextMessage textMessage, Context context) { |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/master/text/MessageTextItem.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/TextMessage.java
// public class TextMessage extends Message {
// private String text;
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context){
// if (this.source == MessageSource.EXTERNAL_USER)
// return new MessageExternalUserTextItem(this, context);
// else
// return new MessageInternalUserTextItem(this, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/utils/DateUtils.java
// public class DateUtils {
//
// public static String getTimestamp(Context context, long then) {
// long now = System.currentTimeMillis();
//
// // convert to seconds
// long nowSeconds = now / 1000;
// long thenSeconds = then / 1000;
//
// int minutesAgo = ((int) (nowSeconds - thenSeconds)) / (60);
// if (minutesAgo < 1)
// return context.getString(R.string.date_now);
// else if (minutesAgo == 1)
// return context.getString(R.string.date_a_minute_ago);
// else if (minutesAgo < 60)
// return minutesAgo + " " + context.getString(R.string.date_minutes_ago);
//
// // convert to minutes
// long nowMinutes = nowSeconds / 60;
// long thenMinutes = thenSeconds / 60;
//
// int hoursAgo = (int) (nowMinutes - thenMinutes) / 60;
// int thenDayOfMonth = getDayOfMonth(then);
// int nowDayOfMonth = getDayOfMonth(now);
// if (hoursAgo < 7 && thenDayOfMonth == nowDayOfMonth) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
// return simpleDateFormat.format(date);
// }
//
// // convert to hours
// long nowHours = nowMinutes / 60;
// long thenHours = thenMinutes / 60;
//
// int daysAgo = (int) (nowHours - thenHours) / 24;
// if (daysAgo == 1) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
// String yesterdayString = context.getString(R.string.date_yesterday);
// return yesterdayString + " " + simpleDateFormat.format(date);
// } else if (daysAgo < 7) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE h:mm a");
// return simpleDateFormat.format(date);
// }
//
// int thenYear = getYear(then);
// int nowYear = getYear(now);
// if (thenYear == nowYear) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d, h:mm a");
// return simpleDateFormat.format(date);
// } else {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d, h:mm a");
// return simpleDateFormat.format(date);
// }
// }
//
// private static int getDayOfMonth(long time) {
// Date date = new Date(time);
// SimpleDateFormat simpleDateFormate = new SimpleDateFormat("d");
// return Integer.parseInt(simpleDateFormate.format(date));
// }
//
// private static int getYear(long time) {
// Date date = new Date(time);
// SimpleDateFormat simpleDateFormate = new SimpleDateFormat("yyyy");
// return Integer.parseInt(simpleDateFormate.format(date));
// }
//
// public static boolean dateNeedsUpdated(Context context, long time, String date) {
// return date == null || date.equals(getTimestamp(context, time));
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
| import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import it.slyce.messaging.R;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.TextMessage;
import it.slyce.messaging.utils.DateUtils;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder; | package it.slyce.messaging.message.messageItem.master.text;
/**
* Created by matthewpage on 6/27/16.
*/
public class MessageTextItem extends MessageItem {
private Context context;
private String avatarUrl;
public MessageTextItem(TextMessage textMessage, Context context) {
super(textMessage);
this.context = context;
}
@Override
public void buildMessageItem( | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/TextMessage.java
// public class TextMessage extends Message {
// private String text;
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context){
// if (this.source == MessageSource.EXTERNAL_USER)
// return new MessageExternalUserTextItem(this, context);
// else
// return new MessageInternalUserTextItem(this, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/utils/DateUtils.java
// public class DateUtils {
//
// public static String getTimestamp(Context context, long then) {
// long now = System.currentTimeMillis();
//
// // convert to seconds
// long nowSeconds = now / 1000;
// long thenSeconds = then / 1000;
//
// int minutesAgo = ((int) (nowSeconds - thenSeconds)) / (60);
// if (minutesAgo < 1)
// return context.getString(R.string.date_now);
// else if (minutesAgo == 1)
// return context.getString(R.string.date_a_minute_ago);
// else if (minutesAgo < 60)
// return minutesAgo + " " + context.getString(R.string.date_minutes_ago);
//
// // convert to minutes
// long nowMinutes = nowSeconds / 60;
// long thenMinutes = thenSeconds / 60;
//
// int hoursAgo = (int) (nowMinutes - thenMinutes) / 60;
// int thenDayOfMonth = getDayOfMonth(then);
// int nowDayOfMonth = getDayOfMonth(now);
// if (hoursAgo < 7 && thenDayOfMonth == nowDayOfMonth) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
// return simpleDateFormat.format(date);
// }
//
// // convert to hours
// long nowHours = nowMinutes / 60;
// long thenHours = thenMinutes / 60;
//
// int daysAgo = (int) (nowHours - thenHours) / 24;
// if (daysAgo == 1) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
// String yesterdayString = context.getString(R.string.date_yesterday);
// return yesterdayString + " " + simpleDateFormat.format(date);
// } else if (daysAgo < 7) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE h:mm a");
// return simpleDateFormat.format(date);
// }
//
// int thenYear = getYear(then);
// int nowYear = getYear(now);
// if (thenYear == nowYear) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d, h:mm a");
// return simpleDateFormat.format(date);
// } else {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d, h:mm a");
// return simpleDateFormat.format(date);
// }
// }
//
// private static int getDayOfMonth(long time) {
// Date date = new Date(time);
// SimpleDateFormat simpleDateFormate = new SimpleDateFormat("d");
// return Integer.parseInt(simpleDateFormate.format(date));
// }
//
// private static int getYear(long time) {
// Date date = new Date(time);
// SimpleDateFormat simpleDateFormate = new SimpleDateFormat("yyyy");
// return Integer.parseInt(simpleDateFormate.format(date));
// }
//
// public static boolean dateNeedsUpdated(Context context, long time, String date) {
// return date == null || date.equals(getTimestamp(context, time));
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/master/text/MessageTextItem.java
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import it.slyce.messaging.R;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.TextMessage;
import it.slyce.messaging.utils.DateUtils;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder;
package it.slyce.messaging.message.messageItem.master.text;
/**
* Created by matthewpage on 6/27/16.
*/
public class MessageTextItem extends MessageItem {
private Context context;
private String avatarUrl;
public MessageTextItem(TextMessage textMessage, Context context) {
super(textMessage);
this.context = context;
}
@Override
public void buildMessageItem( | MessageViewHolder messageViewHolder) { |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/master/text/MessageTextItem.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/TextMessage.java
// public class TextMessage extends Message {
// private String text;
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context){
// if (this.source == MessageSource.EXTERNAL_USER)
// return new MessageExternalUserTextItem(this, context);
// else
// return new MessageInternalUserTextItem(this, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/utils/DateUtils.java
// public class DateUtils {
//
// public static String getTimestamp(Context context, long then) {
// long now = System.currentTimeMillis();
//
// // convert to seconds
// long nowSeconds = now / 1000;
// long thenSeconds = then / 1000;
//
// int minutesAgo = ((int) (nowSeconds - thenSeconds)) / (60);
// if (minutesAgo < 1)
// return context.getString(R.string.date_now);
// else if (minutesAgo == 1)
// return context.getString(R.string.date_a_minute_ago);
// else if (minutesAgo < 60)
// return minutesAgo + " " + context.getString(R.string.date_minutes_ago);
//
// // convert to minutes
// long nowMinutes = nowSeconds / 60;
// long thenMinutes = thenSeconds / 60;
//
// int hoursAgo = (int) (nowMinutes - thenMinutes) / 60;
// int thenDayOfMonth = getDayOfMonth(then);
// int nowDayOfMonth = getDayOfMonth(now);
// if (hoursAgo < 7 && thenDayOfMonth == nowDayOfMonth) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
// return simpleDateFormat.format(date);
// }
//
// // convert to hours
// long nowHours = nowMinutes / 60;
// long thenHours = thenMinutes / 60;
//
// int daysAgo = (int) (nowHours - thenHours) / 24;
// if (daysAgo == 1) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
// String yesterdayString = context.getString(R.string.date_yesterday);
// return yesterdayString + " " + simpleDateFormat.format(date);
// } else if (daysAgo < 7) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE h:mm a");
// return simpleDateFormat.format(date);
// }
//
// int thenYear = getYear(then);
// int nowYear = getYear(now);
// if (thenYear == nowYear) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d, h:mm a");
// return simpleDateFormat.format(date);
// } else {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d, h:mm a");
// return simpleDateFormat.format(date);
// }
// }
//
// private static int getDayOfMonth(long time) {
// Date date = new Date(time);
// SimpleDateFormat simpleDateFormate = new SimpleDateFormat("d");
// return Integer.parseInt(simpleDateFormate.format(date));
// }
//
// private static int getYear(long time) {
// Date date = new Date(time);
// SimpleDateFormat simpleDateFormate = new SimpleDateFormat("yyyy");
// return Integer.parseInt(simpleDateFormate.format(date));
// }
//
// public static boolean dateNeedsUpdated(Context context, long time, String date) {
// return date == null || date.equals(getTimestamp(context, time));
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
| import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import it.slyce.messaging.R;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.TextMessage;
import it.slyce.messaging.utils.DateUtils;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder; | package it.slyce.messaging.message.messageItem.master.text;
/**
* Created by matthewpage on 6/27/16.
*/
public class MessageTextItem extends MessageItem {
private Context context;
private String avatarUrl;
public MessageTextItem(TextMessage textMessage, Context context) {
super(textMessage);
this.context = context;
}
@Override
public void buildMessageItem(
MessageViewHolder messageViewHolder) {
if (message != null && messageViewHolder != null && messageViewHolder instanceof MessageTextViewHolder) {
final MessageTextViewHolder messageTextViewHolder = (MessageTextViewHolder) messageViewHolder;
// Get content | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/TextMessage.java
// public class TextMessage extends Message {
// private String text;
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context){
// if (this.source == MessageSource.EXTERNAL_USER)
// return new MessageExternalUserTextItem(this, context);
// else
// return new MessageInternalUserTextItem(this, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/utils/DateUtils.java
// public class DateUtils {
//
// public static String getTimestamp(Context context, long then) {
// long now = System.currentTimeMillis();
//
// // convert to seconds
// long nowSeconds = now / 1000;
// long thenSeconds = then / 1000;
//
// int minutesAgo = ((int) (nowSeconds - thenSeconds)) / (60);
// if (minutesAgo < 1)
// return context.getString(R.string.date_now);
// else if (minutesAgo == 1)
// return context.getString(R.string.date_a_minute_ago);
// else if (minutesAgo < 60)
// return minutesAgo + " " + context.getString(R.string.date_minutes_ago);
//
// // convert to minutes
// long nowMinutes = nowSeconds / 60;
// long thenMinutes = thenSeconds / 60;
//
// int hoursAgo = (int) (nowMinutes - thenMinutes) / 60;
// int thenDayOfMonth = getDayOfMonth(then);
// int nowDayOfMonth = getDayOfMonth(now);
// if (hoursAgo < 7 && thenDayOfMonth == nowDayOfMonth) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
// return simpleDateFormat.format(date);
// }
//
// // convert to hours
// long nowHours = nowMinutes / 60;
// long thenHours = thenMinutes / 60;
//
// int daysAgo = (int) (nowHours - thenHours) / 24;
// if (daysAgo == 1) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
// String yesterdayString = context.getString(R.string.date_yesterday);
// return yesterdayString + " " + simpleDateFormat.format(date);
// } else if (daysAgo < 7) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE h:mm a");
// return simpleDateFormat.format(date);
// }
//
// int thenYear = getYear(then);
// int nowYear = getYear(now);
// if (thenYear == nowYear) {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d, h:mm a");
// return simpleDateFormat.format(date);
// } else {
// Date date = new Date(then);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d, h:mm a");
// return simpleDateFormat.format(date);
// }
// }
//
// private static int getDayOfMonth(long time) {
// Date date = new Date(time);
// SimpleDateFormat simpleDateFormate = new SimpleDateFormat("d");
// return Integer.parseInt(simpleDateFormate.format(date));
// }
//
// private static int getYear(long time) {
// Date date = new Date(time);
// SimpleDateFormat simpleDateFormate = new SimpleDateFormat("yyyy");
// return Integer.parseInt(simpleDateFormate.format(date));
// }
//
// public static boolean dateNeedsUpdated(Context context, long time, String date) {
// return date == null || date.equals(getTimestamp(context, time));
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/master/text/MessageTextItem.java
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import it.slyce.messaging.R;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.TextMessage;
import it.slyce.messaging.utils.DateUtils;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder;
package it.slyce.messaging.message.messageItem.master.text;
/**
* Created by matthewpage on 6/27/16.
*/
public class MessageTextItem extends MessageItem {
private Context context;
private String avatarUrl;
public MessageTextItem(TextMessage textMessage, Context context) {
super(textMessage);
this.context = context;
}
@Override
public void buildMessageItem(
MessageViewHolder messageViewHolder) {
if (message != null && messageViewHolder != null && messageViewHolder instanceof MessageTextViewHolder) {
final MessageTextViewHolder messageTextViewHolder = (MessageTextViewHolder) messageViewHolder;
// Get content | String date = DateUtils.getTimestamp(context, message.getDate()); |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/main/java/it/slyce/messaging/message/TextMessage.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/internalUser/text/MessageInternalUserTextItem.java
// public class MessageInternalUserTextItem extends MessageTextItem {
//
// public MessageInternalUserTextItem(TextMessage messageText, Context context) {
// super(messageText, context);
// }
// }
| import android.content.Context;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.externalUser.text.MessageExternalUserTextItem;
import it.slyce.messaging.message.messageItem.internalUser.text.MessageInternalUserTextItem; | package it.slyce.messaging.message;
/**
* Created by matthewpage on 6/21/16.
*/
public class TextMessage extends Message {
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public MessageItem toMessageItem(Context context){
if (this.source == MessageSource.EXTERNAL_USER)
return new MessageExternalUserTextItem(this, context);
else | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/internalUser/text/MessageInternalUserTextItem.java
// public class MessageInternalUserTextItem extends MessageTextItem {
//
// public MessageInternalUserTextItem(TextMessage messageText, Context context) {
// super(messageText, context);
// }
// }
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/TextMessage.java
import android.content.Context;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.externalUser.text.MessageExternalUserTextItem;
import it.slyce.messaging.message.messageItem.internalUser.text.MessageInternalUserTextItem;
package it.slyce.messaging.message;
/**
* Created by matthewpage on 6/21/16.
*/
public class TextMessage extends Message {
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public MessageItem toMessageItem(Context context){
if (this.source == MessageSource.EXTERNAL_USER)
return new MessageExternalUserTextItem(this, context);
else | return new MessageInternalUserTextItem(this, context); |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/main/java/it/slyce/messaging/utils/MessageUtils.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
| import java.util.List;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType; |
private static boolean previousMessageIsFromAnotherSender(int i, List<MessageItem> messageItems) {
return messageItems.get(i - 1).getMessageSource() != messageItems.get(i).getMessageSource();
}
private static boolean previousMessageIsSpinner(int i, List<MessageItem> messageItems) {
return isSpinnerMessage(i - 1, messageItems);
}
private static boolean isTheLastConsecutiveMessageFromSource(int i, List<MessageItem> messageItems) {
if (isSpinnerMessage(i, messageItems)) {
return false;
}
return i == messageItems.size() - 1 ||
nextMessageHasDifferentSource(i, messageItems) ||
messageItems.get(i).getMessage() == null ||
messageItems.get(i + 1).getMessage() == null ||
nextMessageWasAtLeastAnHourAfterThisOne(i, messageItems);
}
private static boolean nextMessageWasAtLeastAnHourAfterThisOne(int i, List<MessageItem> messageItems) {
return messageItems.get(i + 1).getMessage().getDate() - messageItems.get(i).getMessage().getDate() > 1000 * 60 * 60; // one hour
}
private static boolean nextMessageHasDifferentSource(int i, List<MessageItem> messageItems) {
return messageItems.get(i).getMessageSource() != messageItems.get(i + 1).getMessageSource();
}
private static boolean isSpinnerMessage(int i, List<MessageItem> messageItems) { | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
// Path: slyce-messaging/src/main/java/it/slyce/messaging/utils/MessageUtils.java
import java.util.List;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
private static boolean previousMessageIsFromAnotherSender(int i, List<MessageItem> messageItems) {
return messageItems.get(i - 1).getMessageSource() != messageItems.get(i).getMessageSource();
}
private static boolean previousMessageIsSpinner(int i, List<MessageItem> messageItems) {
return isSpinnerMessage(i - 1, messageItems);
}
private static boolean isTheLastConsecutiveMessageFromSource(int i, List<MessageItem> messageItems) {
if (isSpinnerMessage(i, messageItems)) {
return false;
}
return i == messageItems.size() - 1 ||
nextMessageHasDifferentSource(i, messageItems) ||
messageItems.get(i).getMessage() == null ||
messageItems.get(i + 1).getMessage() == null ||
nextMessageWasAtLeastAnHourAfterThisOne(i, messageItems);
}
private static boolean nextMessageWasAtLeastAnHourAfterThisOne(int i, List<MessageItem> messageItems) {
return messageItems.get(i + 1).getMessage().getDate() - messageItems.get(i).getMessage().getDate() > 1000 * 60 * 60; // one hour
}
private static boolean nextMessageHasDifferentSource(int i, List<MessageItem> messageItems) {
return messageItems.get(i).getMessageSource() != messageItems.get(i + 1).getMessageSource();
}
private static boolean isSpinnerMessage(int i, List<MessageItem> messageItems) { | return messageItems.get(i).getMessageItemType() == MessageItemType.SPINNER; |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/main/java/it/slyce/messaging/message/MediaMessage.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/externalUser/media/MessageExternalUserMediaItem.java
// public class MessageExternalUserMediaItem extends MessageMediaItem {
//
// public MessageExternalUserMediaItem(MediaMessage messageMedia, Context context) {
// super(messageMedia, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/internalUser/media/MessageInternalUserMediaItem.java
// public class MessageInternalUserMediaItem extends MessageMediaItem {
//
// public MessageInternalUserMediaItem(MediaMessage messageMedia, Context context) {
// super(messageMedia, context);
// }
// }
| import android.content.Context;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.externalUser.media.MessageExternalUserMediaItem;
import it.slyce.messaging.message.messageItem.internalUser.media.MessageInternalUserMediaItem; | package it.slyce.messaging.message;
/**
* Created by matthewpage on 6/21/16.
*/
public class MediaMessage extends Message {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public MessageItem toMessageItem(Context context){
if (this.source == MessageSource.EXTERNAL_USER) | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/externalUser/media/MessageExternalUserMediaItem.java
// public class MessageExternalUserMediaItem extends MessageMediaItem {
//
// public MessageExternalUserMediaItem(MediaMessage messageMedia, Context context) {
// super(messageMedia, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/internalUser/media/MessageInternalUserMediaItem.java
// public class MessageInternalUserMediaItem extends MessageMediaItem {
//
// public MessageInternalUserMediaItem(MediaMessage messageMedia, Context context) {
// super(messageMedia, context);
// }
// }
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MediaMessage.java
import android.content.Context;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.externalUser.media.MessageExternalUserMediaItem;
import it.slyce.messaging.message.messageItem.internalUser.media.MessageInternalUserMediaItem;
package it.slyce.messaging.message;
/**
* Created by matthewpage on 6/21/16.
*/
public class MediaMessage extends Message {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public MessageItem toMessageItem(Context context){
if (this.source == MessageSource.EXTERNAL_USER) | return new MessageExternalUserMediaItem(this, context); |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/main/java/it/slyce/messaging/message/MediaMessage.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/externalUser/media/MessageExternalUserMediaItem.java
// public class MessageExternalUserMediaItem extends MessageMediaItem {
//
// public MessageExternalUserMediaItem(MediaMessage messageMedia, Context context) {
// super(messageMedia, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/internalUser/media/MessageInternalUserMediaItem.java
// public class MessageInternalUserMediaItem extends MessageMediaItem {
//
// public MessageInternalUserMediaItem(MediaMessage messageMedia, Context context) {
// super(messageMedia, context);
// }
// }
| import android.content.Context;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.externalUser.media.MessageExternalUserMediaItem;
import it.slyce.messaging.message.messageItem.internalUser.media.MessageInternalUserMediaItem; | package it.slyce.messaging.message;
/**
* Created by matthewpage on 6/21/16.
*/
public class MediaMessage extends Message {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public MessageItem toMessageItem(Context context){
if (this.source == MessageSource.EXTERNAL_USER)
return new MessageExternalUserMediaItem(this, context);
else | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/externalUser/media/MessageExternalUserMediaItem.java
// public class MessageExternalUserMediaItem extends MessageMediaItem {
//
// public MessageExternalUserMediaItem(MediaMessage messageMedia, Context context) {
// super(messageMedia, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/internalUser/media/MessageInternalUserMediaItem.java
// public class MessageInternalUserMediaItem extends MessageMediaItem {
//
// public MessageInternalUserMediaItem(MediaMessage messageMedia, Context context) {
// super(messageMedia, context);
// }
// }
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MediaMessage.java
import android.content.Context;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.externalUser.media.MessageExternalUserMediaItem;
import it.slyce.messaging.message.messageItem.internalUser.media.MessageInternalUserMediaItem;
package it.slyce.messaging.message;
/**
* Created by matthewpage on 6/21/16.
*/
public class MediaMessage extends Message {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public MessageItem toMessageItem(Context context){
if (this.source == MessageSource.EXTERNAL_USER)
return new MessageExternalUserMediaItem(this, context);
else | return new MessageInternalUserMediaItem(this, context); |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/master/text/MessageTextViewHolder.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/utils/CustomSettings.java
// public class CustomSettings {
// public int backgroudColor;
// public int timestampColor;
// public int localBubbleBackgroundColor;
// public int localBubbleTextColor;
// public int externalBubbleBackgroundColor;
// public int externalBubbleTextColor;
// public int snackbarBackground;
// public int snackbarTitleColor;
// public int snackbarButtonColor;
//
// public UserClicksAvatarPictureListener userClicksAvatarPictureListener;
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
| import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import it.slyce.messaging.utils.CustomSettings;
import it.slyce.messaging.message.messageItem.MessageViewHolder; | package it.slyce.messaging.message.messageItem.master.text;
/**
* Created by matthewpage on 6/27/16.
*/
public abstract class MessageTextViewHolder extends MessageViewHolder {
public ImageView carrot;
public TextView text;
public FrameLayout bubble;
| // Path: slyce-messaging/src/main/java/it/slyce/messaging/utils/CustomSettings.java
// public class CustomSettings {
// public int backgroudColor;
// public int timestampColor;
// public int localBubbleBackgroundColor;
// public int localBubbleTextColor;
// public int externalBubbleBackgroundColor;
// public int externalBubbleTextColor;
// public int snackbarBackground;
// public int snackbarTitleColor;
// public int snackbarButtonColor;
//
// public UserClicksAvatarPictureListener userClicksAvatarPictureListener;
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/master/text/MessageTextViewHolder.java
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import it.slyce.messaging.utils.CustomSettings;
import it.slyce.messaging.message.messageItem.MessageViewHolder;
package it.slyce.messaging.message.messageItem.master.text;
/**
* Created by matthewpage on 6/27/16.
*/
public abstract class MessageTextViewHolder extends MessageViewHolder {
public ImageView carrot;
public TextView text;
public FrameLayout bubble;
| public MessageTextViewHolder(View itemView, CustomSettings customSettings) { |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/general/generalText/MessageGeneralTextItem.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/GeneralTextMessage.java
// public class GeneralTextMessage extends Message {
// private String text;
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getText() {
// return this.text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context) {
// return new MessageGeneralTextItem(this);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
| import it.slyce.messaging.message.GeneralTextMessage;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder; | package it.slyce.messaging.message.messageItem.general.generalText;
public class MessageGeneralTextItem extends MessageItem {
public MessageGeneralTextItem(GeneralTextMessage message) {
super(message);
}
@Override
public void buildMessageItem( | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/GeneralTextMessage.java
// public class GeneralTextMessage extends Message {
// private String text;
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getText() {
// return this.text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context) {
// return new MessageGeneralTextItem(this);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/general/generalText/MessageGeneralTextItem.java
import it.slyce.messaging.message.GeneralTextMessage;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder;
package it.slyce.messaging.message.messageItem.general.generalText;
public class MessageGeneralTextItem extends MessageItem {
public MessageGeneralTextItem(GeneralTextMessage message) {
super(message);
}
@Override
public void buildMessageItem( | MessageViewHolder messageViewHolder) { |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/general/generalText/MessageGeneralTextItem.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/GeneralTextMessage.java
// public class GeneralTextMessage extends Message {
// private String text;
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getText() {
// return this.text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context) {
// return new MessageGeneralTextItem(this);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
| import it.slyce.messaging.message.GeneralTextMessage;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder; | package it.slyce.messaging.message.messageItem.general.generalText;
public class MessageGeneralTextItem extends MessageItem {
public MessageGeneralTextItem(GeneralTextMessage message) {
super(message);
}
@Override
public void buildMessageItem(
MessageViewHolder messageViewHolder) {
MessageGeneralTextViewHolder viewHolder = (MessageGeneralTextViewHolder) messageViewHolder;
GeneralTextMessage generalTextMessage = (GeneralTextMessage) message;
viewHolder.messageTextView.setText(generalTextMessage.getText());
}
@Override | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/GeneralTextMessage.java
// public class GeneralTextMessage extends Message {
// private String text;
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getText() {
// return this.text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context) {
// return new MessageGeneralTextItem(this);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/general/generalText/MessageGeneralTextItem.java
import it.slyce.messaging.message.GeneralTextMessage;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder;
package it.slyce.messaging.message.messageItem.general.generalText;
public class MessageGeneralTextItem extends MessageItem {
public MessageGeneralTextItem(GeneralTextMessage message) {
super(message);
}
@Override
public void buildMessageItem(
MessageViewHolder messageViewHolder) {
MessageGeneralTextViewHolder viewHolder = (MessageGeneralTextViewHolder) messageViewHolder;
GeneralTextMessage generalTextMessage = (GeneralTextMessage) message;
viewHolder.messageTextView.setText(generalTextMessage.getText());
}
@Override | public MessageItemType getMessageItemType() { |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/general/generalText/MessageGeneralTextItem.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/GeneralTextMessage.java
// public class GeneralTextMessage extends Message {
// private String text;
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getText() {
// return this.text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context) {
// return new MessageGeneralTextItem(this);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
| import it.slyce.messaging.message.GeneralTextMessage;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder; | package it.slyce.messaging.message.messageItem.general.generalText;
public class MessageGeneralTextItem extends MessageItem {
public MessageGeneralTextItem(GeneralTextMessage message) {
super(message);
}
@Override
public void buildMessageItem(
MessageViewHolder messageViewHolder) {
MessageGeneralTextViewHolder viewHolder = (MessageGeneralTextViewHolder) messageViewHolder;
GeneralTextMessage generalTextMessage = (GeneralTextMessage) message;
viewHolder.messageTextView.setText(generalTextMessage.getText());
}
@Override
public MessageItemType getMessageItemType() {
return MessageItemType.GENERAL_TEXT;
}
@Override | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/GeneralTextMessage.java
// public class GeneralTextMessage extends Message {
// private String text;
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getText() {
// return this.text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context) {
// return new MessageGeneralTextItem(this);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/general/generalText/MessageGeneralTextItem.java
import it.slyce.messaging.message.GeneralTextMessage;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder;
package it.slyce.messaging.message.messageItem.general.generalText;
public class MessageGeneralTextItem extends MessageItem {
public MessageGeneralTextItem(GeneralTextMessage message) {
super(message);
}
@Override
public void buildMessageItem(
MessageViewHolder messageViewHolder) {
MessageGeneralTextViewHolder viewHolder = (MessageGeneralTextViewHolder) messageViewHolder;
GeneralTextMessage generalTextMessage = (GeneralTextMessage) message;
viewHolder.messageTextView.setText(generalTextMessage.getText());
}
@Override
public MessageItemType getMessageItemType() {
return MessageItemType.GENERAL_TEXT;
}
@Override | public MessageSource getMessageSource() { |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/spinner/SpinnerItem.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
| import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder; | package it.slyce.messaging.message.messageItem.spinner;
/**
* Created by matthewpage on 7/5/16.
*/
public class SpinnerItem extends MessageItem {
public SpinnerItem() {
super(null);
}
@Override | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/spinner/SpinnerItem.java
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder;
package it.slyce.messaging.message.messageItem.spinner;
/**
* Created by matthewpage on 7/5/16.
*/
public class SpinnerItem extends MessageItem {
public SpinnerItem() {
super(null);
}
@Override | public void buildMessageItem(MessageViewHolder messageViewHolder) { |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/spinner/SpinnerItem.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
| import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder; | package it.slyce.messaging.message.messageItem.spinner;
/**
* Created by matthewpage on 7/5/16.
*/
public class SpinnerItem extends MessageItem {
public SpinnerItem() {
super(null);
}
@Override
public void buildMessageItem(MessageViewHolder messageViewHolder) {
}
@Override | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/spinner/SpinnerItem.java
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder;
package it.slyce.messaging.message.messageItem.spinner;
/**
* Created by matthewpage on 7/5/16.
*/
public class SpinnerItem extends MessageItem {
public SpinnerItem() {
super(null);
}
@Override
public void buildMessageItem(MessageViewHolder messageViewHolder) {
}
@Override | public MessageItemType getMessageItemType() { |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/spinner/SpinnerItem.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
| import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder; | package it.slyce.messaging.message.messageItem.spinner;
/**
* Created by matthewpage on 7/5/16.
*/
public class SpinnerItem extends MessageItem {
public SpinnerItem() {
super(null);
}
@Override
public void buildMessageItem(MessageViewHolder messageViewHolder) {
}
@Override
public MessageItemType getMessageItemType() {
return MessageItemType.SPINNER;
}
@Override | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageItemType.java
// public enum MessageItemType {
// INCOMING_MEDIA,
// INCOMING_TEXT,
// OUTGOING_MEDIA,
// OUTGOING_TEXT,
// SPINNER,
// GENERAL_TEXT,
// GENERAL_OPTIONS;
//
// public static final MessageItemType values[] = values();
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/MessageViewHolder.java
// public class MessageViewHolder extends RecyclerView.ViewHolder {
// public ImageView avatar;
// public TextView initials;
// public TextView timestamp;
// public ViewGroup avatarContainer;
// public CustomSettings customSettings;
//
// public MessageViewHolder(View itemView, CustomSettings customSettings) {
// super(itemView);
// this.customSettings = customSettings;
// }
// }
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/messageItem/spinner/SpinnerItem.java
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.message.messageItem.MessageItemType;
import it.slyce.messaging.message.messageItem.MessageViewHolder;
package it.slyce.messaging.message.messageItem.spinner;
/**
* Created by matthewpage on 7/5/16.
*/
public class SpinnerItem extends MessageItem {
public SpinnerItem() {
super(null);
}
@Override
public void buildMessageItem(MessageViewHolder messageViewHolder) {
}
@Override
public MessageItemType getMessageItemType() {
return MessageItemType.SPINNER;
}
@Override | public MessageSource getMessageSource() { |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/test/java/it/slyce/messaging/MessageUtilsTest.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MediaMessage.java
// public class MediaMessage extends Message {
// private String url;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @Override
// public MessageItem toMessageItem(Context context){
// if (this.source == MessageSource.EXTERNAL_USER)
// return new MessageExternalUserMediaItem(this, context);
// else
// return new MessageInternalUserMediaItem(this, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/TextMessage.java
// public class TextMessage extends Message {
// private String text;
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context){
// if (this.source == MessageSource.EXTERNAL_USER)
// return new MessageExternalUserTextItem(this, context);
// else
// return new MessageInternalUserTextItem(this, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/utils/MessageUtils.java
// public class MessageUtils {
//
// public static void markMessageItemAtIndexIfFirstOrLastFromSource(int i, List<MessageItem> messageItems) {
// if (i < 0 || i >= messageItems.size()) {
// return;
// }
//
// MessageItem messageItem = messageItems.get(i);
// messageItem.setIsFirstConsecutiveMessageFromSource(false);
// messageItem.setIsLastConsecutiveMessageFromSource(false);
//
// if (previousMessageIsNotFromSameSource(i, messageItems)) {
// messageItem.setIsFirstConsecutiveMessageFromSource(true);
// }
//
// if (isTheLastConsecutiveMessageFromSource(i, messageItems)) {
// messageItem.setIsLastConsecutiveMessageFromSource(true);
// }
// }
//
// private static boolean previousMessageIsNotFromSameSource(int i, List<MessageItem> messageItems) {
// return i == 0 ||
// previousMessageIsSpinner(i, messageItems) ||
// previousMessageIsFromAnotherSender(i, messageItems);
// }
//
// private static boolean previousMessageIsFromAnotherSender(int i, List<MessageItem> messageItems) {
// return messageItems.get(i - 1).getMessageSource() != messageItems.get(i).getMessageSource();
// }
//
// private static boolean previousMessageIsSpinner(int i, List<MessageItem> messageItems) {
// return isSpinnerMessage(i - 1, messageItems);
// }
//
// private static boolean isTheLastConsecutiveMessageFromSource(int i, List<MessageItem> messageItems) {
// if (isSpinnerMessage(i, messageItems)) {
// return false;
// }
//
// return i == messageItems.size() - 1 ||
// nextMessageHasDifferentSource(i, messageItems) ||
// messageItems.get(i).getMessage() == null ||
// messageItems.get(i + 1).getMessage() == null ||
// nextMessageWasAtLeastAnHourAfterThisOne(i, messageItems);
// }
//
// private static boolean nextMessageWasAtLeastAnHourAfterThisOne(int i, List<MessageItem> messageItems) {
// return messageItems.get(i + 1).getMessage().getDate() - messageItems.get(i).getMessage().getDate() > 1000 * 60 * 60; // one hour
// }
//
// private static boolean nextMessageHasDifferentSource(int i, List<MessageItem> messageItems) {
// return messageItems.get(i).getMessageSource() != messageItems.get(i + 1).getMessageSource();
// }
//
// private static boolean isSpinnerMessage(int i, List<MessageItem> messageItems) {
// return messageItems.get(i).getMessageItemType() == MessageItemType.SPINNER;
// }
// }
| import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import it.slyce.messaging.message.MediaMessage;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.TextMessage;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.utils.MessageUtils;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | package it.slyce.messaging;
/**
* Created by audrey on 7/14/16.
*/
public class MessageUtilsTest {
List<MessageItem> messageItems;
@Before
public void before() {
messageItems = new ArrayList<>();
// incoming text | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MediaMessage.java
// public class MediaMessage extends Message {
// private String url;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @Override
// public MessageItem toMessageItem(Context context){
// if (this.source == MessageSource.EXTERNAL_USER)
// return new MessageExternalUserMediaItem(this, context);
// else
// return new MessageInternalUserMediaItem(this, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/TextMessage.java
// public class TextMessage extends Message {
// private String text;
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context){
// if (this.source == MessageSource.EXTERNAL_USER)
// return new MessageExternalUserTextItem(this, context);
// else
// return new MessageInternalUserTextItem(this, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/utils/MessageUtils.java
// public class MessageUtils {
//
// public static void markMessageItemAtIndexIfFirstOrLastFromSource(int i, List<MessageItem> messageItems) {
// if (i < 0 || i >= messageItems.size()) {
// return;
// }
//
// MessageItem messageItem = messageItems.get(i);
// messageItem.setIsFirstConsecutiveMessageFromSource(false);
// messageItem.setIsLastConsecutiveMessageFromSource(false);
//
// if (previousMessageIsNotFromSameSource(i, messageItems)) {
// messageItem.setIsFirstConsecutiveMessageFromSource(true);
// }
//
// if (isTheLastConsecutiveMessageFromSource(i, messageItems)) {
// messageItem.setIsLastConsecutiveMessageFromSource(true);
// }
// }
//
// private static boolean previousMessageIsNotFromSameSource(int i, List<MessageItem> messageItems) {
// return i == 0 ||
// previousMessageIsSpinner(i, messageItems) ||
// previousMessageIsFromAnotherSender(i, messageItems);
// }
//
// private static boolean previousMessageIsFromAnotherSender(int i, List<MessageItem> messageItems) {
// return messageItems.get(i - 1).getMessageSource() != messageItems.get(i).getMessageSource();
// }
//
// private static boolean previousMessageIsSpinner(int i, List<MessageItem> messageItems) {
// return isSpinnerMessage(i - 1, messageItems);
// }
//
// private static boolean isTheLastConsecutiveMessageFromSource(int i, List<MessageItem> messageItems) {
// if (isSpinnerMessage(i, messageItems)) {
// return false;
// }
//
// return i == messageItems.size() - 1 ||
// nextMessageHasDifferentSource(i, messageItems) ||
// messageItems.get(i).getMessage() == null ||
// messageItems.get(i + 1).getMessage() == null ||
// nextMessageWasAtLeastAnHourAfterThisOne(i, messageItems);
// }
//
// private static boolean nextMessageWasAtLeastAnHourAfterThisOne(int i, List<MessageItem> messageItems) {
// return messageItems.get(i + 1).getMessage().getDate() - messageItems.get(i).getMessage().getDate() > 1000 * 60 * 60; // one hour
// }
//
// private static boolean nextMessageHasDifferentSource(int i, List<MessageItem> messageItems) {
// return messageItems.get(i).getMessageSource() != messageItems.get(i + 1).getMessageSource();
// }
//
// private static boolean isSpinnerMessage(int i, List<MessageItem> messageItems) {
// return messageItems.get(i).getMessageItemType() == MessageItemType.SPINNER;
// }
// }
// Path: slyce-messaging/src/test/java/it/slyce/messaging/MessageUtilsTest.java
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import it.slyce.messaging.message.MediaMessage;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.TextMessage;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.utils.MessageUtils;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
package it.slyce.messaging;
/**
* Created by audrey on 7/14/16.
*/
public class MessageUtilsTest {
List<MessageItem> messageItems;
@Before
public void before() {
messageItems = new ArrayList<>();
// incoming text | TextMessage firstIncoming = new TextMessage(); |
Slyce-Inc/SlyceMessaging | slyce-messaging/src/test/java/it/slyce/messaging/MessageUtilsTest.java | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MediaMessage.java
// public class MediaMessage extends Message {
// private String url;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @Override
// public MessageItem toMessageItem(Context context){
// if (this.source == MessageSource.EXTERNAL_USER)
// return new MessageExternalUserMediaItem(this, context);
// else
// return new MessageInternalUserMediaItem(this, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/TextMessage.java
// public class TextMessage extends Message {
// private String text;
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context){
// if (this.source == MessageSource.EXTERNAL_USER)
// return new MessageExternalUserTextItem(this, context);
// else
// return new MessageInternalUserTextItem(this, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/utils/MessageUtils.java
// public class MessageUtils {
//
// public static void markMessageItemAtIndexIfFirstOrLastFromSource(int i, List<MessageItem> messageItems) {
// if (i < 0 || i >= messageItems.size()) {
// return;
// }
//
// MessageItem messageItem = messageItems.get(i);
// messageItem.setIsFirstConsecutiveMessageFromSource(false);
// messageItem.setIsLastConsecutiveMessageFromSource(false);
//
// if (previousMessageIsNotFromSameSource(i, messageItems)) {
// messageItem.setIsFirstConsecutiveMessageFromSource(true);
// }
//
// if (isTheLastConsecutiveMessageFromSource(i, messageItems)) {
// messageItem.setIsLastConsecutiveMessageFromSource(true);
// }
// }
//
// private static boolean previousMessageIsNotFromSameSource(int i, List<MessageItem> messageItems) {
// return i == 0 ||
// previousMessageIsSpinner(i, messageItems) ||
// previousMessageIsFromAnotherSender(i, messageItems);
// }
//
// private static boolean previousMessageIsFromAnotherSender(int i, List<MessageItem> messageItems) {
// return messageItems.get(i - 1).getMessageSource() != messageItems.get(i).getMessageSource();
// }
//
// private static boolean previousMessageIsSpinner(int i, List<MessageItem> messageItems) {
// return isSpinnerMessage(i - 1, messageItems);
// }
//
// private static boolean isTheLastConsecutiveMessageFromSource(int i, List<MessageItem> messageItems) {
// if (isSpinnerMessage(i, messageItems)) {
// return false;
// }
//
// return i == messageItems.size() - 1 ||
// nextMessageHasDifferentSource(i, messageItems) ||
// messageItems.get(i).getMessage() == null ||
// messageItems.get(i + 1).getMessage() == null ||
// nextMessageWasAtLeastAnHourAfterThisOne(i, messageItems);
// }
//
// private static boolean nextMessageWasAtLeastAnHourAfterThisOne(int i, List<MessageItem> messageItems) {
// return messageItems.get(i + 1).getMessage().getDate() - messageItems.get(i).getMessage().getDate() > 1000 * 60 * 60; // one hour
// }
//
// private static boolean nextMessageHasDifferentSource(int i, List<MessageItem> messageItems) {
// return messageItems.get(i).getMessageSource() != messageItems.get(i + 1).getMessageSource();
// }
//
// private static boolean isSpinnerMessage(int i, List<MessageItem> messageItems) {
// return messageItems.get(i).getMessageItemType() == MessageItemType.SPINNER;
// }
// }
| import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import it.slyce.messaging.message.MediaMessage;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.TextMessage;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.utils.MessageUtils;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | package it.slyce.messaging;
/**
* Created by audrey on 7/14/16.
*/
public class MessageUtilsTest {
List<MessageItem> messageItems;
@Before
public void before() {
messageItems = new ArrayList<>();
// incoming text
TextMessage firstIncoming = new TextMessage(); | // Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MediaMessage.java
// public class MediaMessage extends Message {
// private String url;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @Override
// public MessageItem toMessageItem(Context context){
// if (this.source == MessageSource.EXTERNAL_USER)
// return new MessageExternalUserMediaItem(this, context);
// else
// return new MessageInternalUserMediaItem(this, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/MessageSource.java
// public enum MessageSource {
// LOCAL_USER,
// EXTERNAL_USER,
// GENERAL
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/message/TextMessage.java
// public class TextMessage extends Message {
// private String text;
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Override
// public MessageItem toMessageItem(Context context){
// if (this.source == MessageSource.EXTERNAL_USER)
// return new MessageExternalUserTextItem(this, context);
// else
// return new MessageInternalUserTextItem(this, context);
// }
// }
//
// Path: slyce-messaging/src/main/java/it/slyce/messaging/utils/MessageUtils.java
// public class MessageUtils {
//
// public static void markMessageItemAtIndexIfFirstOrLastFromSource(int i, List<MessageItem> messageItems) {
// if (i < 0 || i >= messageItems.size()) {
// return;
// }
//
// MessageItem messageItem = messageItems.get(i);
// messageItem.setIsFirstConsecutiveMessageFromSource(false);
// messageItem.setIsLastConsecutiveMessageFromSource(false);
//
// if (previousMessageIsNotFromSameSource(i, messageItems)) {
// messageItem.setIsFirstConsecutiveMessageFromSource(true);
// }
//
// if (isTheLastConsecutiveMessageFromSource(i, messageItems)) {
// messageItem.setIsLastConsecutiveMessageFromSource(true);
// }
// }
//
// private static boolean previousMessageIsNotFromSameSource(int i, List<MessageItem> messageItems) {
// return i == 0 ||
// previousMessageIsSpinner(i, messageItems) ||
// previousMessageIsFromAnotherSender(i, messageItems);
// }
//
// private static boolean previousMessageIsFromAnotherSender(int i, List<MessageItem> messageItems) {
// return messageItems.get(i - 1).getMessageSource() != messageItems.get(i).getMessageSource();
// }
//
// private static boolean previousMessageIsSpinner(int i, List<MessageItem> messageItems) {
// return isSpinnerMessage(i - 1, messageItems);
// }
//
// private static boolean isTheLastConsecutiveMessageFromSource(int i, List<MessageItem> messageItems) {
// if (isSpinnerMessage(i, messageItems)) {
// return false;
// }
//
// return i == messageItems.size() - 1 ||
// nextMessageHasDifferentSource(i, messageItems) ||
// messageItems.get(i).getMessage() == null ||
// messageItems.get(i + 1).getMessage() == null ||
// nextMessageWasAtLeastAnHourAfterThisOne(i, messageItems);
// }
//
// private static boolean nextMessageWasAtLeastAnHourAfterThisOne(int i, List<MessageItem> messageItems) {
// return messageItems.get(i + 1).getMessage().getDate() - messageItems.get(i).getMessage().getDate() > 1000 * 60 * 60; // one hour
// }
//
// private static boolean nextMessageHasDifferentSource(int i, List<MessageItem> messageItems) {
// return messageItems.get(i).getMessageSource() != messageItems.get(i + 1).getMessageSource();
// }
//
// private static boolean isSpinnerMessage(int i, List<MessageItem> messageItems) {
// return messageItems.get(i).getMessageItemType() == MessageItemType.SPINNER;
// }
// }
// Path: slyce-messaging/src/test/java/it/slyce/messaging/MessageUtilsTest.java
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import it.slyce.messaging.message.MediaMessage;
import it.slyce.messaging.message.MessageSource;
import it.slyce.messaging.message.TextMessage;
import it.slyce.messaging.message.messageItem.MessageItem;
import it.slyce.messaging.utils.MessageUtils;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
package it.slyce.messaging;
/**
* Created by audrey on 7/14/16.
*/
public class MessageUtilsTest {
List<MessageItem> messageItems;
@Before
public void before() {
messageItems = new ArrayList<>();
// incoming text
TextMessage firstIncoming = new TextMessage(); | firstIncoming.setSource(MessageSource.EXTERNAL_USER); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.