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 |
|---|---|---|---|---|---|---|
census-instrumentation/opencensus-java | exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java | // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java
// static final Duration DEFAULT_DEADLINE = Duration.create(60, 0);
//
// Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java
// static final String DEFAULT_PROJECT_ID =
// Strings.nullToEmpty(ServiceOptions.getDefaultProjectId());
//
// Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java
// static final MonitoredResource DEFAULT_RESOURCE = StackdriverExportUtils.getDefaultResource();
//
// Path: api/src/main/java/io/opencensus/common/OpenCensusLibraryInformation.java
// @ExperimentalApi
// public final class OpenCensusLibraryInformation {
//
// /**
// * The current version of the OpenCensus Java library.
// *
// * @since 0.8
// */
// public static final String VERSION = "0.32.0-SNAPSHOT"; // CURRENT_OPENCENSUS_VERSION
//
// private OpenCensusLibraryInformation() {}
// }
| import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static io.opencensus.exporter.stats.stackdriver.StackdriverExportUtils.DEFAULT_CONSTANT_LABELS;
import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_DEADLINE;
import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_PROJECT_ID;
import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_RESOURCE;
import com.google.api.MonitoredResource;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.rpc.FixedHeaderProvider;
import com.google.api.gax.rpc.HeaderProvider;
import com.google.auth.Credentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.ServiceOptions;
import com.google.cloud.monitoring.v3.MetricServiceClient;
import com.google.cloud.monitoring.v3.MetricServiceSettings;
import com.google.cloud.monitoring.v3.stub.MetricServiceStub;
import com.google.common.annotations.VisibleForTesting;
import io.opencensus.common.Duration;
import io.opencensus.common.OpenCensusLibraryInformation;
import io.opencensus.exporter.metrics.util.IntervalMetricReader;
import io.opencensus.exporter.metrics.util.MetricReader;
import io.opencensus.metrics.LabelKey;
import io.opencensus.metrics.LabelValue;
import io.opencensus.metrics.Metrics;
import java.io.IOException;
import java.util.Map;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe; | */
public static void createAndRegister() throws IOException {
createAndRegister(StackdriverStatsConfiguration.builder().build());
}
/**
* Creates a Stackdriver Stats exporter with default Monitored Resource.
*
* <p>Only one Stackdriver exporter can be created.
*
* <p>This uses the default application credentials. See {@link
* GoogleCredentials#getApplicationDefault}.
*
* <p>This uses the default project ID configured see {@link ServiceOptions#getDefaultProjectId}.
*
* <p>This is equivalent with:
*
* <pre>{@code
* StackdriverStatsExporter.createWithProjectId(ServiceOptions.getDefaultProjectId());
* }</pre>
*
* @param exportInterval the interval between pushing stats to StackDriver.
* @throws IllegalStateException if a Stackdriver exporter is already created.
* @deprecated in favor of {@link #createAndRegister(StackdriverStatsConfiguration)}.
* @since 0.9
*/
@Deprecated
public static void createAndRegister(Duration exportInterval) throws IOException {
checkNotNull(exportInterval, "exportInterval");
checkArgument( | // Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java
// static final Duration DEFAULT_DEADLINE = Duration.create(60, 0);
//
// Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java
// static final String DEFAULT_PROJECT_ID =
// Strings.nullToEmpty(ServiceOptions.getDefaultProjectId());
//
// Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsConfiguration.java
// static final MonitoredResource DEFAULT_RESOURCE = StackdriverExportUtils.getDefaultResource();
//
// Path: api/src/main/java/io/opencensus/common/OpenCensusLibraryInformation.java
// @ExperimentalApi
// public final class OpenCensusLibraryInformation {
//
// /**
// * The current version of the OpenCensus Java library.
// *
// * @since 0.8
// */
// public static final String VERSION = "0.32.0-SNAPSHOT"; // CURRENT_OPENCENSUS_VERSION
//
// private OpenCensusLibraryInformation() {}
// }
// Path: exporters/stats/stackdriver/src/main/java/io/opencensus/exporter/stats/stackdriver/StackdriverStatsExporter.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static io.opencensus.exporter.stats.stackdriver.StackdriverExportUtils.DEFAULT_CONSTANT_LABELS;
import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_DEADLINE;
import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_PROJECT_ID;
import static io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration.DEFAULT_RESOURCE;
import com.google.api.MonitoredResource;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.rpc.FixedHeaderProvider;
import com.google.api.gax.rpc.HeaderProvider;
import com.google.auth.Credentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.ServiceOptions;
import com.google.cloud.monitoring.v3.MetricServiceClient;
import com.google.cloud.monitoring.v3.MetricServiceSettings;
import com.google.cloud.monitoring.v3.stub.MetricServiceStub;
import com.google.common.annotations.VisibleForTesting;
import io.opencensus.common.Duration;
import io.opencensus.common.OpenCensusLibraryInformation;
import io.opencensus.exporter.metrics.util.IntervalMetricReader;
import io.opencensus.exporter.metrics.util.MetricReader;
import io.opencensus.metrics.LabelKey;
import io.opencensus.metrics.LabelValue;
import io.opencensus.metrics.Metrics;
import java.io.IOException;
import java.util.Map;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
*/
public static void createAndRegister() throws IOException {
createAndRegister(StackdriverStatsConfiguration.builder().build());
}
/**
* Creates a Stackdriver Stats exporter with default Monitored Resource.
*
* <p>Only one Stackdriver exporter can be created.
*
* <p>This uses the default application credentials. See {@link
* GoogleCredentials#getApplicationDefault}.
*
* <p>This uses the default project ID configured see {@link ServiceOptions#getDefaultProjectId}.
*
* <p>This is equivalent with:
*
* <pre>{@code
* StackdriverStatsExporter.createWithProjectId(ServiceOptions.getDefaultProjectId());
* }</pre>
*
* @param exportInterval the interval between pushing stats to StackDriver.
* @throws IllegalStateException if a Stackdriver exporter is already created.
* @deprecated in favor of {@link #createAndRegister(StackdriverStatsConfiguration)}.
* @since 0.9
*/
@Deprecated
public static void createAndRegister(Duration exportInterval) throws IOException {
checkNotNull(exportInterval, "exportInterval");
checkArgument( | !DEFAULT_PROJECT_ID.isEmpty(), "Cannot find a project ID from application default."); |
census-instrumentation/opencensus-java | contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthSpanContextHolder.java | // Path: api/src/main/java/io/opencensus/trace/ContextHandle.java
// public interface ContextHandle {
//
// ContextHandle attach();
//
// void detach(ContextHandle contextHandle);
// }
//
// Path: api/src/main/java/io/opencensus/trace/unsafe/ContextHandleUtils.java
// public class ContextHandleUtils {
//
// // No instance of this class.
// private ContextHandleUtils() {}
//
// private static final Logger LOGGER = Logger.getLogger(ContextHandleUtils.class.getName());
// private static final ContextManager CONTEXT_MANAGER =
// loadContextManager(ContextManager.class.getClassLoader());
//
// private static ContextManager loadContextManager(@Nullable ClassLoader classLoader) {
// try {
// return Provider.createInstance(
// Class.forName(
// "io.opentelemetry.opencensusshim.OpenTelemetryContextManager",
// /*initialize=*/ true,
// classLoader),
// ContextManager.class);
// } catch (ClassNotFoundException e) {
// LOGGER.log(
// Level.FINE,
// "Couldn't load full implementation for OpenTelemetry context manager, now loading "
// + "original implementation.",
// e);
// }
// return new ContextManagerImpl();
// }
//
// public static ContextHandle currentContext() {
// return CONTEXT_MANAGER.currentContext();
// }
//
// /**
// * Creates a new {@code ContextHandle} with the given value set.
// *
// * @param context the parent {@code ContextHandle}.
// * @param span the value to be set.
// * @return a new context with the given value set.
// */
// public static ContextHandle withValue(
// ContextHandle context, @javax.annotation.Nullable Span span) {
// return CONTEXT_MANAGER.withValue(context, span);
// }
//
// /**
// * Returns the value from the specified {@code ContextHandle}.
// *
// * @param context the specified {@code ContextHandle}.
// * @return the value from the specified {@code ContextHandle}.
// */
// public static Span getValue(ContextHandle context) {
// return CONTEXT_MANAGER.getValue(context);
// }
//
// /**
// * Attempts to pull the {@link io.grpc.Context} out of an OpenCensus {@code ContextHandle}.
// *
// * @return The context, or null if not a GRPC backed context handle.
// */
// @Nullable
// public static Context tryExtractGrpcContext(ContextHandle handle) {
// if (handle instanceof ContextHandleImpl) {
// return ((ContextHandleImpl) handle).getContext();
// }
// // TODO: see if we can do something for the OpenTelemetry shim.
// return null;
// }
// }
| import io.grpc.Context;
import io.opencensus.common.ExperimentalApi;
import io.opencensus.trace.ContextHandle;
import io.opencensus.trace.unsafe.ContextHandleUtils;
import org.apache.commons.logging.Log;
import org.springframework.cloud.sleuth.Span;
import org.springframework.core.NamedThreadLocal; |
interface SpanFunction {
void apply(Span span);
}
private static final SpanFunction NO_OP_FUNCTION =
new SpanFunction() {
@Override
public void apply(Span span) {}
};
@SuppressWarnings("CheckReturnValue")
private static void setSpanContextInternal(SpanContext spanContext) {
CURRENT_SPAN.set(spanContext);
spanContext.ocCurrentContext.attach();
}
private static boolean isCurrent(Span span) {
if (span == null) {
return false;
}
SpanContext currentSpanContext = CURRENT_SPAN.get();
return currentSpanContext != null && span.equals(currentSpanContext.span);
}
private static class SpanContext {
final Span span;
final boolean autoClose;
@javax.annotation.Nullable final SpanContext parent;
final OpenCensusSleuthSpan ocSpan; | // Path: api/src/main/java/io/opencensus/trace/ContextHandle.java
// public interface ContextHandle {
//
// ContextHandle attach();
//
// void detach(ContextHandle contextHandle);
// }
//
// Path: api/src/main/java/io/opencensus/trace/unsafe/ContextHandleUtils.java
// public class ContextHandleUtils {
//
// // No instance of this class.
// private ContextHandleUtils() {}
//
// private static final Logger LOGGER = Logger.getLogger(ContextHandleUtils.class.getName());
// private static final ContextManager CONTEXT_MANAGER =
// loadContextManager(ContextManager.class.getClassLoader());
//
// private static ContextManager loadContextManager(@Nullable ClassLoader classLoader) {
// try {
// return Provider.createInstance(
// Class.forName(
// "io.opentelemetry.opencensusshim.OpenTelemetryContextManager",
// /*initialize=*/ true,
// classLoader),
// ContextManager.class);
// } catch (ClassNotFoundException e) {
// LOGGER.log(
// Level.FINE,
// "Couldn't load full implementation for OpenTelemetry context manager, now loading "
// + "original implementation.",
// e);
// }
// return new ContextManagerImpl();
// }
//
// public static ContextHandle currentContext() {
// return CONTEXT_MANAGER.currentContext();
// }
//
// /**
// * Creates a new {@code ContextHandle} with the given value set.
// *
// * @param context the parent {@code ContextHandle}.
// * @param span the value to be set.
// * @return a new context with the given value set.
// */
// public static ContextHandle withValue(
// ContextHandle context, @javax.annotation.Nullable Span span) {
// return CONTEXT_MANAGER.withValue(context, span);
// }
//
// /**
// * Returns the value from the specified {@code ContextHandle}.
// *
// * @param context the specified {@code ContextHandle}.
// * @return the value from the specified {@code ContextHandle}.
// */
// public static Span getValue(ContextHandle context) {
// return CONTEXT_MANAGER.getValue(context);
// }
//
// /**
// * Attempts to pull the {@link io.grpc.Context} out of an OpenCensus {@code ContextHandle}.
// *
// * @return The context, or null if not a GRPC backed context handle.
// */
// @Nullable
// public static Context tryExtractGrpcContext(ContextHandle handle) {
// if (handle instanceof ContextHandleImpl) {
// return ((ContextHandleImpl) handle).getContext();
// }
// // TODO: see if we can do something for the OpenTelemetry shim.
// return null;
// }
// }
// Path: contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthSpanContextHolder.java
import io.grpc.Context;
import io.opencensus.common.ExperimentalApi;
import io.opencensus.trace.ContextHandle;
import io.opencensus.trace.unsafe.ContextHandleUtils;
import org.apache.commons.logging.Log;
import org.springframework.cloud.sleuth.Span;
import org.springframework.core.NamedThreadLocal;
interface SpanFunction {
void apply(Span span);
}
private static final SpanFunction NO_OP_FUNCTION =
new SpanFunction() {
@Override
public void apply(Span span) {}
};
@SuppressWarnings("CheckReturnValue")
private static void setSpanContextInternal(SpanContext spanContext) {
CURRENT_SPAN.set(spanContext);
spanContext.ocCurrentContext.attach();
}
private static boolean isCurrent(Span span) {
if (span == null) {
return false;
}
SpanContext currentSpanContext = CURRENT_SPAN.get();
return currentSpanContext != null && span.equals(currentSpanContext.span);
}
private static class SpanContext {
final Span span;
final boolean autoClose;
@javax.annotation.Nullable final SpanContext parent;
final OpenCensusSleuthSpan ocSpan; | final ContextHandle ocCurrentContext; |
census-instrumentation/opencensus-java | contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthSpanContextHolder.java | // Path: api/src/main/java/io/opencensus/trace/ContextHandle.java
// public interface ContextHandle {
//
// ContextHandle attach();
//
// void detach(ContextHandle contextHandle);
// }
//
// Path: api/src/main/java/io/opencensus/trace/unsafe/ContextHandleUtils.java
// public class ContextHandleUtils {
//
// // No instance of this class.
// private ContextHandleUtils() {}
//
// private static final Logger LOGGER = Logger.getLogger(ContextHandleUtils.class.getName());
// private static final ContextManager CONTEXT_MANAGER =
// loadContextManager(ContextManager.class.getClassLoader());
//
// private static ContextManager loadContextManager(@Nullable ClassLoader classLoader) {
// try {
// return Provider.createInstance(
// Class.forName(
// "io.opentelemetry.opencensusshim.OpenTelemetryContextManager",
// /*initialize=*/ true,
// classLoader),
// ContextManager.class);
// } catch (ClassNotFoundException e) {
// LOGGER.log(
// Level.FINE,
// "Couldn't load full implementation for OpenTelemetry context manager, now loading "
// + "original implementation.",
// e);
// }
// return new ContextManagerImpl();
// }
//
// public static ContextHandle currentContext() {
// return CONTEXT_MANAGER.currentContext();
// }
//
// /**
// * Creates a new {@code ContextHandle} with the given value set.
// *
// * @param context the parent {@code ContextHandle}.
// * @param span the value to be set.
// * @return a new context with the given value set.
// */
// public static ContextHandle withValue(
// ContextHandle context, @javax.annotation.Nullable Span span) {
// return CONTEXT_MANAGER.withValue(context, span);
// }
//
// /**
// * Returns the value from the specified {@code ContextHandle}.
// *
// * @param context the specified {@code ContextHandle}.
// * @return the value from the specified {@code ContextHandle}.
// */
// public static Span getValue(ContextHandle context) {
// return CONTEXT_MANAGER.getValue(context);
// }
//
// /**
// * Attempts to pull the {@link io.grpc.Context} out of an OpenCensus {@code ContextHandle}.
// *
// * @return The context, or null if not a GRPC backed context handle.
// */
// @Nullable
// public static Context tryExtractGrpcContext(ContextHandle handle) {
// if (handle instanceof ContextHandleImpl) {
// return ((ContextHandleImpl) handle).getContext();
// }
// // TODO: see if we can do something for the OpenTelemetry shim.
// return null;
// }
// }
| import io.grpc.Context;
import io.opencensus.common.ExperimentalApi;
import io.opencensus.trace.ContextHandle;
import io.opencensus.trace.unsafe.ContextHandleUtils;
import org.apache.commons.logging.Log;
import org.springframework.cloud.sleuth.Span;
import org.springframework.core.NamedThreadLocal; | public void apply(Span span) {}
};
@SuppressWarnings("CheckReturnValue")
private static void setSpanContextInternal(SpanContext spanContext) {
CURRENT_SPAN.set(spanContext);
spanContext.ocCurrentContext.attach();
}
private static boolean isCurrent(Span span) {
if (span == null) {
return false;
}
SpanContext currentSpanContext = CURRENT_SPAN.get();
return currentSpanContext != null && span.equals(currentSpanContext.span);
}
private static class SpanContext {
final Span span;
final boolean autoClose;
@javax.annotation.Nullable final SpanContext parent;
final OpenCensusSleuthSpan ocSpan;
final ContextHandle ocCurrentContext;
private SpanContext(Span span, boolean autoClose) {
this.span = span;
this.autoClose = autoClose;
this.parent = CURRENT_SPAN.get();
this.ocSpan = new OpenCensusSleuthSpan(span);
this.ocCurrentContext = | // Path: api/src/main/java/io/opencensus/trace/ContextHandle.java
// public interface ContextHandle {
//
// ContextHandle attach();
//
// void detach(ContextHandle contextHandle);
// }
//
// Path: api/src/main/java/io/opencensus/trace/unsafe/ContextHandleUtils.java
// public class ContextHandleUtils {
//
// // No instance of this class.
// private ContextHandleUtils() {}
//
// private static final Logger LOGGER = Logger.getLogger(ContextHandleUtils.class.getName());
// private static final ContextManager CONTEXT_MANAGER =
// loadContextManager(ContextManager.class.getClassLoader());
//
// private static ContextManager loadContextManager(@Nullable ClassLoader classLoader) {
// try {
// return Provider.createInstance(
// Class.forName(
// "io.opentelemetry.opencensusshim.OpenTelemetryContextManager",
// /*initialize=*/ true,
// classLoader),
// ContextManager.class);
// } catch (ClassNotFoundException e) {
// LOGGER.log(
// Level.FINE,
// "Couldn't load full implementation for OpenTelemetry context manager, now loading "
// + "original implementation.",
// e);
// }
// return new ContextManagerImpl();
// }
//
// public static ContextHandle currentContext() {
// return CONTEXT_MANAGER.currentContext();
// }
//
// /**
// * Creates a new {@code ContextHandle} with the given value set.
// *
// * @param context the parent {@code ContextHandle}.
// * @param span the value to be set.
// * @return a new context with the given value set.
// */
// public static ContextHandle withValue(
// ContextHandle context, @javax.annotation.Nullable Span span) {
// return CONTEXT_MANAGER.withValue(context, span);
// }
//
// /**
// * Returns the value from the specified {@code ContextHandle}.
// *
// * @param context the specified {@code ContextHandle}.
// * @return the value from the specified {@code ContextHandle}.
// */
// public static Span getValue(ContextHandle context) {
// return CONTEXT_MANAGER.getValue(context);
// }
//
// /**
// * Attempts to pull the {@link io.grpc.Context} out of an OpenCensus {@code ContextHandle}.
// *
// * @return The context, or null if not a GRPC backed context handle.
// */
// @Nullable
// public static Context tryExtractGrpcContext(ContextHandle handle) {
// if (handle instanceof ContextHandleImpl) {
// return ((ContextHandleImpl) handle).getContext();
// }
// // TODO: see if we can do something for the OpenTelemetry shim.
// return null;
// }
// }
// Path: contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthSpanContextHolder.java
import io.grpc.Context;
import io.opencensus.common.ExperimentalApi;
import io.opencensus.trace.ContextHandle;
import io.opencensus.trace.unsafe.ContextHandleUtils;
import org.apache.commons.logging.Log;
import org.springframework.cloud.sleuth.Span;
import org.springframework.core.NamedThreadLocal;
public void apply(Span span) {}
};
@SuppressWarnings("CheckReturnValue")
private static void setSpanContextInternal(SpanContext spanContext) {
CURRENT_SPAN.set(spanContext);
spanContext.ocCurrentContext.attach();
}
private static boolean isCurrent(Span span) {
if (span == null) {
return false;
}
SpanContext currentSpanContext = CURRENT_SPAN.get();
return currentSpanContext != null && span.equals(currentSpanContext.span);
}
private static class SpanContext {
final Span span;
final boolean autoClose;
@javax.annotation.Nullable final SpanContext parent;
final OpenCensusSleuthSpan ocSpan;
final ContextHandle ocCurrentContext;
private SpanContext(Span span, boolean autoClose) {
this.span = span;
this.autoClose = autoClose;
this.parent = CURRENT_SPAN.get();
this.ocSpan = new OpenCensusSleuthSpan(span);
this.ocCurrentContext = | ContextHandleUtils.withValue(ContextHandleUtils.currentContext(), this.ocSpan); |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/view/visualization/RaphaelViz.java | // Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
| import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.java33.vizpres.shared.model.PercentValue;
import java.util.List; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.view.visualization;
/**
* Is a demonstration of using Raphael to render SVG/VML to the browser.
*
* @author Jon Buffington
*/
public class RaphaelViz extends Composite implements IsDataSync {
interface RaphaelVizUiBinder extends UiBinder<FlowPanel, RaphaelViz> {
}
private final static RaphaelVizUiBinder UIBINDER = GWT.create(RaphaelVizUiBinder.class);
@UiField(provided = true)
RaphaelCanvas canvas;
@UiField
Label infoLabel;
@UiConstructor
public RaphaelViz(final int width, final int height) {
canvas = new RaphaelCanvas(width, height, this);
initWidget(UIBINDER.createAndBindUi(this));
}
@Override | // Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
// Path: src/main/java/com/java33/vizpres/client/view/visualization/RaphaelViz.java
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.java33.vizpres.shared.model.PercentValue;
import java.util.List;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.view.visualization;
/**
* Is a demonstration of using Raphael to render SVG/VML to the browser.
*
* @author Jon Buffington
*/
public class RaphaelViz extends Composite implements IsDataSync {
interface RaphaelVizUiBinder extends UiBinder<FlowPanel, RaphaelViz> {
}
private final static RaphaelVizUiBinder UIBINDER = GWT.create(RaphaelVizUiBinder.class);
@UiField(provided = true)
RaphaelCanvas canvas;
@UiField
Label infoLabel;
@UiConstructor
public RaphaelViz(final int width, final int height) {
canvas = new RaphaelCanvas(width, height, this);
initWidget(UIBINDER.createAndBindUi(this));
}
@Override | public void setData(final List<PercentValue> values) { |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/AppController.java | // Path: src/main/java/com/java33/vizpres/client/event/DataEvent.java
// public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
// public interface DataEventHandler extends EventHandler {
// void onData(DataEvent event, IsDataSync dataSync);
// }
//
// public static Type<DataEventHandler> TYPE = new Type<DataEventHandler>();
//
// public IsDataSync target;
//
// @Override
// public Type<DataEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(final DataEventHandler handler) {
// handler.onData(this, target);
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
// @GinModules(AppModule.class)
// public interface AppInjector extends Ginjector {
// AppController getAppController();
//
// MainPresenter getMainPresenter();
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/Presenter.java
// public interface Presenter {
// public void go(final HasWidgets container);
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/service/PercentServiceAsync.java
// public interface PercentServiceAsync extends RestService {
// String PREFERRED_MEDIA_TYPE = "application/vnd.vizpres+json";
//
// @GET
// @Produces(PREFERRED_MEDIA_TYPE)
// void getPercents(MethodCallback<List<PercentValue>> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
| import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;
import com.java33.vizpres.client.event.DataEvent;
import com.java33.vizpres.client.gin.AppInjector;
import com.java33.vizpres.client.presenter.Presenter;
import com.java33.vizpres.client.view.visualization.IsDataSync;
import com.java33.vizpres.shared.service.PercentServiceAsync;
import com.java33.vizpres.shared.model.PercentValue;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.Resource;
import org.fusesource.restygwt.client.RestServiceProxy;
import java.util.List;
import java.util.logging.Logger; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client;
/**
* Coordinate the application's various presenters using GWT's History support.
* The new Activity and Places support in GWT 2.1 would be a better choice for a
* larger application.
*
* @author Jon Buffington
*/
public class AppController implements Presenter, ValueChangeHandler<String> {
private static final Logger logger = Logger.getLogger(AppController.class.getName());
private static final String DEFAULT_TOKEN = "default";
private final EventBus eventBus; | // Path: src/main/java/com/java33/vizpres/client/event/DataEvent.java
// public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
// public interface DataEventHandler extends EventHandler {
// void onData(DataEvent event, IsDataSync dataSync);
// }
//
// public static Type<DataEventHandler> TYPE = new Type<DataEventHandler>();
//
// public IsDataSync target;
//
// @Override
// public Type<DataEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(final DataEventHandler handler) {
// handler.onData(this, target);
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
// @GinModules(AppModule.class)
// public interface AppInjector extends Ginjector {
// AppController getAppController();
//
// MainPresenter getMainPresenter();
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/Presenter.java
// public interface Presenter {
// public void go(final HasWidgets container);
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/service/PercentServiceAsync.java
// public interface PercentServiceAsync extends RestService {
// String PREFERRED_MEDIA_TYPE = "application/vnd.vizpres+json";
//
// @GET
// @Produces(PREFERRED_MEDIA_TYPE)
// void getPercents(MethodCallback<List<PercentValue>> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
// Path: src/main/java/com/java33/vizpres/client/AppController.java
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;
import com.java33.vizpres.client.event.DataEvent;
import com.java33.vizpres.client.gin.AppInjector;
import com.java33.vizpres.client.presenter.Presenter;
import com.java33.vizpres.client.view.visualization.IsDataSync;
import com.java33.vizpres.shared.service.PercentServiceAsync;
import com.java33.vizpres.shared.model.PercentValue;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.Resource;
import org.fusesource.restygwt.client.RestServiceProxy;
import java.util.List;
import java.util.logging.Logger;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client;
/**
* Coordinate the application's various presenters using GWT's History support.
* The new Activity and Places support in GWT 2.1 would be a better choice for a
* larger application.
*
* @author Jon Buffington
*/
public class AppController implements Presenter, ValueChangeHandler<String> {
private static final Logger logger = Logger.getLogger(AppController.class.getName());
private static final String DEFAULT_TOKEN = "default";
private final EventBus eventBus; | private final AppInjector injector; |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/AppController.java | // Path: src/main/java/com/java33/vizpres/client/event/DataEvent.java
// public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
// public interface DataEventHandler extends EventHandler {
// void onData(DataEvent event, IsDataSync dataSync);
// }
//
// public static Type<DataEventHandler> TYPE = new Type<DataEventHandler>();
//
// public IsDataSync target;
//
// @Override
// public Type<DataEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(final DataEventHandler handler) {
// handler.onData(this, target);
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
// @GinModules(AppModule.class)
// public interface AppInjector extends Ginjector {
// AppController getAppController();
//
// MainPresenter getMainPresenter();
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/Presenter.java
// public interface Presenter {
// public void go(final HasWidgets container);
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/service/PercentServiceAsync.java
// public interface PercentServiceAsync extends RestService {
// String PREFERRED_MEDIA_TYPE = "application/vnd.vizpres+json";
//
// @GET
// @Produces(PREFERRED_MEDIA_TYPE)
// void getPercents(MethodCallback<List<PercentValue>> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
| import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;
import com.java33.vizpres.client.event.DataEvent;
import com.java33.vizpres.client.gin.AppInjector;
import com.java33.vizpres.client.presenter.Presenter;
import com.java33.vizpres.client.view.visualization.IsDataSync;
import com.java33.vizpres.shared.service.PercentServiceAsync;
import com.java33.vizpres.shared.model.PercentValue;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.Resource;
import org.fusesource.restygwt.client.RestServiceProxy;
import java.util.List;
import java.util.logging.Logger; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client;
/**
* Coordinate the application's various presenters using GWT's History support.
* The new Activity and Places support in GWT 2.1 would be a better choice for a
* larger application.
*
* @author Jon Buffington
*/
public class AppController implements Presenter, ValueChangeHandler<String> {
private static final Logger logger = Logger.getLogger(AppController.class.getName());
private static final String DEFAULT_TOKEN = "default";
private final EventBus eventBus;
private final AppInjector injector;
private HasWidgets container;
@Inject
public AppController(final EventBus eventBus, final AppInjector injector) {
this.eventBus = eventBus;
this.injector = injector;
bind();
}
/**
* Bind handlers to the application's events.
*/
private void bind() {
History.addValueChangeHandler(this);
| // Path: src/main/java/com/java33/vizpres/client/event/DataEvent.java
// public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
// public interface DataEventHandler extends EventHandler {
// void onData(DataEvent event, IsDataSync dataSync);
// }
//
// public static Type<DataEventHandler> TYPE = new Type<DataEventHandler>();
//
// public IsDataSync target;
//
// @Override
// public Type<DataEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(final DataEventHandler handler) {
// handler.onData(this, target);
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
// @GinModules(AppModule.class)
// public interface AppInjector extends Ginjector {
// AppController getAppController();
//
// MainPresenter getMainPresenter();
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/Presenter.java
// public interface Presenter {
// public void go(final HasWidgets container);
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/service/PercentServiceAsync.java
// public interface PercentServiceAsync extends RestService {
// String PREFERRED_MEDIA_TYPE = "application/vnd.vizpres+json";
//
// @GET
// @Produces(PREFERRED_MEDIA_TYPE)
// void getPercents(MethodCallback<List<PercentValue>> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
// Path: src/main/java/com/java33/vizpres/client/AppController.java
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;
import com.java33.vizpres.client.event.DataEvent;
import com.java33.vizpres.client.gin.AppInjector;
import com.java33.vizpres.client.presenter.Presenter;
import com.java33.vizpres.client.view.visualization.IsDataSync;
import com.java33.vizpres.shared.service.PercentServiceAsync;
import com.java33.vizpres.shared.model.PercentValue;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.Resource;
import org.fusesource.restygwt.client.RestServiceProxy;
import java.util.List;
import java.util.logging.Logger;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client;
/**
* Coordinate the application's various presenters using GWT's History support.
* The new Activity and Places support in GWT 2.1 would be a better choice for a
* larger application.
*
* @author Jon Buffington
*/
public class AppController implements Presenter, ValueChangeHandler<String> {
private static final Logger logger = Logger.getLogger(AppController.class.getName());
private static final String DEFAULT_TOKEN = "default";
private final EventBus eventBus;
private final AppInjector injector;
private HasWidgets container;
@Inject
public AppController(final EventBus eventBus, final AppInjector injector) {
this.eventBus = eventBus;
this.injector = injector;
bind();
}
/**
* Bind handlers to the application's events.
*/
private void bind() {
History.addValueChangeHandler(this);
| eventBus.addHandler(DataEvent.TYPE, new DataEvent.DataEventHandler() { |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/AppController.java | // Path: src/main/java/com/java33/vizpres/client/event/DataEvent.java
// public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
// public interface DataEventHandler extends EventHandler {
// void onData(DataEvent event, IsDataSync dataSync);
// }
//
// public static Type<DataEventHandler> TYPE = new Type<DataEventHandler>();
//
// public IsDataSync target;
//
// @Override
// public Type<DataEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(final DataEventHandler handler) {
// handler.onData(this, target);
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
// @GinModules(AppModule.class)
// public interface AppInjector extends Ginjector {
// AppController getAppController();
//
// MainPresenter getMainPresenter();
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/Presenter.java
// public interface Presenter {
// public void go(final HasWidgets container);
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/service/PercentServiceAsync.java
// public interface PercentServiceAsync extends RestService {
// String PREFERRED_MEDIA_TYPE = "application/vnd.vizpres+json";
//
// @GET
// @Produces(PREFERRED_MEDIA_TYPE)
// void getPercents(MethodCallback<List<PercentValue>> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
| import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;
import com.java33.vizpres.client.event.DataEvent;
import com.java33.vizpres.client.gin.AppInjector;
import com.java33.vizpres.client.presenter.Presenter;
import com.java33.vizpres.client.view.visualization.IsDataSync;
import com.java33.vizpres.shared.service.PercentServiceAsync;
import com.java33.vizpres.shared.model.PercentValue;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.Resource;
import org.fusesource.restygwt.client.RestServiceProxy;
import java.util.List;
import java.util.logging.Logger; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client;
/**
* Coordinate the application's various presenters using GWT's History support.
* The new Activity and Places support in GWT 2.1 would be a better choice for a
* larger application.
*
* @author Jon Buffington
*/
public class AppController implements Presenter, ValueChangeHandler<String> {
private static final Logger logger = Logger.getLogger(AppController.class.getName());
private static final String DEFAULT_TOKEN = "default";
private final EventBus eventBus;
private final AppInjector injector;
private HasWidgets container;
@Inject
public AppController(final EventBus eventBus, final AppInjector injector) {
this.eventBus = eventBus;
this.injector = injector;
bind();
}
/**
* Bind handlers to the application's events.
*/
private void bind() {
History.addValueChangeHandler(this);
eventBus.addHandler(DataEvent.TYPE, new DataEvent.DataEventHandler() { | // Path: src/main/java/com/java33/vizpres/client/event/DataEvent.java
// public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
// public interface DataEventHandler extends EventHandler {
// void onData(DataEvent event, IsDataSync dataSync);
// }
//
// public static Type<DataEventHandler> TYPE = new Type<DataEventHandler>();
//
// public IsDataSync target;
//
// @Override
// public Type<DataEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(final DataEventHandler handler) {
// handler.onData(this, target);
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
// @GinModules(AppModule.class)
// public interface AppInjector extends Ginjector {
// AppController getAppController();
//
// MainPresenter getMainPresenter();
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/Presenter.java
// public interface Presenter {
// public void go(final HasWidgets container);
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/service/PercentServiceAsync.java
// public interface PercentServiceAsync extends RestService {
// String PREFERRED_MEDIA_TYPE = "application/vnd.vizpres+json";
//
// @GET
// @Produces(PREFERRED_MEDIA_TYPE)
// void getPercents(MethodCallback<List<PercentValue>> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
// Path: src/main/java/com/java33/vizpres/client/AppController.java
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;
import com.java33.vizpres.client.event.DataEvent;
import com.java33.vizpres.client.gin.AppInjector;
import com.java33.vizpres.client.presenter.Presenter;
import com.java33.vizpres.client.view.visualization.IsDataSync;
import com.java33.vizpres.shared.service.PercentServiceAsync;
import com.java33.vizpres.shared.model.PercentValue;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.Resource;
import org.fusesource.restygwt.client.RestServiceProxy;
import java.util.List;
import java.util.logging.Logger;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client;
/**
* Coordinate the application's various presenters using GWT's History support.
* The new Activity and Places support in GWT 2.1 would be a better choice for a
* larger application.
*
* @author Jon Buffington
*/
public class AppController implements Presenter, ValueChangeHandler<String> {
private static final Logger logger = Logger.getLogger(AppController.class.getName());
private static final String DEFAULT_TOKEN = "default";
private final EventBus eventBus;
private final AppInjector injector;
private HasWidgets container;
@Inject
public AppController(final EventBus eventBus, final AppInjector injector) {
this.eventBus = eventBus;
this.injector = injector;
bind();
}
/**
* Bind handlers to the application's events.
*/
private void bind() {
History.addValueChangeHandler(this);
eventBus.addHandler(DataEvent.TYPE, new DataEvent.DataEventHandler() { | public void onData(final DataEvent event, final IsDataSync dataSync) { |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/AppController.java | // Path: src/main/java/com/java33/vizpres/client/event/DataEvent.java
// public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
// public interface DataEventHandler extends EventHandler {
// void onData(DataEvent event, IsDataSync dataSync);
// }
//
// public static Type<DataEventHandler> TYPE = new Type<DataEventHandler>();
//
// public IsDataSync target;
//
// @Override
// public Type<DataEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(final DataEventHandler handler) {
// handler.onData(this, target);
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
// @GinModules(AppModule.class)
// public interface AppInjector extends Ginjector {
// AppController getAppController();
//
// MainPresenter getMainPresenter();
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/Presenter.java
// public interface Presenter {
// public void go(final HasWidgets container);
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/service/PercentServiceAsync.java
// public interface PercentServiceAsync extends RestService {
// String PREFERRED_MEDIA_TYPE = "application/vnd.vizpres+json";
//
// @GET
// @Produces(PREFERRED_MEDIA_TYPE)
// void getPercents(MethodCallback<List<PercentValue>> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
| import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;
import com.java33.vizpres.client.event.DataEvent;
import com.java33.vizpres.client.gin.AppInjector;
import com.java33.vizpres.client.presenter.Presenter;
import com.java33.vizpres.client.view.visualization.IsDataSync;
import com.java33.vizpres.shared.service.PercentServiceAsync;
import com.java33.vizpres.shared.model.PercentValue;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.Resource;
import org.fusesource.restygwt.client.RestServiceProxy;
import java.util.List;
import java.util.logging.Logger; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client;
/**
* Coordinate the application's various presenters using GWT's History support.
* The new Activity and Places support in GWT 2.1 would be a better choice for a
* larger application.
*
* @author Jon Buffington
*/
public class AppController implements Presenter, ValueChangeHandler<String> {
private static final Logger logger = Logger.getLogger(AppController.class.getName());
private static final String DEFAULT_TOKEN = "default";
private final EventBus eventBus;
private final AppInjector injector;
private HasWidgets container;
@Inject
public AppController(final EventBus eventBus, final AppInjector injector) {
this.eventBus = eventBus;
this.injector = injector;
bind();
}
/**
* Bind handlers to the application's events.
*/
private void bind() {
History.addValueChangeHandler(this);
eventBus.addHandler(DataEvent.TYPE, new DataEvent.DataEventHandler() {
public void onData(final DataEvent event, final IsDataSync dataSync) {
doRequestData(dataSync);
}
});
}
/**
* Performs the request for data and asynchronously receives the response or failure notice.
* A response's data is pushed to the dataSync.
*
* @param dataSync Is the receiver of a data response's payload.
*/
private void doRequestData(final IsDataSync dataSync) {
final Resource resource = new Resource("/dataset"); | // Path: src/main/java/com/java33/vizpres/client/event/DataEvent.java
// public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
// public interface DataEventHandler extends EventHandler {
// void onData(DataEvent event, IsDataSync dataSync);
// }
//
// public static Type<DataEventHandler> TYPE = new Type<DataEventHandler>();
//
// public IsDataSync target;
//
// @Override
// public Type<DataEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(final DataEventHandler handler) {
// handler.onData(this, target);
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
// @GinModules(AppModule.class)
// public interface AppInjector extends Ginjector {
// AppController getAppController();
//
// MainPresenter getMainPresenter();
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/Presenter.java
// public interface Presenter {
// public void go(final HasWidgets container);
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/service/PercentServiceAsync.java
// public interface PercentServiceAsync extends RestService {
// String PREFERRED_MEDIA_TYPE = "application/vnd.vizpres+json";
//
// @GET
// @Produces(PREFERRED_MEDIA_TYPE)
// void getPercents(MethodCallback<List<PercentValue>> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
// Path: src/main/java/com/java33/vizpres/client/AppController.java
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;
import com.java33.vizpres.client.event.DataEvent;
import com.java33.vizpres.client.gin.AppInjector;
import com.java33.vizpres.client.presenter.Presenter;
import com.java33.vizpres.client.view.visualization.IsDataSync;
import com.java33.vizpres.shared.service.PercentServiceAsync;
import com.java33.vizpres.shared.model.PercentValue;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.Resource;
import org.fusesource.restygwt.client.RestServiceProxy;
import java.util.List;
import java.util.logging.Logger;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client;
/**
* Coordinate the application's various presenters using GWT's History support.
* The new Activity and Places support in GWT 2.1 would be a better choice for a
* larger application.
*
* @author Jon Buffington
*/
public class AppController implements Presenter, ValueChangeHandler<String> {
private static final Logger logger = Logger.getLogger(AppController.class.getName());
private static final String DEFAULT_TOKEN = "default";
private final EventBus eventBus;
private final AppInjector injector;
private HasWidgets container;
@Inject
public AppController(final EventBus eventBus, final AppInjector injector) {
this.eventBus = eventBus;
this.injector = injector;
bind();
}
/**
* Bind handlers to the application's events.
*/
private void bind() {
History.addValueChangeHandler(this);
eventBus.addHandler(DataEvent.TYPE, new DataEvent.DataEventHandler() {
public void onData(final DataEvent event, final IsDataSync dataSync) {
doRequestData(dataSync);
}
});
}
/**
* Performs the request for data and asynchronously receives the response or failure notice.
* A response's data is pushed to the dataSync.
*
* @param dataSync Is the receiver of a data response's payload.
*/
private void doRequestData(final IsDataSync dataSync) {
final Resource resource = new Resource("/dataset"); | final PercentServiceAsync percentServiceAsync = GWT.create(PercentServiceAsync.class); |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/AppController.java | // Path: src/main/java/com/java33/vizpres/client/event/DataEvent.java
// public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
// public interface DataEventHandler extends EventHandler {
// void onData(DataEvent event, IsDataSync dataSync);
// }
//
// public static Type<DataEventHandler> TYPE = new Type<DataEventHandler>();
//
// public IsDataSync target;
//
// @Override
// public Type<DataEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(final DataEventHandler handler) {
// handler.onData(this, target);
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
// @GinModules(AppModule.class)
// public interface AppInjector extends Ginjector {
// AppController getAppController();
//
// MainPresenter getMainPresenter();
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/Presenter.java
// public interface Presenter {
// public void go(final HasWidgets container);
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/service/PercentServiceAsync.java
// public interface PercentServiceAsync extends RestService {
// String PREFERRED_MEDIA_TYPE = "application/vnd.vizpres+json";
//
// @GET
// @Produces(PREFERRED_MEDIA_TYPE)
// void getPercents(MethodCallback<List<PercentValue>> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
| import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;
import com.java33.vizpres.client.event.DataEvent;
import com.java33.vizpres.client.gin.AppInjector;
import com.java33.vizpres.client.presenter.Presenter;
import com.java33.vizpres.client.view.visualization.IsDataSync;
import com.java33.vizpres.shared.service.PercentServiceAsync;
import com.java33.vizpres.shared.model.PercentValue;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.Resource;
import org.fusesource.restygwt.client.RestServiceProxy;
import java.util.List;
import java.util.logging.Logger; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client;
/**
* Coordinate the application's various presenters using GWT's History support.
* The new Activity and Places support in GWT 2.1 would be a better choice for a
* larger application.
*
* @author Jon Buffington
*/
public class AppController implements Presenter, ValueChangeHandler<String> {
private static final Logger logger = Logger.getLogger(AppController.class.getName());
private static final String DEFAULT_TOKEN = "default";
private final EventBus eventBus;
private final AppInjector injector;
private HasWidgets container;
@Inject
public AppController(final EventBus eventBus, final AppInjector injector) {
this.eventBus = eventBus;
this.injector = injector;
bind();
}
/**
* Bind handlers to the application's events.
*/
private void bind() {
History.addValueChangeHandler(this);
eventBus.addHandler(DataEvent.TYPE, new DataEvent.DataEventHandler() {
public void onData(final DataEvent event, final IsDataSync dataSync) {
doRequestData(dataSync);
}
});
}
/**
* Performs the request for data and asynchronously receives the response or failure notice.
* A response's data is pushed to the dataSync.
*
* @param dataSync Is the receiver of a data response's payload.
*/
private void doRequestData(final IsDataSync dataSync) {
final Resource resource = new Resource("/dataset");
final PercentServiceAsync percentServiceAsync = GWT.create(PercentServiceAsync.class);
((RestServiceProxy) percentServiceAsync).setResource(resource); | // Path: src/main/java/com/java33/vizpres/client/event/DataEvent.java
// public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
// public interface DataEventHandler extends EventHandler {
// void onData(DataEvent event, IsDataSync dataSync);
// }
//
// public static Type<DataEventHandler> TYPE = new Type<DataEventHandler>();
//
// public IsDataSync target;
//
// @Override
// public Type<DataEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(final DataEventHandler handler) {
// handler.onData(this, target);
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
// @GinModules(AppModule.class)
// public interface AppInjector extends Ginjector {
// AppController getAppController();
//
// MainPresenter getMainPresenter();
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/Presenter.java
// public interface Presenter {
// public void go(final HasWidgets container);
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/service/PercentServiceAsync.java
// public interface PercentServiceAsync extends RestService {
// String PREFERRED_MEDIA_TYPE = "application/vnd.vizpres+json";
//
// @GET
// @Produces(PREFERRED_MEDIA_TYPE)
// void getPercents(MethodCallback<List<PercentValue>> values);
// }
//
// Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
// Path: src/main/java/com/java33/vizpres/client/AppController.java
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;
import com.java33.vizpres.client.event.DataEvent;
import com.java33.vizpres.client.gin.AppInjector;
import com.java33.vizpres.client.presenter.Presenter;
import com.java33.vizpres.client.view.visualization.IsDataSync;
import com.java33.vizpres.shared.service.PercentServiceAsync;
import com.java33.vizpres.shared.model.PercentValue;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.Resource;
import org.fusesource.restygwt.client.RestServiceProxy;
import java.util.List;
import java.util.logging.Logger;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client;
/**
* Coordinate the application's various presenters using GWT's History support.
* The new Activity and Places support in GWT 2.1 would be a better choice for a
* larger application.
*
* @author Jon Buffington
*/
public class AppController implements Presenter, ValueChangeHandler<String> {
private static final Logger logger = Logger.getLogger(AppController.class.getName());
private static final String DEFAULT_TOKEN = "default";
private final EventBus eventBus;
private final AppInjector injector;
private HasWidgets container;
@Inject
public AppController(final EventBus eventBus, final AppInjector injector) {
this.eventBus = eventBus;
this.injector = injector;
bind();
}
/**
* Bind handlers to the application's events.
*/
private void bind() {
History.addValueChangeHandler(this);
eventBus.addHandler(DataEvent.TYPE, new DataEvent.DataEventHandler() {
public void onData(final DataEvent event, final IsDataSync dataSync) {
doRequestData(dataSync);
}
});
}
/**
* Performs the request for data and asynchronously receives the response or failure notice.
* A response's data is pushed to the dataSync.
*
* @param dataSync Is the receiver of a data response's payload.
*/
private void doRequestData(final IsDataSync dataSync) {
final Resource resource = new Resource("/dataset");
final PercentServiceAsync percentServiceAsync = GWT.create(PercentServiceAsync.class);
((RestServiceProxy) percentServiceAsync).setResource(resource); | percentServiceAsync.getPercents(new MethodCallback<List<PercentValue>>() { |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/view/visualization/CellViz.java | // Path: src/main/java/com/java33/vizpres/client/view/cell/BarCell.java
// public class BarCell extends AbstractCell<PercentValue> {
// /**
// * {@inheritDoc}
// */
// @Override
// public void render(final Context context, final PercentValue value, final SafeHtmlBuilder sb) {
// final int percentage = value.percentage;
// if (percentage >= 0 && percentage <= 100) {
// final StringBuilder tags = new StringBuilder("<div class='java33-barCell' style='width: ")
// .append(percentage)
// .append("%;'>")
// .append(percentage)
// .append("</div>");
// sb.appendHtmlConstant(tags.toString());
// }
// else {
// sb.appendHtmlConstant("<p><strong>Value is out-of-range.</strong></p>");
// }
// }
// }
//
// Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
| import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.uibinder.client.UiFactory;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.java33.vizpres.client.view.cell.BarCell;
import com.java33.vizpres.shared.model.PercentValue; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.view.visualization;
/**
* Is a simple demonstration using a CellList to render a bar chart. The
* CellList uses {@link BarCell} to render the bar.
*
* @author Jon Buffington
*/
public class CellViz extends Composite implements IsDataSync {
interface CellVizUiBinder extends UiBinder<FlowPanel, CellViz> {
}
private final static CellVizUiBinder UIBINDER = GWT.create(CellVizUiBinder.class);
private final String width;
private final String height;
@UiField | // Path: src/main/java/com/java33/vizpres/client/view/cell/BarCell.java
// public class BarCell extends AbstractCell<PercentValue> {
// /**
// * {@inheritDoc}
// */
// @Override
// public void render(final Context context, final PercentValue value, final SafeHtmlBuilder sb) {
// final int percentage = value.percentage;
// if (percentage >= 0 && percentage <= 100) {
// final StringBuilder tags = new StringBuilder("<div class='java33-barCell' style='width: ")
// .append(percentage)
// .append("%;'>")
// .append(percentage)
// .append("</div>");
// sb.appendHtmlConstant(tags.toString());
// }
// else {
// sb.appendHtmlConstant("<p><strong>Value is out-of-range.</strong></p>");
// }
// }
// }
//
// Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
// Path: src/main/java/com/java33/vizpres/client/view/visualization/CellViz.java
import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.uibinder.client.UiFactory;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.java33.vizpres.client.view.cell.BarCell;
import com.java33.vizpres.shared.model.PercentValue;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.view.visualization;
/**
* Is a simple demonstration using a CellList to render a bar chart. The
* CellList uses {@link BarCell} to render the bar.
*
* @author Jon Buffington
*/
public class CellViz extends Composite implements IsDataSync {
interface CellVizUiBinder extends UiBinder<FlowPanel, CellViz> {
}
private final static CellVizUiBinder UIBINDER = GWT.create(CellVizUiBinder.class);
private final String width;
private final String height;
@UiField | CellList<PercentValue> cellList; |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/view/visualization/CellViz.java | // Path: src/main/java/com/java33/vizpres/client/view/cell/BarCell.java
// public class BarCell extends AbstractCell<PercentValue> {
// /**
// * {@inheritDoc}
// */
// @Override
// public void render(final Context context, final PercentValue value, final SafeHtmlBuilder sb) {
// final int percentage = value.percentage;
// if (percentage >= 0 && percentage <= 100) {
// final StringBuilder tags = new StringBuilder("<div class='java33-barCell' style='width: ")
// .append(percentage)
// .append("%;'>")
// .append(percentage)
// .append("</div>");
// sb.appendHtmlConstant(tags.toString());
// }
// else {
// sb.appendHtmlConstant("<p><strong>Value is out-of-range.</strong></p>");
// }
// }
// }
//
// Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
| import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.uibinder.client.UiFactory;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.java33.vizpres.client.view.cell.BarCell;
import com.java33.vizpres.shared.model.PercentValue; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.view.visualization;
/**
* Is a simple demonstration using a CellList to render a bar chart. The
* CellList uses {@link BarCell} to render the bar.
*
* @author Jon Buffington
*/
public class CellViz extends Composite implements IsDataSync {
interface CellVizUiBinder extends UiBinder<FlowPanel, CellViz> {
}
private final static CellVizUiBinder UIBINDER = GWT.create(CellVizUiBinder.class);
private final String width;
private final String height;
@UiField
CellList<PercentValue> cellList;
@UiField
Label infoLabel;
@UiConstructor
public CellViz(final String width, final String height) {
this.width = width;
this.height = height;
initWidget(UIBINDER.createAndBindUi(this));
}
/**
* Create a {@link CellList} instance using a custom factory method. The custom
* factory is required because a CellList must be constructed using an
* instance of its cell type.
*
* @return Returns a CellList that uses {@link BarCell} for rendering values.
*/
@UiFactory
CellList<PercentValue> makeCellList() {
// Create a CellList using the custom BarCell class for rendering and interaction handling. | // Path: src/main/java/com/java33/vizpres/client/view/cell/BarCell.java
// public class BarCell extends AbstractCell<PercentValue> {
// /**
// * {@inheritDoc}
// */
// @Override
// public void render(final Context context, final PercentValue value, final SafeHtmlBuilder sb) {
// final int percentage = value.percentage;
// if (percentage >= 0 && percentage <= 100) {
// final StringBuilder tags = new StringBuilder("<div class='java33-barCell' style='width: ")
// .append(percentage)
// .append("%;'>")
// .append(percentage)
// .append("</div>");
// sb.appendHtmlConstant(tags.toString());
// }
// else {
// sb.appendHtmlConstant("<p><strong>Value is out-of-range.</strong></p>");
// }
// }
// }
//
// Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
// Path: src/main/java/com/java33/vizpres/client/view/visualization/CellViz.java
import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.uibinder.client.UiFactory;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.java33.vizpres.client.view.cell.BarCell;
import com.java33.vizpres.shared.model.PercentValue;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.view.visualization;
/**
* Is a simple demonstration using a CellList to render a bar chart. The
* CellList uses {@link BarCell} to render the bar.
*
* @author Jon Buffington
*/
public class CellViz extends Composite implements IsDataSync {
interface CellVizUiBinder extends UiBinder<FlowPanel, CellViz> {
}
private final static CellVizUiBinder UIBINDER = GWT.create(CellVizUiBinder.class);
private final String width;
private final String height;
@UiField
CellList<PercentValue> cellList;
@UiField
Label infoLabel;
@UiConstructor
public CellViz(final String width, final String height) {
this.width = width;
this.height = height;
initWidget(UIBINDER.createAndBindUi(this));
}
/**
* Create a {@link CellList} instance using a custom factory method. The custom
* factory is required because a CellList must be constructed using an
* instance of its cell type.
*
* @return Returns a CellList that uses {@link BarCell} for rendering values.
*/
@UiFactory
CellList<PercentValue> makeCellList() {
// Create a CellList using the custom BarCell class for rendering and interaction handling. | final CellList<PercentValue> cellList = new CellList<PercentValue>(new BarCell()); |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/view/visualization/GoogleCharts.java | // Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
| import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.visualization.client.AbstractDataTable;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.visualizations.corechart.*;
import com.java33.vizpres.shared.model.PercentValue;
import java.util.Collections;
import java.util.List; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.view.visualization;
/**
* Is a simple demonstration using the Google Chart tools to render a bar chart. Lots
* of code was spilled in an attempt to wrangle the {@link BarChart}.
*
* @author Jon Buffington
*/
public class GoogleCharts extends Composite implements IsDataSync {
private final FlowPanel root = new FlowPanel();
private final int width;
private final int height;
private CoreChart chart;
@UiConstructor
public GoogleCharts(final int width, final int height) {
this.width = width;
this.height = height;
initWidget(root);
VisualizationUtils.loadVisualizationApi(new Runnable() {
@Override
public void run() {
GoogleCharts.this.chart = makeChart();
root.add(chart);
}
}, CoreChart.PACKAGE);
}
protected CoreChart makeChart() { | // Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
// Path: src/main/java/com/java33/vizpres/client/view/visualization/GoogleCharts.java
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.visualization.client.AbstractDataTable;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.visualizations.corechart.*;
import com.java33.vizpres.shared.model.PercentValue;
import java.util.Collections;
import java.util.List;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.view.visualization;
/**
* Is a simple demonstration using the Google Chart tools to render a bar chart. Lots
* of code was spilled in an attempt to wrangle the {@link BarChart}.
*
* @author Jon Buffington
*/
public class GoogleCharts extends Composite implements IsDataSync {
private final FlowPanel root = new FlowPanel();
private final int width;
private final int height;
private CoreChart chart;
@UiConstructor
public GoogleCharts(final int width, final int height) {
this.width = width;
this.height = height;
initWidget(root);
VisualizationUtils.loadVisualizationApi(new Runnable() {
@Override
public void run() {
GoogleCharts.this.chart = makeChart();
root.add(chart);
}
}, CoreChart.PACKAGE);
}
protected CoreChart makeChart() { | return new BarChart(makeDataTable(Collections.<PercentValue>emptyList()), makeOptions(width, height)); |
jonbuffington/vizpres | src/test/java/com/java33/vizpres/client/ExampleGwtTC.java | // Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
// @GinModules(AppModule.class)
// public interface AppInjector extends Ginjector {
// AppController getAppController();
//
// MainPresenter getMainPresenter();
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
// public class MainPresenter implements Presenter {
// private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
//
// public interface Display extends IsWidget, IsDataSync {
// HasClickHandlers getRefreshButton();
// }
//
// private final EventBus eventBus;
// private final Display display;
//
// @Inject
// public MainPresenter(final EventBus eventBus, final Display view) {
// this.eventBus = eventBus;
// display = view;
// }
//
// /**
// * Binds the refresh button click into a data request bus event.
// */
// protected void bind() {
// display.getRefreshButton().addClickHandler(new ClickHandler() {
// public void onClick(final ClickEvent event) {
// logger.fine("Request data from server using the event bus.");
// final DataEvent dataEvent = GWT.create(DataEvent.class);
// dataEvent.target = display;
// eventBus.fireEvent(dataEvent);
// }
// });
// }
//
// public void go(final HasWidgets container) {
// bind();
// container.clear();
// container.add(display.asWidget());
// }
//
// /**
// * Get the target's view instance. This method is primarily used by tests.
// *
// * @return Return the target's view.
// */
// public Display getDisplay() {
// return display;
// }
// }
| import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.ui.Button;
import com.java33.vizpres.client.gin.AppInjector;
import com.java33.vizpres.client.presenter.MainPresenter; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client;
/**
* Is an example Application (GWTTestCase) application test class.
* <p>Note: The file avoids the default "GwtTest_.java" naming pattern
* to avoid being run by the default plugin configuration as this test
* case is included in the GwtTestSuite.</p>
*/
public class ExampleGwtTC extends GWTTestCase {
private MainPresenter presenter;
private Messages messages;
/**
* Return the fully-qualified name of the GWT module. This is the glue
* that tells the GWTTestCase runner which GWT module to use.
*
* @see com.google.gwt.junit.client.GWTTestCase#getModuleName()
*/
public String getModuleName() {
return "com.java33.vizpres.IntegrationTestModule";
}
@Override
public void gwtSetUp() { | // Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
// @GinModules(AppModule.class)
// public interface AppInjector extends Ginjector {
// AppController getAppController();
//
// MainPresenter getMainPresenter();
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
// public class MainPresenter implements Presenter {
// private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
//
// public interface Display extends IsWidget, IsDataSync {
// HasClickHandlers getRefreshButton();
// }
//
// private final EventBus eventBus;
// private final Display display;
//
// @Inject
// public MainPresenter(final EventBus eventBus, final Display view) {
// this.eventBus = eventBus;
// display = view;
// }
//
// /**
// * Binds the refresh button click into a data request bus event.
// */
// protected void bind() {
// display.getRefreshButton().addClickHandler(new ClickHandler() {
// public void onClick(final ClickEvent event) {
// logger.fine("Request data from server using the event bus.");
// final DataEvent dataEvent = GWT.create(DataEvent.class);
// dataEvent.target = display;
// eventBus.fireEvent(dataEvent);
// }
// });
// }
//
// public void go(final HasWidgets container) {
// bind();
// container.clear();
// container.add(display.asWidget());
// }
//
// /**
// * Get the target's view instance. This method is primarily used by tests.
// *
// * @return Return the target's view.
// */
// public Display getDisplay() {
// return display;
// }
// }
// Path: src/test/java/com/java33/vizpres/client/ExampleGwtTC.java
import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.ui.Button;
import com.java33.vizpres.client.gin.AppInjector;
import com.java33.vizpres.client.presenter.MainPresenter;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client;
/**
* Is an example Application (GWTTestCase) application test class.
* <p>Note: The file avoids the default "GwtTest_.java" naming pattern
* to avoid being run by the default plugin configuration as this test
* case is included in the GwtTestSuite.</p>
*/
public class ExampleGwtTC extends GWTTestCase {
private MainPresenter presenter;
private Messages messages;
/**
* Return the fully-qualified name of the GWT module. This is the glue
* that tells the GWTTestCase runner which GWT module to use.
*
* @see com.google.gwt.junit.client.GWTTestCase#getModuleName()
*/
public String getModuleName() {
return "com.java33.vizpres.IntegrationTestModule";
}
@Override
public void gwtSetUp() { | final AppInjector injector = GWT.create(AppInjector.class); |
jonbuffington/vizpres | src/test/java/com/java33/vizpres/logic/ExampleTest.java | // Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
// public class MainPresenter implements Presenter {
// private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
//
// public interface Display extends IsWidget, IsDataSync {
// HasClickHandlers getRefreshButton();
// }
//
// private final EventBus eventBus;
// private final Display display;
//
// @Inject
// public MainPresenter(final EventBus eventBus, final Display view) {
// this.eventBus = eventBus;
// display = view;
// }
//
// /**
// * Binds the refresh button click into a data request bus event.
// */
// protected void bind() {
// display.getRefreshButton().addClickHandler(new ClickHandler() {
// public void onClick(final ClickEvent event) {
// logger.fine("Request data from server using the event bus.");
// final DataEvent dataEvent = GWT.create(DataEvent.class);
// dataEvent.target = display;
// eventBus.fireEvent(dataEvent);
// }
// });
// }
//
// public void go(final HasWidgets container) {
// bind();
// container.clear();
// container.add(display.asWidget());
// }
//
// /**
// * Get the target's view instance. This method is primarily used by tests.
// *
// * @return Return the target's view.
// */
// public Display getDisplay() {
// return display;
// }
// }
| import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.java33.vizpres.client.presenter.MainPresenter;
import org.junit.Assert;
import org.junit.Test; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.logic;
/**
* Is an example logic (JRE) logic test class using JUnit.
*/
public class ExampleTest {
private final Injector injector;
public ExampleTest() {
// Create an injection context that mocks the concrete view dependencies
// to be used below in the tests.
injector = Guice.createInjector(new MockModule());
}
@Test
public void testPresenterInjection() { | // Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
// public class MainPresenter implements Presenter {
// private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
//
// public interface Display extends IsWidget, IsDataSync {
// HasClickHandlers getRefreshButton();
// }
//
// private final EventBus eventBus;
// private final Display display;
//
// @Inject
// public MainPresenter(final EventBus eventBus, final Display view) {
// this.eventBus = eventBus;
// display = view;
// }
//
// /**
// * Binds the refresh button click into a data request bus event.
// */
// protected void bind() {
// display.getRefreshButton().addClickHandler(new ClickHandler() {
// public void onClick(final ClickEvent event) {
// logger.fine("Request data from server using the event bus.");
// final DataEvent dataEvent = GWT.create(DataEvent.class);
// dataEvent.target = display;
// eventBus.fireEvent(dataEvent);
// }
// });
// }
//
// public void go(final HasWidgets container) {
// bind();
// container.clear();
// container.add(display.asWidget());
// }
//
// /**
// * Get the target's view instance. This method is primarily used by tests.
// *
// * @return Return the target's view.
// */
// public Display getDisplay() {
// return display;
// }
// }
// Path: src/test/java/com/java33/vizpres/logic/ExampleTest.java
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.java33.vizpres.client.presenter.MainPresenter;
import org.junit.Assert;
import org.junit.Test;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.logic;
/**
* Is an example logic (JRE) logic test class using JUnit.
*/
public class ExampleTest {
private final Injector injector;
public ExampleTest() {
// Create an injection context that mocks the concrete view dependencies
// to be used below in the tests.
injector = Guice.createInjector(new MockModule());
}
@Test
public void testPresenterInjection() { | final MainPresenter defaultPresenter = injector.getInstance(MainPresenter.class); |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/VizPres.java | // Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
// @GinModules(AppModule.class)
// public interface AppInjector extends Ginjector {
// AppController getAppController();
//
// MainPresenter getMainPresenter();
// }
| import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.java33.vizpres.client.gin.AppInjector;
import java.util.logging.Logger; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*
* @author Jon Buffington
*/
public class VizPres implements EntryPoint {
private static final Logger logger = Logger.getLogger(VizPres.class.getName());
/**
* This is the entry point method.
*/
public void onModuleLoad() { | // Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
// @GinModules(AppModule.class)
// public interface AppInjector extends Ginjector {
// AppController getAppController();
//
// MainPresenter getMainPresenter();
// }
// Path: src/main/java/com/java33/vizpres/client/VizPres.java
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.java33.vizpres.client.gin.AppInjector;
import java.util.logging.Logger;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*
* @author Jon Buffington
*/
public class VizPres implements EntryPoint {
private static final Logger logger = Logger.getLogger(VizPres.class.getName());
/**
* This is the entry point method.
*/
public void onModuleLoad() { | final AppInjector injector = GWT.create(AppInjector.class); |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/gin/AppModule.java | // Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
// public class MainPresenter implements Presenter {
// private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
//
// public interface Display extends IsWidget, IsDataSync {
// HasClickHandlers getRefreshButton();
// }
//
// private final EventBus eventBus;
// private final Display display;
//
// @Inject
// public MainPresenter(final EventBus eventBus, final Display view) {
// this.eventBus = eventBus;
// display = view;
// }
//
// /**
// * Binds the refresh button click into a data request bus event.
// */
// protected void bind() {
// display.getRefreshButton().addClickHandler(new ClickHandler() {
// public void onClick(final ClickEvent event) {
// logger.fine("Request data from server using the event bus.");
// final DataEvent dataEvent = GWT.create(DataEvent.class);
// dataEvent.target = display;
// eventBus.fireEvent(dataEvent);
// }
// });
// }
//
// public void go(final HasWidgets container) {
// bind();
// container.clear();
// container.add(display.asWidget());
// }
//
// /**
// * Get the target's view instance. This method is primarily used by tests.
// *
// * @return Return the target's view.
// */
// public Display getDisplay() {
// return display;
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/MainView.java
// public class MainView extends Composite implements MainPresenter.Display {
// private static final Messages messages = GWT.create(Messages.class);
//
// interface MainViewUiBinder extends UiBinder<DockLayoutPanel, MainView> {
// }
//
// private static MainViewUiBinder BINDER = GWT.create(MainViewUiBinder.class);
//
// @UiField
// Label titleText;
// @UiField
// Label copyrightText;
// @UiField
// Button refreshButton;
// @UiField
// GoogleCharts googleChartBaseView;
// @UiField
// CellViz cellBasedView;
// @UiField
// CanvasViz canvasBasedView;
// @UiField
// RaphaelViz raphaelBasedView;
//
// public MainView() {
// initWidget(BINDER.createAndBindUi(this));
//
// titleText.setText(messages.title());
// copyrightText.setText(messages.copyright());
// refreshButton.setText(messages.refresh());
// }
//
// @Override
// public HasClickHandlers getRefreshButton() {
// return refreshButton;
// }
//
// @Override
// public void setData(final List<PercentValue> values) {
// // Walk the sub-views and set their data.
// cellBasedView.setData(values);
// canvasBasedView.setData(values);
// raphaelBasedView.setData(values);
// googleChartBaseView.setData(values);
// }
// }
| import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.inject.client.AbstractGinModule;
import com.google.inject.Singleton;
import com.java33.vizpres.client.presenter.MainPresenter;
import com.java33.vizpres.client.view.MainView; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.gin;
public class AppModule extends AbstractGinModule {
@Override
protected void configure() {
// Support injecting the HandlerManager into the Application scope.
bind(EventBus.class).to(SimpleEventBus.class).in(Singleton.class);
// Bind the main presenter's display to an instance of its UI view. | // Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
// public class MainPresenter implements Presenter {
// private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
//
// public interface Display extends IsWidget, IsDataSync {
// HasClickHandlers getRefreshButton();
// }
//
// private final EventBus eventBus;
// private final Display display;
//
// @Inject
// public MainPresenter(final EventBus eventBus, final Display view) {
// this.eventBus = eventBus;
// display = view;
// }
//
// /**
// * Binds the refresh button click into a data request bus event.
// */
// protected void bind() {
// display.getRefreshButton().addClickHandler(new ClickHandler() {
// public void onClick(final ClickEvent event) {
// logger.fine("Request data from server using the event bus.");
// final DataEvent dataEvent = GWT.create(DataEvent.class);
// dataEvent.target = display;
// eventBus.fireEvent(dataEvent);
// }
// });
// }
//
// public void go(final HasWidgets container) {
// bind();
// container.clear();
// container.add(display.asWidget());
// }
//
// /**
// * Get the target's view instance. This method is primarily used by tests.
// *
// * @return Return the target's view.
// */
// public Display getDisplay() {
// return display;
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/MainView.java
// public class MainView extends Composite implements MainPresenter.Display {
// private static final Messages messages = GWT.create(Messages.class);
//
// interface MainViewUiBinder extends UiBinder<DockLayoutPanel, MainView> {
// }
//
// private static MainViewUiBinder BINDER = GWT.create(MainViewUiBinder.class);
//
// @UiField
// Label titleText;
// @UiField
// Label copyrightText;
// @UiField
// Button refreshButton;
// @UiField
// GoogleCharts googleChartBaseView;
// @UiField
// CellViz cellBasedView;
// @UiField
// CanvasViz canvasBasedView;
// @UiField
// RaphaelViz raphaelBasedView;
//
// public MainView() {
// initWidget(BINDER.createAndBindUi(this));
//
// titleText.setText(messages.title());
// copyrightText.setText(messages.copyright());
// refreshButton.setText(messages.refresh());
// }
//
// @Override
// public HasClickHandlers getRefreshButton() {
// return refreshButton;
// }
//
// @Override
// public void setData(final List<PercentValue> values) {
// // Walk the sub-views and set their data.
// cellBasedView.setData(values);
// canvasBasedView.setData(values);
// raphaelBasedView.setData(values);
// googleChartBaseView.setData(values);
// }
// }
// Path: src/main/java/com/java33/vizpres/client/gin/AppModule.java
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.inject.client.AbstractGinModule;
import com.google.inject.Singleton;
import com.java33.vizpres.client.presenter.MainPresenter;
import com.java33.vizpres.client.view.MainView;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.gin;
public class AppModule extends AbstractGinModule {
@Override
protected void configure() {
// Support injecting the HandlerManager into the Application scope.
bind(EventBus.class).to(SimpleEventBus.class).in(Singleton.class);
// Bind the main presenter's display to an instance of its UI view. | bind(MainPresenter.Display.class).to(MainView.class); |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/gin/AppModule.java | // Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
// public class MainPresenter implements Presenter {
// private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
//
// public interface Display extends IsWidget, IsDataSync {
// HasClickHandlers getRefreshButton();
// }
//
// private final EventBus eventBus;
// private final Display display;
//
// @Inject
// public MainPresenter(final EventBus eventBus, final Display view) {
// this.eventBus = eventBus;
// display = view;
// }
//
// /**
// * Binds the refresh button click into a data request bus event.
// */
// protected void bind() {
// display.getRefreshButton().addClickHandler(new ClickHandler() {
// public void onClick(final ClickEvent event) {
// logger.fine("Request data from server using the event bus.");
// final DataEvent dataEvent = GWT.create(DataEvent.class);
// dataEvent.target = display;
// eventBus.fireEvent(dataEvent);
// }
// });
// }
//
// public void go(final HasWidgets container) {
// bind();
// container.clear();
// container.add(display.asWidget());
// }
//
// /**
// * Get the target's view instance. This method is primarily used by tests.
// *
// * @return Return the target's view.
// */
// public Display getDisplay() {
// return display;
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/MainView.java
// public class MainView extends Composite implements MainPresenter.Display {
// private static final Messages messages = GWT.create(Messages.class);
//
// interface MainViewUiBinder extends UiBinder<DockLayoutPanel, MainView> {
// }
//
// private static MainViewUiBinder BINDER = GWT.create(MainViewUiBinder.class);
//
// @UiField
// Label titleText;
// @UiField
// Label copyrightText;
// @UiField
// Button refreshButton;
// @UiField
// GoogleCharts googleChartBaseView;
// @UiField
// CellViz cellBasedView;
// @UiField
// CanvasViz canvasBasedView;
// @UiField
// RaphaelViz raphaelBasedView;
//
// public MainView() {
// initWidget(BINDER.createAndBindUi(this));
//
// titleText.setText(messages.title());
// copyrightText.setText(messages.copyright());
// refreshButton.setText(messages.refresh());
// }
//
// @Override
// public HasClickHandlers getRefreshButton() {
// return refreshButton;
// }
//
// @Override
// public void setData(final List<PercentValue> values) {
// // Walk the sub-views and set their data.
// cellBasedView.setData(values);
// canvasBasedView.setData(values);
// raphaelBasedView.setData(values);
// googleChartBaseView.setData(values);
// }
// }
| import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.inject.client.AbstractGinModule;
import com.google.inject.Singleton;
import com.java33.vizpres.client.presenter.MainPresenter;
import com.java33.vizpres.client.view.MainView; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.gin;
public class AppModule extends AbstractGinModule {
@Override
protected void configure() {
// Support injecting the HandlerManager into the Application scope.
bind(EventBus.class).to(SimpleEventBus.class).in(Singleton.class);
// Bind the main presenter's display to an instance of its UI view. | // Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
// public class MainPresenter implements Presenter {
// private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
//
// public interface Display extends IsWidget, IsDataSync {
// HasClickHandlers getRefreshButton();
// }
//
// private final EventBus eventBus;
// private final Display display;
//
// @Inject
// public MainPresenter(final EventBus eventBus, final Display view) {
// this.eventBus = eventBus;
// display = view;
// }
//
// /**
// * Binds the refresh button click into a data request bus event.
// */
// protected void bind() {
// display.getRefreshButton().addClickHandler(new ClickHandler() {
// public void onClick(final ClickEvent event) {
// logger.fine("Request data from server using the event bus.");
// final DataEvent dataEvent = GWT.create(DataEvent.class);
// dataEvent.target = display;
// eventBus.fireEvent(dataEvent);
// }
// });
// }
//
// public void go(final HasWidgets container) {
// bind();
// container.clear();
// container.add(display.asWidget());
// }
//
// /**
// * Get the target's view instance. This method is primarily used by tests.
// *
// * @return Return the target's view.
// */
// public Display getDisplay() {
// return display;
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/MainView.java
// public class MainView extends Composite implements MainPresenter.Display {
// private static final Messages messages = GWT.create(Messages.class);
//
// interface MainViewUiBinder extends UiBinder<DockLayoutPanel, MainView> {
// }
//
// private static MainViewUiBinder BINDER = GWT.create(MainViewUiBinder.class);
//
// @UiField
// Label titleText;
// @UiField
// Label copyrightText;
// @UiField
// Button refreshButton;
// @UiField
// GoogleCharts googleChartBaseView;
// @UiField
// CellViz cellBasedView;
// @UiField
// CanvasViz canvasBasedView;
// @UiField
// RaphaelViz raphaelBasedView;
//
// public MainView() {
// initWidget(BINDER.createAndBindUi(this));
//
// titleText.setText(messages.title());
// copyrightText.setText(messages.copyright());
// refreshButton.setText(messages.refresh());
// }
//
// @Override
// public HasClickHandlers getRefreshButton() {
// return refreshButton;
// }
//
// @Override
// public void setData(final List<PercentValue> values) {
// // Walk the sub-views and set their data.
// cellBasedView.setData(values);
// canvasBasedView.setData(values);
// raphaelBasedView.setData(values);
// googleChartBaseView.setData(values);
// }
// }
// Path: src/main/java/com/java33/vizpres/client/gin/AppModule.java
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.inject.client.AbstractGinModule;
import com.google.inject.Singleton;
import com.java33.vizpres.client.presenter.MainPresenter;
import com.java33.vizpres.client.view.MainView;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.gin;
public class AppModule extends AbstractGinModule {
@Override
protected void configure() {
// Support injecting the HandlerManager into the Application scope.
bind(EventBus.class).to(SimpleEventBus.class).in(Singleton.class);
// Bind the main presenter's display to an instance of its UI view. | bind(MainPresenter.Display.class).to(MainView.class); |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/shared/service/PercentServiceAsync.java | // Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
| import com.java33.vizpres.shared.model.PercentValue;
import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.RestService;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import java.util.List; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.shared.service;
/**
* Could be the most complex ReST-based service interface to date. No. Maybe not.
*
* @author Jon Buffington
*/
public interface PercentServiceAsync extends RestService {
String PREFERRED_MEDIA_TYPE = "application/vnd.vizpres+json";
@GET
@Produces(PREFERRED_MEDIA_TYPE) | // Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
// Path: src/main/java/com/java33/vizpres/shared/service/PercentServiceAsync.java
import com.java33.vizpres.shared.model.PercentValue;
import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.RestService;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import java.util.List;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.shared.service;
/**
* Could be the most complex ReST-based service interface to date. No. Maybe not.
*
* @author Jon Buffington
*/
public interface PercentServiceAsync extends RestService {
String PREFERRED_MEDIA_TYPE = "application/vnd.vizpres+json";
@GET
@Produces(PREFERRED_MEDIA_TYPE) | void getPercents(MethodCallback<List<PercentValue>> values); |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java | // Path: src/main/java/com/java33/vizpres/client/event/DataEvent.java
// public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
// public interface DataEventHandler extends EventHandler {
// void onData(DataEvent event, IsDataSync dataSync);
// }
//
// public static Type<DataEventHandler> TYPE = new Type<DataEventHandler>();
//
// public IsDataSync target;
//
// @Override
// public Type<DataEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(final DataEventHandler handler) {
// handler.onData(this, target);
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
| import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.inject.Inject;
import com.java33.vizpres.client.event.DataEvent;
import com.java33.vizpres.client.view.visualization.IsDataSync;
import java.util.logging.Logger; |
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.presenter;
/**
* Is the presenter for the primary display.
*
* @author Jon Buffington
*/
public class MainPresenter implements Presenter {
private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
| // Path: src/main/java/com/java33/vizpres/client/event/DataEvent.java
// public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
// public interface DataEventHandler extends EventHandler {
// void onData(DataEvent event, IsDataSync dataSync);
// }
//
// public static Type<DataEventHandler> TYPE = new Type<DataEventHandler>();
//
// public IsDataSync target;
//
// @Override
// public Type<DataEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(final DataEventHandler handler) {
// handler.onData(this, target);
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
// Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.inject.Inject;
import com.java33.vizpres.client.event.DataEvent;
import com.java33.vizpres.client.view.visualization.IsDataSync;
import java.util.logging.Logger;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.presenter;
/**
* Is the presenter for the primary display.
*
* @author Jon Buffington
*/
public class MainPresenter implements Presenter {
private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
| public interface Display extends IsWidget, IsDataSync { |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java | // Path: src/main/java/com/java33/vizpres/client/event/DataEvent.java
// public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
// public interface DataEventHandler extends EventHandler {
// void onData(DataEvent event, IsDataSync dataSync);
// }
//
// public static Type<DataEventHandler> TYPE = new Type<DataEventHandler>();
//
// public IsDataSync target;
//
// @Override
// public Type<DataEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(final DataEventHandler handler) {
// handler.onData(this, target);
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
| import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.inject.Inject;
import com.java33.vizpres.client.event.DataEvent;
import com.java33.vizpres.client.view.visualization.IsDataSync;
import java.util.logging.Logger; |
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.presenter;
/**
* Is the presenter for the primary display.
*
* @author Jon Buffington
*/
public class MainPresenter implements Presenter {
private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
public interface Display extends IsWidget, IsDataSync {
HasClickHandlers getRefreshButton();
}
private final EventBus eventBus;
private final Display display;
@Inject
public MainPresenter(final EventBus eventBus, final Display view) {
this.eventBus = eventBus;
display = view;
}
/**
* Binds the refresh button click into a data request bus event.
*/
protected void bind() {
display.getRefreshButton().addClickHandler(new ClickHandler() {
public void onClick(final ClickEvent event) {
logger.fine("Request data from server using the event bus."); | // Path: src/main/java/com/java33/vizpres/client/event/DataEvent.java
// public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
// public interface DataEventHandler extends EventHandler {
// void onData(DataEvent event, IsDataSync dataSync);
// }
//
// public static Type<DataEventHandler> TYPE = new Type<DataEventHandler>();
//
// public IsDataSync target;
//
// @Override
// public Type<DataEventHandler> getAssociatedType() {
// return TYPE;
// }
//
// @Override
// protected void dispatch(final DataEventHandler handler) {
// handler.onData(this, target);
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
// Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.inject.Inject;
import com.java33.vizpres.client.event.DataEvent;
import com.java33.vizpres.client.view.visualization.IsDataSync;
import java.util.logging.Logger;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.presenter;
/**
* Is the presenter for the primary display.
*
* @author Jon Buffington
*/
public class MainPresenter implements Presenter {
private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
public interface Display extends IsWidget, IsDataSync {
HasClickHandlers getRefreshButton();
}
private final EventBus eventBus;
private final Display display;
@Inject
public MainPresenter(final EventBus eventBus, final Display view) {
this.eventBus = eventBus;
display = view;
}
/**
* Binds the refresh button click into a data request bus event.
*/
protected void bind() {
display.getRefreshButton().addClickHandler(new ClickHandler() {
public void onClick(final ClickEvent event) {
logger.fine("Request data from server using the event bus."); | final DataEvent dataEvent = GWT.create(DataEvent.class); |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/gin/AppInjector.java | // Path: src/main/java/com/java33/vizpres/client/AppController.java
// public class AppController implements Presenter, ValueChangeHandler<String> {
// private static final Logger logger = Logger.getLogger(AppController.class.getName());
//
// private static final String DEFAULT_TOKEN = "default";
// private final EventBus eventBus;
// private final AppInjector injector;
// private HasWidgets container;
//
// @Inject
// public AppController(final EventBus eventBus, final AppInjector injector) {
// this.eventBus = eventBus;
// this.injector = injector;
// bind();
// }
//
// /**
// * Bind handlers to the application's events.
// */
// private void bind() {
// History.addValueChangeHandler(this);
//
// eventBus.addHandler(DataEvent.TYPE, new DataEvent.DataEventHandler() {
// public void onData(final DataEvent event, final IsDataSync dataSync) {
// doRequestData(dataSync);
// }
// });
//
// }
//
// /**
// * Performs the request for data and asynchronously receives the response or failure notice.
// * A response's data is pushed to the dataSync.
// *
// * @param dataSync Is the receiver of a data response's payload.
// */
// private void doRequestData(final IsDataSync dataSync) {
// final Resource resource = new Resource("/dataset");
// final PercentServiceAsync percentServiceAsync = GWT.create(PercentServiceAsync.class);
// ((RestServiceProxy) percentServiceAsync).setResource(resource);
// percentServiceAsync.getPercents(new MethodCallback<List<PercentValue>>() {
// @Override
// public void onFailure(final Method method, final Throwable throwable) {
// logger.warning(throwable.toString());
// }
//
// @Override
// public void onSuccess(final Method method, final List<PercentValue> values) {
// logger.fine(values.toString());
// dataSync.setData(values);
// }
// });
//
// // History.newItem(EXAMPLE_TOKEN);
// }
//
// /**
// * Capture the desired container and pump the history value.
// */
// public void go(final HasWidgets container) {
// this.container = container;
//
// if ("".equals(History.getToken())) {
// History.newItem(DEFAULT_TOKEN);
// }
// else {
// History.fireCurrentHistoryState();
// }
// }
//
// /**
// * Delegate the application state handling to the appropriate target.
// */
// public void onValueChange(final ValueChangeEvent<String> event) {
// final String token = event.getValue();
//
// if (token != null) {
// Presenter presenter = null;
//
// if (token.equals(DEFAULT_TOKEN)) {
// presenter = injector.getMainPresenter();
// }
//
// if (presenter != null) {
// // Pass the container to the current target.
// presenter.go(container);
// }
// }
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
// public class MainPresenter implements Presenter {
// private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
//
// public interface Display extends IsWidget, IsDataSync {
// HasClickHandlers getRefreshButton();
// }
//
// private final EventBus eventBus;
// private final Display display;
//
// @Inject
// public MainPresenter(final EventBus eventBus, final Display view) {
// this.eventBus = eventBus;
// display = view;
// }
//
// /**
// * Binds the refresh button click into a data request bus event.
// */
// protected void bind() {
// display.getRefreshButton().addClickHandler(new ClickHandler() {
// public void onClick(final ClickEvent event) {
// logger.fine("Request data from server using the event bus.");
// final DataEvent dataEvent = GWT.create(DataEvent.class);
// dataEvent.target = display;
// eventBus.fireEvent(dataEvent);
// }
// });
// }
//
// public void go(final HasWidgets container) {
// bind();
// container.clear();
// container.add(display.asWidget());
// }
//
// /**
// * Get the target's view instance. This method is primarily used by tests.
// *
// * @return Return the target's view.
// */
// public Display getDisplay() {
// return display;
// }
// }
| import com.google.gwt.inject.client.GinModules;
import com.google.gwt.inject.client.Ginjector;
import com.java33.vizpres.client.AppController;
import com.java33.vizpres.client.presenter.MainPresenter; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.gin;
/**
* This interface is only used to generate top-level instances in the
* AppModule scope. This approach is used to overcome the lack of Java
* reflection in GWT's emulation.
*
* @author Jon Buffington
*/
@GinModules(AppModule.class)
public interface AppInjector extends Ginjector { | // Path: src/main/java/com/java33/vizpres/client/AppController.java
// public class AppController implements Presenter, ValueChangeHandler<String> {
// private static final Logger logger = Logger.getLogger(AppController.class.getName());
//
// private static final String DEFAULT_TOKEN = "default";
// private final EventBus eventBus;
// private final AppInjector injector;
// private HasWidgets container;
//
// @Inject
// public AppController(final EventBus eventBus, final AppInjector injector) {
// this.eventBus = eventBus;
// this.injector = injector;
// bind();
// }
//
// /**
// * Bind handlers to the application's events.
// */
// private void bind() {
// History.addValueChangeHandler(this);
//
// eventBus.addHandler(DataEvent.TYPE, new DataEvent.DataEventHandler() {
// public void onData(final DataEvent event, final IsDataSync dataSync) {
// doRequestData(dataSync);
// }
// });
//
// }
//
// /**
// * Performs the request for data and asynchronously receives the response or failure notice.
// * A response's data is pushed to the dataSync.
// *
// * @param dataSync Is the receiver of a data response's payload.
// */
// private void doRequestData(final IsDataSync dataSync) {
// final Resource resource = new Resource("/dataset");
// final PercentServiceAsync percentServiceAsync = GWT.create(PercentServiceAsync.class);
// ((RestServiceProxy) percentServiceAsync).setResource(resource);
// percentServiceAsync.getPercents(new MethodCallback<List<PercentValue>>() {
// @Override
// public void onFailure(final Method method, final Throwable throwable) {
// logger.warning(throwable.toString());
// }
//
// @Override
// public void onSuccess(final Method method, final List<PercentValue> values) {
// logger.fine(values.toString());
// dataSync.setData(values);
// }
// });
//
// // History.newItem(EXAMPLE_TOKEN);
// }
//
// /**
// * Capture the desired container and pump the history value.
// */
// public void go(final HasWidgets container) {
// this.container = container;
//
// if ("".equals(History.getToken())) {
// History.newItem(DEFAULT_TOKEN);
// }
// else {
// History.fireCurrentHistoryState();
// }
// }
//
// /**
// * Delegate the application state handling to the appropriate target.
// */
// public void onValueChange(final ValueChangeEvent<String> event) {
// final String token = event.getValue();
//
// if (token != null) {
// Presenter presenter = null;
//
// if (token.equals(DEFAULT_TOKEN)) {
// presenter = injector.getMainPresenter();
// }
//
// if (presenter != null) {
// // Pass the container to the current target.
// presenter.go(container);
// }
// }
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
// public class MainPresenter implements Presenter {
// private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
//
// public interface Display extends IsWidget, IsDataSync {
// HasClickHandlers getRefreshButton();
// }
//
// private final EventBus eventBus;
// private final Display display;
//
// @Inject
// public MainPresenter(final EventBus eventBus, final Display view) {
// this.eventBus = eventBus;
// display = view;
// }
//
// /**
// * Binds the refresh button click into a data request bus event.
// */
// protected void bind() {
// display.getRefreshButton().addClickHandler(new ClickHandler() {
// public void onClick(final ClickEvent event) {
// logger.fine("Request data from server using the event bus.");
// final DataEvent dataEvent = GWT.create(DataEvent.class);
// dataEvent.target = display;
// eventBus.fireEvent(dataEvent);
// }
// });
// }
//
// public void go(final HasWidgets container) {
// bind();
// container.clear();
// container.add(display.asWidget());
// }
//
// /**
// * Get the target's view instance. This method is primarily used by tests.
// *
// * @return Return the target's view.
// */
// public Display getDisplay() {
// return display;
// }
// }
// Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
import com.google.gwt.inject.client.GinModules;
import com.google.gwt.inject.client.Ginjector;
import com.java33.vizpres.client.AppController;
import com.java33.vizpres.client.presenter.MainPresenter;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.gin;
/**
* This interface is only used to generate top-level instances in the
* AppModule scope. This approach is used to overcome the lack of Java
* reflection in GWT's emulation.
*
* @author Jon Buffington
*/
@GinModules(AppModule.class)
public interface AppInjector extends Ginjector { | AppController getAppController(); |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/gin/AppInjector.java | // Path: src/main/java/com/java33/vizpres/client/AppController.java
// public class AppController implements Presenter, ValueChangeHandler<String> {
// private static final Logger logger = Logger.getLogger(AppController.class.getName());
//
// private static final String DEFAULT_TOKEN = "default";
// private final EventBus eventBus;
// private final AppInjector injector;
// private HasWidgets container;
//
// @Inject
// public AppController(final EventBus eventBus, final AppInjector injector) {
// this.eventBus = eventBus;
// this.injector = injector;
// bind();
// }
//
// /**
// * Bind handlers to the application's events.
// */
// private void bind() {
// History.addValueChangeHandler(this);
//
// eventBus.addHandler(DataEvent.TYPE, new DataEvent.DataEventHandler() {
// public void onData(final DataEvent event, final IsDataSync dataSync) {
// doRequestData(dataSync);
// }
// });
//
// }
//
// /**
// * Performs the request for data and asynchronously receives the response or failure notice.
// * A response's data is pushed to the dataSync.
// *
// * @param dataSync Is the receiver of a data response's payload.
// */
// private void doRequestData(final IsDataSync dataSync) {
// final Resource resource = new Resource("/dataset");
// final PercentServiceAsync percentServiceAsync = GWT.create(PercentServiceAsync.class);
// ((RestServiceProxy) percentServiceAsync).setResource(resource);
// percentServiceAsync.getPercents(new MethodCallback<List<PercentValue>>() {
// @Override
// public void onFailure(final Method method, final Throwable throwable) {
// logger.warning(throwable.toString());
// }
//
// @Override
// public void onSuccess(final Method method, final List<PercentValue> values) {
// logger.fine(values.toString());
// dataSync.setData(values);
// }
// });
//
// // History.newItem(EXAMPLE_TOKEN);
// }
//
// /**
// * Capture the desired container and pump the history value.
// */
// public void go(final HasWidgets container) {
// this.container = container;
//
// if ("".equals(History.getToken())) {
// History.newItem(DEFAULT_TOKEN);
// }
// else {
// History.fireCurrentHistoryState();
// }
// }
//
// /**
// * Delegate the application state handling to the appropriate target.
// */
// public void onValueChange(final ValueChangeEvent<String> event) {
// final String token = event.getValue();
//
// if (token != null) {
// Presenter presenter = null;
//
// if (token.equals(DEFAULT_TOKEN)) {
// presenter = injector.getMainPresenter();
// }
//
// if (presenter != null) {
// // Pass the container to the current target.
// presenter.go(container);
// }
// }
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
// public class MainPresenter implements Presenter {
// private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
//
// public interface Display extends IsWidget, IsDataSync {
// HasClickHandlers getRefreshButton();
// }
//
// private final EventBus eventBus;
// private final Display display;
//
// @Inject
// public MainPresenter(final EventBus eventBus, final Display view) {
// this.eventBus = eventBus;
// display = view;
// }
//
// /**
// * Binds the refresh button click into a data request bus event.
// */
// protected void bind() {
// display.getRefreshButton().addClickHandler(new ClickHandler() {
// public void onClick(final ClickEvent event) {
// logger.fine("Request data from server using the event bus.");
// final DataEvent dataEvent = GWT.create(DataEvent.class);
// dataEvent.target = display;
// eventBus.fireEvent(dataEvent);
// }
// });
// }
//
// public void go(final HasWidgets container) {
// bind();
// container.clear();
// container.add(display.asWidget());
// }
//
// /**
// * Get the target's view instance. This method is primarily used by tests.
// *
// * @return Return the target's view.
// */
// public Display getDisplay() {
// return display;
// }
// }
| import com.google.gwt.inject.client.GinModules;
import com.google.gwt.inject.client.Ginjector;
import com.java33.vizpres.client.AppController;
import com.java33.vizpres.client.presenter.MainPresenter; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.gin;
/**
* This interface is only used to generate top-level instances in the
* AppModule scope. This approach is used to overcome the lack of Java
* reflection in GWT's emulation.
*
* @author Jon Buffington
*/
@GinModules(AppModule.class)
public interface AppInjector extends Ginjector {
AppController getAppController();
| // Path: src/main/java/com/java33/vizpres/client/AppController.java
// public class AppController implements Presenter, ValueChangeHandler<String> {
// private static final Logger logger = Logger.getLogger(AppController.class.getName());
//
// private static final String DEFAULT_TOKEN = "default";
// private final EventBus eventBus;
// private final AppInjector injector;
// private HasWidgets container;
//
// @Inject
// public AppController(final EventBus eventBus, final AppInjector injector) {
// this.eventBus = eventBus;
// this.injector = injector;
// bind();
// }
//
// /**
// * Bind handlers to the application's events.
// */
// private void bind() {
// History.addValueChangeHandler(this);
//
// eventBus.addHandler(DataEvent.TYPE, new DataEvent.DataEventHandler() {
// public void onData(final DataEvent event, final IsDataSync dataSync) {
// doRequestData(dataSync);
// }
// });
//
// }
//
// /**
// * Performs the request for data and asynchronously receives the response or failure notice.
// * A response's data is pushed to the dataSync.
// *
// * @param dataSync Is the receiver of a data response's payload.
// */
// private void doRequestData(final IsDataSync dataSync) {
// final Resource resource = new Resource("/dataset");
// final PercentServiceAsync percentServiceAsync = GWT.create(PercentServiceAsync.class);
// ((RestServiceProxy) percentServiceAsync).setResource(resource);
// percentServiceAsync.getPercents(new MethodCallback<List<PercentValue>>() {
// @Override
// public void onFailure(final Method method, final Throwable throwable) {
// logger.warning(throwable.toString());
// }
//
// @Override
// public void onSuccess(final Method method, final List<PercentValue> values) {
// logger.fine(values.toString());
// dataSync.setData(values);
// }
// });
//
// // History.newItem(EXAMPLE_TOKEN);
// }
//
// /**
// * Capture the desired container and pump the history value.
// */
// public void go(final HasWidgets container) {
// this.container = container;
//
// if ("".equals(History.getToken())) {
// History.newItem(DEFAULT_TOKEN);
// }
// else {
// History.fireCurrentHistoryState();
// }
// }
//
// /**
// * Delegate the application state handling to the appropriate target.
// */
// public void onValueChange(final ValueChangeEvent<String> event) {
// final String token = event.getValue();
//
// if (token != null) {
// Presenter presenter = null;
//
// if (token.equals(DEFAULT_TOKEN)) {
// presenter = injector.getMainPresenter();
// }
//
// if (presenter != null) {
// // Pass the container to the current target.
// presenter.go(container);
// }
// }
// }
// }
//
// Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
// public class MainPresenter implements Presenter {
// private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
//
// public interface Display extends IsWidget, IsDataSync {
// HasClickHandlers getRefreshButton();
// }
//
// private final EventBus eventBus;
// private final Display display;
//
// @Inject
// public MainPresenter(final EventBus eventBus, final Display view) {
// this.eventBus = eventBus;
// display = view;
// }
//
// /**
// * Binds the refresh button click into a data request bus event.
// */
// protected void bind() {
// display.getRefreshButton().addClickHandler(new ClickHandler() {
// public void onClick(final ClickEvent event) {
// logger.fine("Request data from server using the event bus.");
// final DataEvent dataEvent = GWT.create(DataEvent.class);
// dataEvent.target = display;
// eventBus.fireEvent(dataEvent);
// }
// });
// }
//
// public void go(final HasWidgets container) {
// bind();
// container.clear();
// container.add(display.asWidget());
// }
//
// /**
// * Get the target's view instance. This method is primarily used by tests.
// *
// * @return Return the target's view.
// */
// public Display getDisplay() {
// return display;
// }
// }
// Path: src/main/java/com/java33/vizpres/client/gin/AppInjector.java
import com.google.gwt.inject.client.GinModules;
import com.google.gwt.inject.client.Ginjector;
import com.java33.vizpres.client.AppController;
import com.java33.vizpres.client.presenter.MainPresenter;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.gin;
/**
* This interface is only used to generate top-level instances in the
* AppModule scope. This approach is used to overcome the lack of Java
* reflection in GWT's emulation.
*
* @author Jon Buffington
*/
@GinModules(AppModule.class)
public interface AppInjector extends Ginjector {
AppController getAppController();
| MainPresenter getMainPresenter(); |
jonbuffington/vizpres | src/test/java/com/java33/vizpres/logic/MockModule.java | // Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
// public class MainPresenter implements Presenter {
// private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
//
// public interface Display extends IsWidget, IsDataSync {
// HasClickHandlers getRefreshButton();
// }
//
// private final EventBus eventBus;
// private final Display display;
//
// @Inject
// public MainPresenter(final EventBus eventBus, final Display view) {
// this.eventBus = eventBus;
// display = view;
// }
//
// /**
// * Binds the refresh button click into a data request bus event.
// */
// protected void bind() {
// display.getRefreshButton().addClickHandler(new ClickHandler() {
// public void onClick(final ClickEvent event) {
// logger.fine("Request data from server using the event bus.");
// final DataEvent dataEvent = GWT.create(DataEvent.class);
// dataEvent.target = display;
// eventBus.fireEvent(dataEvent);
// }
// });
// }
//
// public void go(final HasWidgets container) {
// bind();
// container.clear();
// container.add(display.asWidget());
// }
//
// /**
// * Get the target's view instance. This method is primarily used by tests.
// *
// * @return Return the target's view.
// */
// public Display getDisplay() {
// return display;
// }
// }
| import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.AbstractModule;
import com.java33.vizpres.client.presenter.MainPresenter;
import org.mockito.Mockito; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.logic;
/**
* Is a Guice/GIN module used by logic tests to mock concrete view dependencies.
*/
public class MockModule extends AbstractModule {
@Override
protected void configure() {
// Support injecting the HandlerManager into the Application scope.
final EventBus mockedEventBus = Mockito.mock(EventBus.class);
bind(EventBus.class).toInstance(mockedEventBus);
// Mock the container that holds the target's views.
final HasWidgets mockedContainer = Mockito.mock(HasWidgets.class);
bind(HasWidgets.class).toInstance(mockedContainer);
// Mock the target's view. | // Path: src/main/java/com/java33/vizpres/client/presenter/MainPresenter.java
// public class MainPresenter implements Presenter {
// private static final Logger logger = Logger.getLogger(MainPresenter.class.getName());
//
// public interface Display extends IsWidget, IsDataSync {
// HasClickHandlers getRefreshButton();
// }
//
// private final EventBus eventBus;
// private final Display display;
//
// @Inject
// public MainPresenter(final EventBus eventBus, final Display view) {
// this.eventBus = eventBus;
// display = view;
// }
//
// /**
// * Binds the refresh button click into a data request bus event.
// */
// protected void bind() {
// display.getRefreshButton().addClickHandler(new ClickHandler() {
// public void onClick(final ClickEvent event) {
// logger.fine("Request data from server using the event bus.");
// final DataEvent dataEvent = GWT.create(DataEvent.class);
// dataEvent.target = display;
// eventBus.fireEvent(dataEvent);
// }
// });
// }
//
// public void go(final HasWidgets container) {
// bind();
// container.clear();
// container.add(display.asWidget());
// }
//
// /**
// * Get the target's view instance. This method is primarily used by tests.
// *
// * @return Return the target's view.
// */
// public Display getDisplay() {
// return display;
// }
// }
// Path: src/test/java/com/java33/vizpres/logic/MockModule.java
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.AbstractModule;
import com.java33.vizpres.client.presenter.MainPresenter;
import org.mockito.Mockito;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.logic;
/**
* Is a Guice/GIN module used by logic tests to mock concrete view dependencies.
*/
public class MockModule extends AbstractModule {
@Override
protected void configure() {
// Support injecting the HandlerManager into the Application scope.
final EventBus mockedEventBus = Mockito.mock(EventBus.class);
bind(EventBus.class).toInstance(mockedEventBus);
// Mock the container that holds the target's views.
final HasWidgets mockedContainer = Mockito.mock(HasWidgets.class);
bind(HasWidgets.class).toInstance(mockedContainer);
// Mock the target's view. | final MainPresenter.Display mockedView = Mockito.mock(MainPresenter.Display.class); |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/event/DataEvent.java | // Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
| import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.java33.vizpres.client.view.visualization.IsDataSync; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.event;
/**
* Is a a custom event used to signal data needs to be requested.
*
* @author Jon Buffington
*/
public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
public interface DataEventHandler extends EventHandler { | // Path: src/main/java/com/java33/vizpres/client/view/visualization/IsDataSync.java
// public interface IsDataSync {
//
// /**
// * Pushes the data values into the data sync.
// *
// * @param values Is a list of percentage values.
// */
// void setData(final List<PercentValue> values);
// }
// Path: src/main/java/com/java33/vizpres/client/event/DataEvent.java
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.java33.vizpres.client.view.visualization.IsDataSync;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.event;
/**
* Is a a custom event used to signal data needs to be requested.
*
* @author Jon Buffington
*/
public class DataEvent extends GwtEvent<DataEvent.DataEventHandler> {
public interface DataEventHandler extends EventHandler { | void onData(DataEvent event, IsDataSync dataSync); |
jonbuffington/vizpres | src/test/java/com/java33/vizpres/gwtsuite/GwtTestSuite.java | // Path: src/test/java/com/java33/vizpres/client/ExampleGwtTC.java
// public class ExampleGwtTC extends GWTTestCase {
// private MainPresenter presenter;
// private Messages messages;
//
// /**
// * Return the fully-qualified name of the GWT module. This is the glue
// * that tells the GWTTestCase runner which GWT module to use.
// *
// * @see com.google.gwt.junit.client.GWTTestCase#getModuleName()
// */
// public String getModuleName() {
// return "com.java33.vizpres.IntegrationTestModule";
// }
//
// @Override
// public void gwtSetUp() {
// final AppInjector injector = GWT.create(AppInjector.class);
// presenter = injector.getMainPresenter();
//
// messages = GWT.create(Messages.class);
// }
//
// /**
// * Furiously test the button.
// */
// public void testRefreshButton() {
// final MainPresenter.Display display = presenter.getDisplay();
// assertNotNull(display);
// final Button button = (Button) display.getRefreshButton();
// assertNotNull(button);
// assertTrue("The display's button is using an unexpected label.", button.getText().equals(messages.refresh()));
// }
//
// }
| import com.google.gwt.junit.tools.GWTTestSuite;
import com.java33.vizpres.client.ExampleGwtTC;
import junit.framework.Test;
import junit.framework.TestSuite; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.gwtsuite;
/**
* From "Use GWTTestSuite padawan":
* <p/>
* GWTTestCase derived tests are slow. This is because the JUnitShell has to load the
* module for each test (create the shell, hook into it, etc). GWTTestSuite mitigates
* this by grouping all the tests that are for the same module
* (those that return the same value for getModuleName) together and running them
* via the same shell instance.
* <p/>
* We recommend to name your test suite GwtTestSuite.java so that the test filter picks it up,
* but name the actual tests with a convention that Surefire will ignore by default - something
* that does not start with GwtTest, and does not start or end with Test. For example MyClassTestGwt.java.
* This way, gwt-maven-plugin picks up the Suite, and runs it, but does not also run individual
* tests (and Surefire does not pick it up either)
* <p/>
* http://mojo.codehaus.org/gwt-maven-plugin/user-guide/testing.html
*/
public class GwtTestSuite extends GWTTestSuite {
public static Test suite() {
final TestSuite suite = new TestSuite("GWT application integration tests"); | // Path: src/test/java/com/java33/vizpres/client/ExampleGwtTC.java
// public class ExampleGwtTC extends GWTTestCase {
// private MainPresenter presenter;
// private Messages messages;
//
// /**
// * Return the fully-qualified name of the GWT module. This is the glue
// * that tells the GWTTestCase runner which GWT module to use.
// *
// * @see com.google.gwt.junit.client.GWTTestCase#getModuleName()
// */
// public String getModuleName() {
// return "com.java33.vizpres.IntegrationTestModule";
// }
//
// @Override
// public void gwtSetUp() {
// final AppInjector injector = GWT.create(AppInjector.class);
// presenter = injector.getMainPresenter();
//
// messages = GWT.create(Messages.class);
// }
//
// /**
// * Furiously test the button.
// */
// public void testRefreshButton() {
// final MainPresenter.Display display = presenter.getDisplay();
// assertNotNull(display);
// final Button button = (Button) display.getRefreshButton();
// assertNotNull(button);
// assertTrue("The display's button is using an unexpected label.", button.getText().equals(messages.refresh()));
// }
//
// }
// Path: src/test/java/com/java33/vizpres/gwtsuite/GwtTestSuite.java
import com.google.gwt.junit.tools.GWTTestSuite;
import com.java33.vizpres.client.ExampleGwtTC;
import junit.framework.Test;
import junit.framework.TestSuite;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.gwtsuite;
/**
* From "Use GWTTestSuite padawan":
* <p/>
* GWTTestCase derived tests are slow. This is because the JUnitShell has to load the
* module for each test (create the shell, hook into it, etc). GWTTestSuite mitigates
* this by grouping all the tests that are for the same module
* (those that return the same value for getModuleName) together and running them
* via the same shell instance.
* <p/>
* We recommend to name your test suite GwtTestSuite.java so that the test filter picks it up,
* but name the actual tests with a convention that Surefire will ignore by default - something
* that does not start with GwtTest, and does not start or end with Test. For example MyClassTestGwt.java.
* This way, gwt-maven-plugin picks up the Suite, and runs it, but does not also run individual
* tests (and Surefire does not pick it up either)
* <p/>
* http://mojo.codehaus.org/gwt-maven-plugin/user-guide/testing.html
*/
public class GwtTestSuite extends GWTTestSuite {
public static Test suite() {
final TestSuite suite = new TestSuite("GWT application integration tests"); | suite.addTestSuite(ExampleGwtTC.class); |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/view/visualization/RaphaelCanvas.java | // Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
| import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.hydro4ge.raphaelgwt.client.Raphael;
import com.java33.vizpres.shared.model.PercentValue;
import java.util.List; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.view.visualization;
/**
* Is a demonstration of using Raphael to render SVG/VML to the browser.
*
* @author Jon Buffington
*/
public class RaphaelCanvas extends Raphael implements IsDataSync {
private static final int ROW_HEIGHT = 30;
private static final int BAR_HEIGHT = 28;
private static final int TEXT_HEIGHT = 12;
private static final int TEXT_OFFSET = (TEXT_HEIGHT / 2) + ((BAR_HEIGHT - TEXT_HEIGHT) / 2);
private final RaphaelViz parent;
private final int width;
public RaphaelCanvas(final int width, final int height, final RaphaelViz parent) {
super(width, height);
this.width = width;
this.parent = parent;
}
@Override | // Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
// Path: src/main/java/com/java33/vizpres/client/view/visualization/RaphaelCanvas.java
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.hydro4ge.raphaelgwt.client.Raphael;
import com.java33.vizpres.shared.model.PercentValue;
import java.util.List;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.view.visualization;
/**
* Is a demonstration of using Raphael to render SVG/VML to the browser.
*
* @author Jon Buffington
*/
public class RaphaelCanvas extends Raphael implements IsDataSync {
private static final int ROW_HEIGHT = 30;
private static final int BAR_HEIGHT = 28;
private static final int TEXT_HEIGHT = 12;
private static final int TEXT_OFFSET = (TEXT_HEIGHT / 2) + ((BAR_HEIGHT - TEXT_HEIGHT) / 2);
private final RaphaelViz parent;
private final int width;
public RaphaelCanvas(final int width, final int height, final RaphaelViz parent) {
super(width, height);
this.width = width;
this.parent = parent;
}
@Override | public void setData(final List<PercentValue> values) { |
jonbuffington/vizpres | src/main/java/com/java33/vizpres/client/view/visualization/CanvasViz.java | // Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
| import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.java33.vizpres.shared.model.PercentValue;
import java.util.List; | /*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.view.visualization;
/**
* Is a simple demonstration using the Canvas 2D context to render a bar chart.
*
* @author Jon Buffington
*/
public class CanvasViz extends Composite implements IsDataSync {
private static final int ROW_HEIGHT = 30;
private static final int BAR_HEIGHT = 28;
private static final int TEXT_HEIGHT = 14;
private final FlowPanel root;
private final int width;
private final int height;
private Canvas canvas;
@UiConstructor
public CanvasViz(final int width, final int height) {
root = new FlowPanel();
this.width = width;
this.height = height;
root.add(new Label("Technique: Use a Canvas element to draw the chart."));
initWidget(root);
}
/**
* If the browser supports the canvas tag and 2D drawing API, add a GWT
* {@link Canvas} to the root panel.
*/
@Override
protected void onLoad() {
super.onLoad();
canvas = Canvas.createIfSupported();
if (canvas != null) {
// Set-up a 1-to-1 pixel to coordinate space.
canvas.setWidth(Integer.toString(width) + "px");
canvas.setCoordinateSpaceWidth(width);
canvas.setHeight(Integer.toString(height) + "px");
canvas.setCoordinateSpaceHeight(height);
root.add(canvas);
}
}
/**
* Renders the percent data values using the Canvas 2D API as horizontal
* bars with a text label.
*
* @param values Is the list of values to render.
*/
@Override | // Path: src/main/java/com/java33/vizpres/shared/model/PercentValue.java
// public class PercentValue {
// public int percentage;
//
// public PercentValue(final int value) {
// this.percentage = value;
// }
//
// public PercentValue() {
// this(0);
// }
//
// @Override
// public String toString() {
// return "PercentValue{" +
// "percentage=" + percentage +
// '}';
// }
// }
// Path: src/main/java/com/java33/vizpres/client/view/visualization/CanvasViz.java
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.java33.vizpres.shared.model.PercentValue;
import java.util.List;
/*
* Copyright (c) 2011 Jon Buffington. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.java33.vizpres.client.view.visualization;
/**
* Is a simple demonstration using the Canvas 2D context to render a bar chart.
*
* @author Jon Buffington
*/
public class CanvasViz extends Composite implements IsDataSync {
private static final int ROW_HEIGHT = 30;
private static final int BAR_HEIGHT = 28;
private static final int TEXT_HEIGHT = 14;
private final FlowPanel root;
private final int width;
private final int height;
private Canvas canvas;
@UiConstructor
public CanvasViz(final int width, final int height) {
root = new FlowPanel();
this.width = width;
this.height = height;
root.add(new Label("Technique: Use a Canvas element to draw the chart."));
initWidget(root);
}
/**
* If the browser supports the canvas tag and 2D drawing API, add a GWT
* {@link Canvas} to the root panel.
*/
@Override
protected void onLoad() {
super.onLoad();
canvas = Canvas.createIfSupported();
if (canvas != null) {
// Set-up a 1-to-1 pixel to coordinate space.
canvas.setWidth(Integer.toString(width) + "px");
canvas.setCoordinateSpaceWidth(width);
canvas.setHeight(Integer.toString(height) + "px");
canvas.setCoordinateSpaceHeight(height);
root.add(canvas);
}
}
/**
* Renders the percent data values using the Canvas 2D API as horizontal
* bars with a text label.
*
* @param values Is the list of values to render.
*/
@Override | public void setData(final List<PercentValue> values) { |
VernonLee/Theogony | app/src/main/java/com/nodlee/theogony/core/Api.java | // Path: app/src/main/java/com/nodlee/theogony/bean/DragonData.java
// public class DragonData extends RealmObject {
// private String type;
// private String format;
// private String version;
// private String languageCode;
// private RealmList<Champion> data;
// private boolean isOutDate; // 数据过时,即有新版本数据可更新
//
// public DragonData() {
// }
//
// public DragonData(String type, String format, String version, RealmList<Champion> data) {
// this.type = type;
// this.format = format;
// this.version = version;
// this.data = data;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getFormat() {
// return format;
// }
//
// public void setFormat(String format) {
// this.format = format;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public List<Champion> getData() {
// return data;
// }
//
// public void setData(RealmList<Champion> data) {
// this.data = data;
// }
//
// public String getLanguageCode() {
// return languageCode;
// }
//
// public void setLanguageCode(String languageCode) {
// this.languageCode = languageCode;
// }
//
// public boolean isOutDate() {
// return isOutDate;
// }
//
// public void setOutDate(boolean outDate) {
// isOutDate = outDate;
// }
//
// @Override
// public String toString() {
// return "type:" + type + "\n" +
// "format:" + format + "\n" +
// "version:" + version + "\n" +
// "language code:" + languageCode +
// "data size:" + (data == null ? 0 : data.size());
// }
// }
| import com.nodlee.theogony.bean.DragonData; | package com.nodlee.theogony.core;
/**
* 作者:nodlee
* 时间:2017/3/19
* 说明:本地业务接口
*/
public interface Api {
/**
* 从服务器加载数据
* @param url
*/
String request(String url);
/**
* 解析JSON字符串
* @param json
* @return
*/ | // Path: app/src/main/java/com/nodlee/theogony/bean/DragonData.java
// public class DragonData extends RealmObject {
// private String type;
// private String format;
// private String version;
// private String languageCode;
// private RealmList<Champion> data;
// private boolean isOutDate; // 数据过时,即有新版本数据可更新
//
// public DragonData() {
// }
//
// public DragonData(String type, String format, String version, RealmList<Champion> data) {
// this.type = type;
// this.format = format;
// this.version = version;
// this.data = data;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getFormat() {
// return format;
// }
//
// public void setFormat(String format) {
// this.format = format;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public List<Champion> getData() {
// return data;
// }
//
// public void setData(RealmList<Champion> data) {
// this.data = data;
// }
//
// public String getLanguageCode() {
// return languageCode;
// }
//
// public void setLanguageCode(String languageCode) {
// this.languageCode = languageCode;
// }
//
// public boolean isOutDate() {
// return isOutDate;
// }
//
// public void setOutDate(boolean outDate) {
// isOutDate = outDate;
// }
//
// @Override
// public String toString() {
// return "type:" + type + "\n" +
// "format:" + format + "\n" +
// "version:" + version + "\n" +
// "language code:" + languageCode +
// "data size:" + (data == null ? 0 : data.size());
// }
// }
// Path: app/src/main/java/com/nodlee/theogony/core/Api.java
import com.nodlee.theogony.bean.DragonData;
package com.nodlee.theogony.core;
/**
* 作者:nodlee
* 时间:2017/3/19
* 说明:本地业务接口
*/
public interface Api {
/**
* 从服务器加载数据
* @param url
*/
String request(String url);
/**
* 解析JSON字符串
* @param json
* @return
*/ | DragonData parseJsonWithGson(String json); |
VernonLee/Theogony | app/src/main/java/com/nodlee/theogony/App.java | // Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
| import android.app.Application;
import com.nodlee.theogony.thirdparty.realm.RealmProvider; | package com.nodlee.theogony;
/**
* Created by Vernon Lee on 15-11-19.
*/
public class App extends Application {
public static final String META_DATA_APP_KEY = "app_key";
@Override
public void onCreate() {
super.onCreate(); | // Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
// Path: app/src/main/java/com/nodlee/theogony/App.java
import android.app.Application;
import com.nodlee.theogony.thirdparty.realm.RealmProvider;
package com.nodlee.theogony;
/**
* Created by Vernon Lee on 15-11-19.
*/
public class App extends Application {
public static final String META_DATA_APP_KEY = "app_key";
@Override
public void onCreate() {
super.onCreate(); | RealmProvider.getInstance().init(this); |
VernonLee/Theogony | app/src/main/java/com/nodlee/theogony/ui/adapter/SkinWithLoadMoreAdapter.java | // Path: app/src/main/java/com/nodlee/theogony/bean/Skin.java
// public class Skin extends RealmObject implements Serializable {
// private int id;
// private String name;
// private int num;
// private String image;
//
// public Skin() {
// }
//
// public Skin(int id, String name, int num) {
// this.id = id;
// this.name = name;
// this.num = num;
// }
//
// public String getImage() {
// return image;
// }
//
// public void setImage(String image) {
// this.image = image;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getNum() {
// return num;
// }
//
// public void setNum(int num) {
// this.num = num;
// }
// }
| import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.nodlee.theogony.R;
import com.nodlee.theogony.bean.Skin;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife; | package com.nodlee.theogony.ui.adapter;
/**
* 作者:nodlee
* 时间:16/8/24
* 说明:
*/
public class SkinWithLoadMoreAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private static final int VIEW_TYPE_LOAD_MORE = 0;
private static final int VIEW_TYPE_NORMAL = 1;
private ImageLoader mImageLoader; | // Path: app/src/main/java/com/nodlee/theogony/bean/Skin.java
// public class Skin extends RealmObject implements Serializable {
// private int id;
// private String name;
// private int num;
// private String image;
//
// public Skin() {
// }
//
// public Skin(int id, String name, int num) {
// this.id = id;
// this.name = name;
// this.num = num;
// }
//
// public String getImage() {
// return image;
// }
//
// public void setImage(String image) {
// this.image = image;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getNum() {
// return num;
// }
//
// public void setNum(int num) {
// this.num = num;
// }
// }
// Path: app/src/main/java/com/nodlee/theogony/ui/adapter/SkinWithLoadMoreAdapter.java
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.nodlee.theogony.R;
import com.nodlee.theogony.bean.Skin;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
package com.nodlee.theogony.ui.adapter;
/**
* 作者:nodlee
* 时间:16/8/24
* 说明:
*/
public class SkinWithLoadMoreAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private static final int VIEW_TYPE_LOAD_MORE = 0;
private static final int VIEW_TYPE_NORMAL = 1;
private ImageLoader mImageLoader; | private ArrayList<Skin> mSkins; |
VernonLee/Theogony | app/src/androidTest/java/com/nodlee/theogony/thirdparty/gson/SpellDeserializerTest.java | // Path: app/src/main/java/com/nodlee/theogony/bean/Var.java
// public class Var extends RealmObject {
// private String key;
// private String link;
// @Ignore
// private float[] coeff;
//
// public Var() {
// }
//
// public Var(String key, String link, float[] coeff) {
// this.key = key;
// this.link = link;
// this.coeff = coeff;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getLink() {
// return link;
// }
//
// public void setLink(String link) {
// this.link = link;
// }
//
// public float[] getCoeff() {
// return coeff;
// }
//
// public void setCoeff(float[] coeff) {
// this.coeff = coeff;
// }
// }
| import android.util.Log;
import com.nodlee.theogony.bean.Var;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*; | package com.nodlee.theogony.thirdparty.gson;
/**
* 作者:nodlee
* 时间:2017/3/30
* 说明:
*/
public class SpellDeserializerTest {
@Test
public void deserialize() throws Exception {
String title1 = "賈克斯跳向目標,如目標是敵人,則造成 {{ e1 }} (+{{ f1 }}) (+{{ a1 }})物理傷害。";
String title2 = "賈克斯強化他的武器,下次基礎攻擊或跳斬附加額外 {{ e1 }} (+{{ a1 }}) 點魔法傷害。";
String title3 = "賈克斯進入忘我的防禦姿態 {{ e6 }} 秒,閃避所有普通攻擊並且減少範圍技能傷害 {{ e3 }}%。 再次使用技能或是 2 秒後,賈克斯暈眩身邊所有敵人,持續 {{ e2 }} 秒並對他們造成 {{ e1 }} (+{{ f2 }})物理傷害。 賈克斯每閃過一次攻擊,反擊風暴造成傷害上升{{ e5 }}%(最多提昇 {{ e4 }}% 傷害)。";
String title4 = "被動:當進行 3 次普攻時,賈克斯可以造成額外 {{ e1 }}﹝+{{ a1 }}﹞魔法傷害。 主動:強化戰鬥的意志,提高 {{ f2 }} 物理防禦和 {{ f1 }} 魔法防禦,持續 {{ e5 }} 秒。 額外的物理防禦等同 {{ e3 }} 加上額外 {{ e6 }}% 物理攻擊。 額外的魔法防禦等同 {{ e3 }} 加上額外 {{ e7 }}% 魔法攻擊。";
String title5 = "主動: 索娜獲得 {{ f1*100 }}% 跑速【{{ e1 }}% + 每 100 魔法攻擊獲得 {{ f2*100 }}%】,持續 {{ e9 }} 秒(或被敵方攻擊則停止 ),並將力量和弦 附加上 節奏 效果。 旋律: 索娜獲得靈氣,持續 {{ e3 }} 秒。接觸到靈氣的友軍將獲得 {{ f3*100 }}% 跑速,持續 {{ e5 }} 秒。 索娜自身增加的額外跑速將一直持續至少 {{ e5 }} 秒。";
| // Path: app/src/main/java/com/nodlee/theogony/bean/Var.java
// public class Var extends RealmObject {
// private String key;
// private String link;
// @Ignore
// private float[] coeff;
//
// public Var() {
// }
//
// public Var(String key, String link, float[] coeff) {
// this.key = key;
// this.link = link;
// this.coeff = coeff;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getLink() {
// return link;
// }
//
// public void setLink(String link) {
// this.link = link;
// }
//
// public float[] getCoeff() {
// return coeff;
// }
//
// public void setCoeff(float[] coeff) {
// this.coeff = coeff;
// }
// }
// Path: app/src/androidTest/java/com/nodlee/theogony/thirdparty/gson/SpellDeserializerTest.java
import android.util.Log;
import com.nodlee.theogony.bean.Var;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
package com.nodlee.theogony.thirdparty.gson;
/**
* 作者:nodlee
* 时间:2017/3/30
* 说明:
*/
public class SpellDeserializerTest {
@Test
public void deserialize() throws Exception {
String title1 = "賈克斯跳向目標,如目標是敵人,則造成 {{ e1 }} (+{{ f1 }}) (+{{ a1 }})物理傷害。";
String title2 = "賈克斯強化他的武器,下次基礎攻擊或跳斬附加額外 {{ e1 }} (+{{ a1 }}) 點魔法傷害。";
String title3 = "賈克斯進入忘我的防禦姿態 {{ e6 }} 秒,閃避所有普通攻擊並且減少範圍技能傷害 {{ e3 }}%。 再次使用技能或是 2 秒後,賈克斯暈眩身邊所有敵人,持續 {{ e2 }} 秒並對他們造成 {{ e1 }} (+{{ f2 }})物理傷害。 賈克斯每閃過一次攻擊,反擊風暴造成傷害上升{{ e5 }}%(最多提昇 {{ e4 }}% 傷害)。";
String title4 = "被動:當進行 3 次普攻時,賈克斯可以造成額外 {{ e1 }}﹝+{{ a1 }}﹞魔法傷害。 主動:強化戰鬥的意志,提高 {{ f2 }} 物理防禦和 {{ f1 }} 魔法防禦,持續 {{ e5 }} 秒。 額外的物理防禦等同 {{ e3 }} 加上額外 {{ e6 }}% 物理攻擊。 額外的魔法防禦等同 {{ e3 }} 加上額外 {{ e7 }}% 魔法攻擊。";
String title5 = "主動: 索娜獲得 {{ f1*100 }}% 跑速【{{ e1 }}% + 每 100 魔法攻擊獲得 {{ f2*100 }}%】,持續 {{ e9 }} 秒(或被敵方攻擊則停止 ),並將力量和弦 附加上 節奏 效果。 旋律: 索娜獲得靈氣,持續 {{ e3 }} 秒。接觸到靈氣的友軍將獲得 {{ f3*100 }}% 跑速,持續 {{ e5 }} 秒。 索娜自身增加的額外跑速將一直持續至少 {{ e5 }} 秒。";
| Var var = new Var("f1", "bonusattackdamage", new float[] { 1.0f }); |
VernonLee/Theogony | app/src/main/java/com/nodlee/theogony/core/DragonDataManager.java | // Path: app/src/main/java/com/nodlee/theogony/bean/DragonData.java
// public class DragonData extends RealmObject {
// private String type;
// private String format;
// private String version;
// private String languageCode;
// private RealmList<Champion> data;
// private boolean isOutDate; // 数据过时,即有新版本数据可更新
//
// public DragonData() {
// }
//
// public DragonData(String type, String format, String version, RealmList<Champion> data) {
// this.type = type;
// this.format = format;
// this.version = version;
// this.data = data;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getFormat() {
// return format;
// }
//
// public void setFormat(String format) {
// this.format = format;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public List<Champion> getData() {
// return data;
// }
//
// public void setData(RealmList<Champion> data) {
// this.data = data;
// }
//
// public String getLanguageCode() {
// return languageCode;
// }
//
// public void setLanguageCode(String languageCode) {
// this.languageCode = languageCode;
// }
//
// public boolean isOutDate() {
// return isOutDate;
// }
//
// public void setOutDate(boolean outDate) {
// isOutDate = outDate;
// }
//
// @Override
// public String toString() {
// return "type:" + type + "\n" +
// "format:" + format + "\n" +
// "version:" + version + "\n" +
// "language code:" + languageCode +
// "data size:" + (data == null ? 0 : data.size());
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/utils/LogHelper.java
// public class LogHelper {
// private static final String TAG = "theogony";
// private static boolean DEBUG = true;
//
// public static void LOGD(String message) {
// if (DEBUG) {
// Log.d(TAG, message);
// }
// }
//
// public static void LOGI(String message) {
// if (DEBUG) {
// Log.i(TAG, message);
// }
// }
//
// public static void LOGW(String message) {
// if (DEBUG) {
// Log.w(TAG, message);
// }
// }
//
// public static void LOGE(String message) {
// if (DEBUG) {
// Log.e(TAG, message);
// }
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
| import com.nodlee.theogony.bean.DragonData;
import com.nodlee.theogony.utils.LogHelper;
import com.nodlee.theogony.thirdparty.realm.RealmProvider;
import io.realm.Realm; | package com.nodlee.theogony.core;
/**
* Created by Vernon Lee on 15-11-22.
*/
public class DragonDataManager {
private static DragonDataManager sManager;
public static DragonDataManager getInstance() {
if (sManager == null) {
sManager = new DragonDataManager();
}
return sManager;
}
private DragonDataManager() {
}
| // Path: app/src/main/java/com/nodlee/theogony/bean/DragonData.java
// public class DragonData extends RealmObject {
// private String type;
// private String format;
// private String version;
// private String languageCode;
// private RealmList<Champion> data;
// private boolean isOutDate; // 数据过时,即有新版本数据可更新
//
// public DragonData() {
// }
//
// public DragonData(String type, String format, String version, RealmList<Champion> data) {
// this.type = type;
// this.format = format;
// this.version = version;
// this.data = data;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getFormat() {
// return format;
// }
//
// public void setFormat(String format) {
// this.format = format;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public List<Champion> getData() {
// return data;
// }
//
// public void setData(RealmList<Champion> data) {
// this.data = data;
// }
//
// public String getLanguageCode() {
// return languageCode;
// }
//
// public void setLanguageCode(String languageCode) {
// this.languageCode = languageCode;
// }
//
// public boolean isOutDate() {
// return isOutDate;
// }
//
// public void setOutDate(boolean outDate) {
// isOutDate = outDate;
// }
//
// @Override
// public String toString() {
// return "type:" + type + "\n" +
// "format:" + format + "\n" +
// "version:" + version + "\n" +
// "language code:" + languageCode +
// "data size:" + (data == null ? 0 : data.size());
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/utils/LogHelper.java
// public class LogHelper {
// private static final String TAG = "theogony";
// private static boolean DEBUG = true;
//
// public static void LOGD(String message) {
// if (DEBUG) {
// Log.d(TAG, message);
// }
// }
//
// public static void LOGI(String message) {
// if (DEBUG) {
// Log.i(TAG, message);
// }
// }
//
// public static void LOGW(String message) {
// if (DEBUG) {
// Log.w(TAG, message);
// }
// }
//
// public static void LOGE(String message) {
// if (DEBUG) {
// Log.e(TAG, message);
// }
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
// Path: app/src/main/java/com/nodlee/theogony/core/DragonDataManager.java
import com.nodlee.theogony.bean.DragonData;
import com.nodlee.theogony.utils.LogHelper;
import com.nodlee.theogony.thirdparty.realm.RealmProvider;
import io.realm.Realm;
package com.nodlee.theogony.core;
/**
* Created by Vernon Lee on 15-11-22.
*/
public class DragonDataManager {
private static DragonDataManager sManager;
public static DragonDataManager getInstance() {
if (sManager == null) {
sManager = new DragonDataManager();
}
return sManager;
}
private DragonDataManager() {
}
| public DragonData getDefault() { |
VernonLee/Theogony | app/src/main/java/com/nodlee/theogony/core/DragonDataManager.java | // Path: app/src/main/java/com/nodlee/theogony/bean/DragonData.java
// public class DragonData extends RealmObject {
// private String type;
// private String format;
// private String version;
// private String languageCode;
// private RealmList<Champion> data;
// private boolean isOutDate; // 数据过时,即有新版本数据可更新
//
// public DragonData() {
// }
//
// public DragonData(String type, String format, String version, RealmList<Champion> data) {
// this.type = type;
// this.format = format;
// this.version = version;
// this.data = data;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getFormat() {
// return format;
// }
//
// public void setFormat(String format) {
// this.format = format;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public List<Champion> getData() {
// return data;
// }
//
// public void setData(RealmList<Champion> data) {
// this.data = data;
// }
//
// public String getLanguageCode() {
// return languageCode;
// }
//
// public void setLanguageCode(String languageCode) {
// this.languageCode = languageCode;
// }
//
// public boolean isOutDate() {
// return isOutDate;
// }
//
// public void setOutDate(boolean outDate) {
// isOutDate = outDate;
// }
//
// @Override
// public String toString() {
// return "type:" + type + "\n" +
// "format:" + format + "\n" +
// "version:" + version + "\n" +
// "language code:" + languageCode +
// "data size:" + (data == null ? 0 : data.size());
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/utils/LogHelper.java
// public class LogHelper {
// private static final String TAG = "theogony";
// private static boolean DEBUG = true;
//
// public static void LOGD(String message) {
// if (DEBUG) {
// Log.d(TAG, message);
// }
// }
//
// public static void LOGI(String message) {
// if (DEBUG) {
// Log.i(TAG, message);
// }
// }
//
// public static void LOGW(String message) {
// if (DEBUG) {
// Log.w(TAG, message);
// }
// }
//
// public static void LOGE(String message) {
// if (DEBUG) {
// Log.e(TAG, message);
// }
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
| import com.nodlee.theogony.bean.DragonData;
import com.nodlee.theogony.utils.LogHelper;
import com.nodlee.theogony.thirdparty.realm.RealmProvider;
import io.realm.Realm; | package com.nodlee.theogony.core;
/**
* Created by Vernon Lee on 15-11-22.
*/
public class DragonDataManager {
private static DragonDataManager sManager;
public static DragonDataManager getInstance() {
if (sManager == null) {
sManager = new DragonDataManager();
}
return sManager;
}
private DragonDataManager() {
}
public DragonData getDefault() { | // Path: app/src/main/java/com/nodlee/theogony/bean/DragonData.java
// public class DragonData extends RealmObject {
// private String type;
// private String format;
// private String version;
// private String languageCode;
// private RealmList<Champion> data;
// private boolean isOutDate; // 数据过时,即有新版本数据可更新
//
// public DragonData() {
// }
//
// public DragonData(String type, String format, String version, RealmList<Champion> data) {
// this.type = type;
// this.format = format;
// this.version = version;
// this.data = data;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getFormat() {
// return format;
// }
//
// public void setFormat(String format) {
// this.format = format;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public List<Champion> getData() {
// return data;
// }
//
// public void setData(RealmList<Champion> data) {
// this.data = data;
// }
//
// public String getLanguageCode() {
// return languageCode;
// }
//
// public void setLanguageCode(String languageCode) {
// this.languageCode = languageCode;
// }
//
// public boolean isOutDate() {
// return isOutDate;
// }
//
// public void setOutDate(boolean outDate) {
// isOutDate = outDate;
// }
//
// @Override
// public String toString() {
// return "type:" + type + "\n" +
// "format:" + format + "\n" +
// "version:" + version + "\n" +
// "language code:" + languageCode +
// "data size:" + (data == null ? 0 : data.size());
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/utils/LogHelper.java
// public class LogHelper {
// private static final String TAG = "theogony";
// private static boolean DEBUG = true;
//
// public static void LOGD(String message) {
// if (DEBUG) {
// Log.d(TAG, message);
// }
// }
//
// public static void LOGI(String message) {
// if (DEBUG) {
// Log.i(TAG, message);
// }
// }
//
// public static void LOGW(String message) {
// if (DEBUG) {
// Log.w(TAG, message);
// }
// }
//
// public static void LOGE(String message) {
// if (DEBUG) {
// Log.e(TAG, message);
// }
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
// Path: app/src/main/java/com/nodlee/theogony/core/DragonDataManager.java
import com.nodlee.theogony.bean.DragonData;
import com.nodlee.theogony.utils.LogHelper;
import com.nodlee.theogony.thirdparty.realm.RealmProvider;
import io.realm.Realm;
package com.nodlee.theogony.core;
/**
* Created by Vernon Lee on 15-11-22.
*/
public class DragonDataManager {
private static DragonDataManager sManager;
public static DragonDataManager getInstance() {
if (sManager == null) {
sManager = new DragonDataManager();
}
return sManager;
}
private DragonDataManager() {
}
public DragonData getDefault() { | Realm realm = RealmProvider.getInstance().getRealm(); |
VernonLee/Theogony | app/src/main/java/com/nodlee/theogony/core/DragonDataManager.java | // Path: app/src/main/java/com/nodlee/theogony/bean/DragonData.java
// public class DragonData extends RealmObject {
// private String type;
// private String format;
// private String version;
// private String languageCode;
// private RealmList<Champion> data;
// private boolean isOutDate; // 数据过时,即有新版本数据可更新
//
// public DragonData() {
// }
//
// public DragonData(String type, String format, String version, RealmList<Champion> data) {
// this.type = type;
// this.format = format;
// this.version = version;
// this.data = data;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getFormat() {
// return format;
// }
//
// public void setFormat(String format) {
// this.format = format;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public List<Champion> getData() {
// return data;
// }
//
// public void setData(RealmList<Champion> data) {
// this.data = data;
// }
//
// public String getLanguageCode() {
// return languageCode;
// }
//
// public void setLanguageCode(String languageCode) {
// this.languageCode = languageCode;
// }
//
// public boolean isOutDate() {
// return isOutDate;
// }
//
// public void setOutDate(boolean outDate) {
// isOutDate = outDate;
// }
//
// @Override
// public String toString() {
// return "type:" + type + "\n" +
// "format:" + format + "\n" +
// "version:" + version + "\n" +
// "language code:" + languageCode +
// "data size:" + (data == null ? 0 : data.size());
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/utils/LogHelper.java
// public class LogHelper {
// private static final String TAG = "theogony";
// private static boolean DEBUG = true;
//
// public static void LOGD(String message) {
// if (DEBUG) {
// Log.d(TAG, message);
// }
// }
//
// public static void LOGI(String message) {
// if (DEBUG) {
// Log.i(TAG, message);
// }
// }
//
// public static void LOGW(String message) {
// if (DEBUG) {
// Log.w(TAG, message);
// }
// }
//
// public static void LOGE(String message) {
// if (DEBUG) {
// Log.e(TAG, message);
// }
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
| import com.nodlee.theogony.bean.DragonData;
import com.nodlee.theogony.utils.LogHelper;
import com.nodlee.theogony.thirdparty.realm.RealmProvider;
import io.realm.Realm; | package com.nodlee.theogony.core;
/**
* Created by Vernon Lee on 15-11-22.
*/
public class DragonDataManager {
private static DragonDataManager sManager;
public static DragonDataManager getInstance() {
if (sManager == null) {
sManager = new DragonDataManager();
}
return sManager;
}
private DragonDataManager() {
}
public DragonData getDefault() {
Realm realm = RealmProvider.getInstance().getRealm();
try {
DragonData result = realm.where(DragonData.class).findFirst();
return result;
} finally {
realm.close();
}
}
public void setOutDate() {
Realm realm = RealmProvider.getInstance().getRealm();
try {
realm.beginTransaction();
DragonData dragonData = getDefault();
dragonData.setOutDate(true);
realm.commitTransaction(); | // Path: app/src/main/java/com/nodlee/theogony/bean/DragonData.java
// public class DragonData extends RealmObject {
// private String type;
// private String format;
// private String version;
// private String languageCode;
// private RealmList<Champion> data;
// private boolean isOutDate; // 数据过时,即有新版本数据可更新
//
// public DragonData() {
// }
//
// public DragonData(String type, String format, String version, RealmList<Champion> data) {
// this.type = type;
// this.format = format;
// this.version = version;
// this.data = data;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getFormat() {
// return format;
// }
//
// public void setFormat(String format) {
// this.format = format;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public List<Champion> getData() {
// return data;
// }
//
// public void setData(RealmList<Champion> data) {
// this.data = data;
// }
//
// public String getLanguageCode() {
// return languageCode;
// }
//
// public void setLanguageCode(String languageCode) {
// this.languageCode = languageCode;
// }
//
// public boolean isOutDate() {
// return isOutDate;
// }
//
// public void setOutDate(boolean outDate) {
// isOutDate = outDate;
// }
//
// @Override
// public String toString() {
// return "type:" + type + "\n" +
// "format:" + format + "\n" +
// "version:" + version + "\n" +
// "language code:" + languageCode +
// "data size:" + (data == null ? 0 : data.size());
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/utils/LogHelper.java
// public class LogHelper {
// private static final String TAG = "theogony";
// private static boolean DEBUG = true;
//
// public static void LOGD(String message) {
// if (DEBUG) {
// Log.d(TAG, message);
// }
// }
//
// public static void LOGI(String message) {
// if (DEBUG) {
// Log.i(TAG, message);
// }
// }
//
// public static void LOGW(String message) {
// if (DEBUG) {
// Log.w(TAG, message);
// }
// }
//
// public static void LOGE(String message) {
// if (DEBUG) {
// Log.e(TAG, message);
// }
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
// Path: app/src/main/java/com/nodlee/theogony/core/DragonDataManager.java
import com.nodlee.theogony.bean.DragonData;
import com.nodlee.theogony.utils.LogHelper;
import com.nodlee.theogony.thirdparty.realm.RealmProvider;
import io.realm.Realm;
package com.nodlee.theogony.core;
/**
* Created by Vernon Lee on 15-11-22.
*/
public class DragonDataManager {
private static DragonDataManager sManager;
public static DragonDataManager getInstance() {
if (sManager == null) {
sManager = new DragonDataManager();
}
return sManager;
}
private DragonDataManager() {
}
public DragonData getDefault() {
Realm realm = RealmProvider.getInstance().getRealm();
try {
DragonData result = realm.where(DragonData.class).findFirst();
return result;
} finally {
realm.close();
}
}
public void setOutDate() {
Realm realm = RealmProvider.getInstance().getRealm();
try {
realm.beginTransaction();
DragonData dragonData = getDefault();
dragonData.setOutDate(true);
realm.commitTransaction(); | LogHelper.LOGD("数据已过时"); |
VernonLee/Theogony | app/src/androidTest/java/com/nodlee/theogony/core/ApiImplTest.java | // Path: app/src/main/java/com/nodlee/theogony/bean/DragonData.java
// public class DragonData extends RealmObject {
// private String type;
// private String format;
// private String version;
// private String languageCode;
// private RealmList<Champion> data;
// private boolean isOutDate; // 数据过时,即有新版本数据可更新
//
// public DragonData() {
// }
//
// public DragonData(String type, String format, String version, RealmList<Champion> data) {
// this.type = type;
// this.format = format;
// this.version = version;
// this.data = data;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getFormat() {
// return format;
// }
//
// public void setFormat(String format) {
// this.format = format;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public List<Champion> getData() {
// return data;
// }
//
// public void setData(RealmList<Champion> data) {
// this.data = data;
// }
//
// public String getLanguageCode() {
// return languageCode;
// }
//
// public void setLanguageCode(String languageCode) {
// this.languageCode = languageCode;
// }
//
// public boolean isOutDate() {
// return isOutDate;
// }
//
// public void setOutDate(boolean outDate) {
// isOutDate = outDate;
// }
//
// @Override
// public String toString() {
// return "type:" + type + "\n" +
// "format:" + format + "\n" +
// "version:" + version + "\n" +
// "language code:" + languageCode +
// "data size:" + (data == null ? 0 : data.size());
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
| import android.support.test.runner.AndroidJUnit4;
import com.nodlee.theogony.bean.DragonData;
import com.nodlee.theogony.thirdparty.realm.RealmProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import io.realm.Realm;
import static org.junit.Assert.*; | package com.nodlee.theogony.core;
/**
* 作者:nodlee
* 时间:2017/3/19
* 说明:
*/
@RunWith(AndroidJUnit4.class)
public class ApiImplTest {
private Realm mRealm;
private ApiImpl mApi;
@Before
public void setUp() throws Exception { | // Path: app/src/main/java/com/nodlee/theogony/bean/DragonData.java
// public class DragonData extends RealmObject {
// private String type;
// private String format;
// private String version;
// private String languageCode;
// private RealmList<Champion> data;
// private boolean isOutDate; // 数据过时,即有新版本数据可更新
//
// public DragonData() {
// }
//
// public DragonData(String type, String format, String version, RealmList<Champion> data) {
// this.type = type;
// this.format = format;
// this.version = version;
// this.data = data;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getFormat() {
// return format;
// }
//
// public void setFormat(String format) {
// this.format = format;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public List<Champion> getData() {
// return data;
// }
//
// public void setData(RealmList<Champion> data) {
// this.data = data;
// }
//
// public String getLanguageCode() {
// return languageCode;
// }
//
// public void setLanguageCode(String languageCode) {
// this.languageCode = languageCode;
// }
//
// public boolean isOutDate() {
// return isOutDate;
// }
//
// public void setOutDate(boolean outDate) {
// isOutDate = outDate;
// }
//
// @Override
// public String toString() {
// return "type:" + type + "\n" +
// "format:" + format + "\n" +
// "version:" + version + "\n" +
// "language code:" + languageCode +
// "data size:" + (data == null ? 0 : data.size());
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
// Path: app/src/androidTest/java/com/nodlee/theogony/core/ApiImplTest.java
import android.support.test.runner.AndroidJUnit4;
import com.nodlee.theogony.bean.DragonData;
import com.nodlee.theogony.thirdparty.realm.RealmProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import io.realm.Realm;
import static org.junit.Assert.*;
package com.nodlee.theogony.core;
/**
* 作者:nodlee
* 时间:2017/3/19
* 说明:
*/
@RunWith(AndroidJUnit4.class)
public class ApiImplTest {
private Realm mRealm;
private ApiImpl mApi;
@Before
public void setUp() throws Exception { | mRealm = RealmProvider.getInstance().getRealm(); |
VernonLee/Theogony | app/src/androidTest/java/com/nodlee/theogony/core/ApiImplTest.java | // Path: app/src/main/java/com/nodlee/theogony/bean/DragonData.java
// public class DragonData extends RealmObject {
// private String type;
// private String format;
// private String version;
// private String languageCode;
// private RealmList<Champion> data;
// private boolean isOutDate; // 数据过时,即有新版本数据可更新
//
// public DragonData() {
// }
//
// public DragonData(String type, String format, String version, RealmList<Champion> data) {
// this.type = type;
// this.format = format;
// this.version = version;
// this.data = data;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getFormat() {
// return format;
// }
//
// public void setFormat(String format) {
// this.format = format;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public List<Champion> getData() {
// return data;
// }
//
// public void setData(RealmList<Champion> data) {
// this.data = data;
// }
//
// public String getLanguageCode() {
// return languageCode;
// }
//
// public void setLanguageCode(String languageCode) {
// this.languageCode = languageCode;
// }
//
// public boolean isOutDate() {
// return isOutDate;
// }
//
// public void setOutDate(boolean outDate) {
// isOutDate = outDate;
// }
//
// @Override
// public String toString() {
// return "type:" + type + "\n" +
// "format:" + format + "\n" +
// "version:" + version + "\n" +
// "language code:" + languageCode +
// "data size:" + (data == null ? 0 : data.size());
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
| import android.support.test.runner.AndroidJUnit4;
import com.nodlee.theogony.bean.DragonData;
import com.nodlee.theogony.thirdparty.realm.RealmProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import io.realm.Realm;
import static org.junit.Assert.*; | package com.nodlee.theogony.core;
/**
* 作者:nodlee
* 时间:2017/3/19
* 说明:
*/
@RunWith(AndroidJUnit4.class)
public class ApiImplTest {
private Realm mRealm;
private ApiImpl mApi;
@Before
public void setUp() throws Exception {
mRealm = RealmProvider.getInstance().getRealm();
mApi = ApiImpl.getInstance();
}
@After
public void tearDown() throws Exception {
if (mRealm != null) {
mRealm.close();
}
}
@Test
public void loadDragonDataFromServer() throws Exception {
String baiduUrl = "http://baidu.com/";
String baiduString = mApi.request(baiduUrl);
assertTrue(baiduString != null);
}
@Test
public void parseJsonWithGson() throws Exception {
String gradonDataUrl = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?locale=zh_TW&champData=all&api_key=e0af5cdf-caab-44c2-a692-dea1d712f8ab";
String gradonDataString = mApi.request(gradonDataUrl);
assertTrue(gradonDataString != null && gradonDataString.length() > 100);
| // Path: app/src/main/java/com/nodlee/theogony/bean/DragonData.java
// public class DragonData extends RealmObject {
// private String type;
// private String format;
// private String version;
// private String languageCode;
// private RealmList<Champion> data;
// private boolean isOutDate; // 数据过时,即有新版本数据可更新
//
// public DragonData() {
// }
//
// public DragonData(String type, String format, String version, RealmList<Champion> data) {
// this.type = type;
// this.format = format;
// this.version = version;
// this.data = data;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getFormat() {
// return format;
// }
//
// public void setFormat(String format) {
// this.format = format;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public List<Champion> getData() {
// return data;
// }
//
// public void setData(RealmList<Champion> data) {
// this.data = data;
// }
//
// public String getLanguageCode() {
// return languageCode;
// }
//
// public void setLanguageCode(String languageCode) {
// this.languageCode = languageCode;
// }
//
// public boolean isOutDate() {
// return isOutDate;
// }
//
// public void setOutDate(boolean outDate) {
// isOutDate = outDate;
// }
//
// @Override
// public String toString() {
// return "type:" + type + "\n" +
// "format:" + format + "\n" +
// "version:" + version + "\n" +
// "language code:" + languageCode +
// "data size:" + (data == null ? 0 : data.size());
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
// Path: app/src/androidTest/java/com/nodlee/theogony/core/ApiImplTest.java
import android.support.test.runner.AndroidJUnit4;
import com.nodlee.theogony.bean.DragonData;
import com.nodlee.theogony.thirdparty.realm.RealmProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import io.realm.Realm;
import static org.junit.Assert.*;
package com.nodlee.theogony.core;
/**
* 作者:nodlee
* 时间:2017/3/19
* 说明:
*/
@RunWith(AndroidJUnit4.class)
public class ApiImplTest {
private Realm mRealm;
private ApiImpl mApi;
@Before
public void setUp() throws Exception {
mRealm = RealmProvider.getInstance().getRealm();
mApi = ApiImpl.getInstance();
}
@After
public void tearDown() throws Exception {
if (mRealm != null) {
mRealm.close();
}
}
@Test
public void loadDragonDataFromServer() throws Exception {
String baiduUrl = "http://baidu.com/";
String baiduString = mApi.request(baiduUrl);
assertTrue(baiduString != null);
}
@Test
public void parseJsonWithGson() throws Exception {
String gradonDataUrl = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?locale=zh_TW&champData=all&api_key=e0af5cdf-caab-44c2-a692-dea1d712f8ab";
String gradonDataString = mApi.request(gradonDataUrl);
assertTrue(gradonDataString != null && gradonDataString.length() > 100);
| DragonData dragonData = mApi.parseJsonWithGson(gradonDataString); |
VernonLee/Theogony | app/src/main/java/com/nodlee/theogony/core/ChampionManager.java | // Path: app/src/main/java/com/nodlee/theogony/bean/Champion.java
// public class Champion extends RealmObject implements Serializable {
// @PrimaryKey
// private int id;
// private String key;
// private String name;
// private String title;
// private String image;
// private String lore;
// private String blurb;
// private String enemytipsc;
// private String allytipsc;
// private String tagsc;
// private String partype;
// private Info info;
// private Stats stats;
// private Passive passive;
// private RealmList<Spell> spells;
// private RealmList<Skin> skins;
//
// public Champion() {
// }
//
// public Champion(int id, String key, String name, String title,
// String image, String lore, String blurb,
// String enemytipsc, String allytipsc, String tagsc,
// String partype, Info info, Stats stats, Passive passive,
// RealmList<Spell> spells, RealmList<Skin> skins) {
// this.id = id;
// this.key = key;
// this.name = name;
// this.title = title;
// this.image = image;
// this.lore = lore;
// this.blurb = blurb;
// this.enemytipsc = enemytipsc;
// this.allytipsc = allytipsc;
// this.tagsc = tagsc;
// this.partype = partype;
// this.info = info;
// this.stats = stats;
// this.passive = passive;
// this.spells = spells;
// this.skins = skins;
// }
//
// public Passive getPassive() {
// return passive;
// }
//
// public void setPassive(Passive passive) {
// this.passive = passive;
// }
//
// public String getEnemytipsc() {
// return enemytipsc;
// }
//
// public void setEnemytipsc(String enemytipsc) {
// this.enemytipsc = enemytipsc;
// }
//
// public String getAllytipsc() {
// return allytipsc;
// }
//
// public void setAllytipsc(String allytipsc) {
// this.allytipsc = allytipsc;
// }
//
// public String getTagsc() {
// return tagsc;
// }
//
// public void setTagsc(String tagsc) {
// this.tagsc = tagsc;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public Spanned getLore() {
// return Html.fromHtml(lore);
// }
//
// public void setLore(String lore) {
// this.lore = lore;
// }
//
// public String getBlurb() {
// return blurb;
// }
//
// public void setBlurb(String blurb) {
// this.blurb = blurb;
// }
//
// public String getPartype() {
// return partype;
// }
//
// public void setPartype(String partype) {
// this.partype = partype;
// }
//
// public Info getInfo() {
// return info;
// }
//
// public void setInfo(Info info) {
// this.info = info;
// }
//
// public Stats getStats() {
// return stats;
// }
//
// public void setStats(Stats stats) {
// this.stats = stats;
// }
//
// public RealmList<Spell> getSpells() {
// return spells;
// }
//
// public void setSpells(RealmList<Spell> spells) {
// this.spells = spells;
// }
//
// public RealmList<Skin> getSkins() {
// return skins;
// }
//
// public void setSkins(RealmList<Skin> skins) {
// this.skins = skins;
// }
//
// public String getImage() {
// return image;
// }
//
// public void setImage(String image) {
// this.image = image;
// }
//
// public String getDesc() {
// return name + ",江湖人称" + title;
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
| import android.text.TextUtils;
import com.nodlee.theogony.bean.Champion;
import com.nodlee.theogony.thirdparty.realm.RealmProvider;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmResults; | package com.nodlee.theogony.core;
/**
* 作者:nodlee
* 时间:2017/3/19
* 说明:
*/
public class ChampionManager {
private static ChampionManager sManager;
private ChampionManager() {
}
public static ChampionManager getInstance() {
if (sManager == null) {
sManager = new ChampionManager();
}
return sManager;
}
| // Path: app/src/main/java/com/nodlee/theogony/bean/Champion.java
// public class Champion extends RealmObject implements Serializable {
// @PrimaryKey
// private int id;
// private String key;
// private String name;
// private String title;
// private String image;
// private String lore;
// private String blurb;
// private String enemytipsc;
// private String allytipsc;
// private String tagsc;
// private String partype;
// private Info info;
// private Stats stats;
// private Passive passive;
// private RealmList<Spell> spells;
// private RealmList<Skin> skins;
//
// public Champion() {
// }
//
// public Champion(int id, String key, String name, String title,
// String image, String lore, String blurb,
// String enemytipsc, String allytipsc, String tagsc,
// String partype, Info info, Stats stats, Passive passive,
// RealmList<Spell> spells, RealmList<Skin> skins) {
// this.id = id;
// this.key = key;
// this.name = name;
// this.title = title;
// this.image = image;
// this.lore = lore;
// this.blurb = blurb;
// this.enemytipsc = enemytipsc;
// this.allytipsc = allytipsc;
// this.tagsc = tagsc;
// this.partype = partype;
// this.info = info;
// this.stats = stats;
// this.passive = passive;
// this.spells = spells;
// this.skins = skins;
// }
//
// public Passive getPassive() {
// return passive;
// }
//
// public void setPassive(Passive passive) {
// this.passive = passive;
// }
//
// public String getEnemytipsc() {
// return enemytipsc;
// }
//
// public void setEnemytipsc(String enemytipsc) {
// this.enemytipsc = enemytipsc;
// }
//
// public String getAllytipsc() {
// return allytipsc;
// }
//
// public void setAllytipsc(String allytipsc) {
// this.allytipsc = allytipsc;
// }
//
// public String getTagsc() {
// return tagsc;
// }
//
// public void setTagsc(String tagsc) {
// this.tagsc = tagsc;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public Spanned getLore() {
// return Html.fromHtml(lore);
// }
//
// public void setLore(String lore) {
// this.lore = lore;
// }
//
// public String getBlurb() {
// return blurb;
// }
//
// public void setBlurb(String blurb) {
// this.blurb = blurb;
// }
//
// public String getPartype() {
// return partype;
// }
//
// public void setPartype(String partype) {
// this.partype = partype;
// }
//
// public Info getInfo() {
// return info;
// }
//
// public void setInfo(Info info) {
// this.info = info;
// }
//
// public Stats getStats() {
// return stats;
// }
//
// public void setStats(Stats stats) {
// this.stats = stats;
// }
//
// public RealmList<Spell> getSpells() {
// return spells;
// }
//
// public void setSpells(RealmList<Spell> spells) {
// this.spells = spells;
// }
//
// public RealmList<Skin> getSkins() {
// return skins;
// }
//
// public void setSkins(RealmList<Skin> skins) {
// this.skins = skins;
// }
//
// public String getImage() {
// return image;
// }
//
// public void setImage(String image) {
// this.image = image;
// }
//
// public String getDesc() {
// return name + ",江湖人称" + title;
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
// Path: app/src/main/java/com/nodlee/theogony/core/ChampionManager.java
import android.text.TextUtils;
import com.nodlee.theogony.bean.Champion;
import com.nodlee.theogony.thirdparty.realm.RealmProvider;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmResults;
package com.nodlee.theogony.core;
/**
* 作者:nodlee
* 时间:2017/3/19
* 说明:
*/
public class ChampionManager {
private static ChampionManager sManager;
private ChampionManager() {
}
public static ChampionManager getInstance() {
if (sManager == null) {
sManager = new ChampionManager();
}
return sManager;
}
| public List<Champion> getAll() { |
VernonLee/Theogony | app/src/main/java/com/nodlee/theogony/core/ChampionManager.java | // Path: app/src/main/java/com/nodlee/theogony/bean/Champion.java
// public class Champion extends RealmObject implements Serializable {
// @PrimaryKey
// private int id;
// private String key;
// private String name;
// private String title;
// private String image;
// private String lore;
// private String blurb;
// private String enemytipsc;
// private String allytipsc;
// private String tagsc;
// private String partype;
// private Info info;
// private Stats stats;
// private Passive passive;
// private RealmList<Spell> spells;
// private RealmList<Skin> skins;
//
// public Champion() {
// }
//
// public Champion(int id, String key, String name, String title,
// String image, String lore, String blurb,
// String enemytipsc, String allytipsc, String tagsc,
// String partype, Info info, Stats stats, Passive passive,
// RealmList<Spell> spells, RealmList<Skin> skins) {
// this.id = id;
// this.key = key;
// this.name = name;
// this.title = title;
// this.image = image;
// this.lore = lore;
// this.blurb = blurb;
// this.enemytipsc = enemytipsc;
// this.allytipsc = allytipsc;
// this.tagsc = tagsc;
// this.partype = partype;
// this.info = info;
// this.stats = stats;
// this.passive = passive;
// this.spells = spells;
// this.skins = skins;
// }
//
// public Passive getPassive() {
// return passive;
// }
//
// public void setPassive(Passive passive) {
// this.passive = passive;
// }
//
// public String getEnemytipsc() {
// return enemytipsc;
// }
//
// public void setEnemytipsc(String enemytipsc) {
// this.enemytipsc = enemytipsc;
// }
//
// public String getAllytipsc() {
// return allytipsc;
// }
//
// public void setAllytipsc(String allytipsc) {
// this.allytipsc = allytipsc;
// }
//
// public String getTagsc() {
// return tagsc;
// }
//
// public void setTagsc(String tagsc) {
// this.tagsc = tagsc;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public Spanned getLore() {
// return Html.fromHtml(lore);
// }
//
// public void setLore(String lore) {
// this.lore = lore;
// }
//
// public String getBlurb() {
// return blurb;
// }
//
// public void setBlurb(String blurb) {
// this.blurb = blurb;
// }
//
// public String getPartype() {
// return partype;
// }
//
// public void setPartype(String partype) {
// this.partype = partype;
// }
//
// public Info getInfo() {
// return info;
// }
//
// public void setInfo(Info info) {
// this.info = info;
// }
//
// public Stats getStats() {
// return stats;
// }
//
// public void setStats(Stats stats) {
// this.stats = stats;
// }
//
// public RealmList<Spell> getSpells() {
// return spells;
// }
//
// public void setSpells(RealmList<Spell> spells) {
// this.spells = spells;
// }
//
// public RealmList<Skin> getSkins() {
// return skins;
// }
//
// public void setSkins(RealmList<Skin> skins) {
// this.skins = skins;
// }
//
// public String getImage() {
// return image;
// }
//
// public void setImage(String image) {
// this.image = image;
// }
//
// public String getDesc() {
// return name + ",江湖人称" + title;
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
| import android.text.TextUtils;
import com.nodlee.theogony.bean.Champion;
import com.nodlee.theogony.thirdparty.realm.RealmProvider;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmResults; | package com.nodlee.theogony.core;
/**
* 作者:nodlee
* 时间:2017/3/19
* 说明:
*/
public class ChampionManager {
private static ChampionManager sManager;
private ChampionManager() {
}
public static ChampionManager getInstance() {
if (sManager == null) {
sManager = new ChampionManager();
}
return sManager;
}
public List<Champion> getAll() { | // Path: app/src/main/java/com/nodlee/theogony/bean/Champion.java
// public class Champion extends RealmObject implements Serializable {
// @PrimaryKey
// private int id;
// private String key;
// private String name;
// private String title;
// private String image;
// private String lore;
// private String blurb;
// private String enemytipsc;
// private String allytipsc;
// private String tagsc;
// private String partype;
// private Info info;
// private Stats stats;
// private Passive passive;
// private RealmList<Spell> spells;
// private RealmList<Skin> skins;
//
// public Champion() {
// }
//
// public Champion(int id, String key, String name, String title,
// String image, String lore, String blurb,
// String enemytipsc, String allytipsc, String tagsc,
// String partype, Info info, Stats stats, Passive passive,
// RealmList<Spell> spells, RealmList<Skin> skins) {
// this.id = id;
// this.key = key;
// this.name = name;
// this.title = title;
// this.image = image;
// this.lore = lore;
// this.blurb = blurb;
// this.enemytipsc = enemytipsc;
// this.allytipsc = allytipsc;
// this.tagsc = tagsc;
// this.partype = partype;
// this.info = info;
// this.stats = stats;
// this.passive = passive;
// this.spells = spells;
// this.skins = skins;
// }
//
// public Passive getPassive() {
// return passive;
// }
//
// public void setPassive(Passive passive) {
// this.passive = passive;
// }
//
// public String getEnemytipsc() {
// return enemytipsc;
// }
//
// public void setEnemytipsc(String enemytipsc) {
// this.enemytipsc = enemytipsc;
// }
//
// public String getAllytipsc() {
// return allytipsc;
// }
//
// public void setAllytipsc(String allytipsc) {
// this.allytipsc = allytipsc;
// }
//
// public String getTagsc() {
// return tagsc;
// }
//
// public void setTagsc(String tagsc) {
// this.tagsc = tagsc;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public Spanned getLore() {
// return Html.fromHtml(lore);
// }
//
// public void setLore(String lore) {
// this.lore = lore;
// }
//
// public String getBlurb() {
// return blurb;
// }
//
// public void setBlurb(String blurb) {
// this.blurb = blurb;
// }
//
// public String getPartype() {
// return partype;
// }
//
// public void setPartype(String partype) {
// this.partype = partype;
// }
//
// public Info getInfo() {
// return info;
// }
//
// public void setInfo(Info info) {
// this.info = info;
// }
//
// public Stats getStats() {
// return stats;
// }
//
// public void setStats(Stats stats) {
// this.stats = stats;
// }
//
// public RealmList<Spell> getSpells() {
// return spells;
// }
//
// public void setSpells(RealmList<Spell> spells) {
// this.spells = spells;
// }
//
// public RealmList<Skin> getSkins() {
// return skins;
// }
//
// public void setSkins(RealmList<Skin> skins) {
// this.skins = skins;
// }
//
// public String getImage() {
// return image;
// }
//
// public void setImage(String image) {
// this.image = image;
// }
//
// public String getDesc() {
// return name + ",江湖人称" + title;
// }
// }
//
// Path: app/src/main/java/com/nodlee/theogony/thirdparty/realm/RealmProvider.java
// public class RealmProvider {
//
// private static RealmProvider sProvider;
//
// private RealmProvider() {
// }
//
// public static RealmProvider getInstance() {
// if (sProvider == null) {
// sProvider = new RealmProvider();
// }
// return sProvider;
// }
//
// public void init(Context context) {
// Realm.init(context);
// }
//
// public Realm getRealm() {
// RealmConfiguration config = new RealmConfiguration.Builder()
// .deleteRealmIfMigrationNeeded()
// .build();
// return Realm.getInstance(config);
// }
//
// public boolean isEmpty() {
// return getRealm().isEmpty();
// }
// }
// Path: app/src/main/java/com/nodlee/theogony/core/ChampionManager.java
import android.text.TextUtils;
import com.nodlee.theogony.bean.Champion;
import com.nodlee.theogony.thirdparty.realm.RealmProvider;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmResults;
package com.nodlee.theogony.core;
/**
* 作者:nodlee
* 时间:2017/3/19
* 说明:
*/
public class ChampionManager {
private static ChampionManager sManager;
private ChampionManager() {
}
public static ChampionManager getInstance() {
if (sManager == null) {
sManager = new ChampionManager();
}
return sManager;
}
public List<Champion> getAll() { | Realm realm = RealmProvider.getInstance().getRealm(); |
cameronleger/neural-style-gui | src/main/java/com/cameronleger/neuralstylegui/component/CheckboxView.java | // Path: src/main/java/com/cameronleger/neuralstylegui/model/properties/NeuralBoolean.java
// public class NeuralBoolean extends NeuralProperty<Boolean> {
//
// private BooleanProperty value;
// private final static boolean GLOBAL_DEFAULT = true;
//
// public NeuralBoolean(String name) {
// super(name);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleBooleanProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralBoolean(String name, String prettyName) {
// super(name, prettyName);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleBooleanProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralBoolean(String name, boolean value) {
// super(name);
// this.defaultValue = value;
// this.value = new SimpleBooleanProperty(value);
// }
//
// public NeuralBoolean(String name, String prettyName, boolean value) {
// super(name, prettyName);
// this.defaultValue = value;
// this.value = new SimpleBooleanProperty(value);
// }
//
// @Override
// public Boolean getValue() {
// return this.value.get();
// }
//
// @Override
// public Property<Boolean> valueProperty() {
// return this.value;
// }
//
// @Override
// public void setValue(Boolean value) {
// this.value.set(value);
// }
//
// @Override
// public void reset() {
// this.value.set(defaultValue);
// }
//
// }
| import com.cameronleger.neuralstylegui.model.properties.NeuralBoolean;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Logger; | package com.cameronleger.neuralstylegui.component;
public class CheckboxView extends HBox {
private static final Logger log = Logger.getLogger(CheckboxView.class.getName());
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private CheckBox value;
@FXML
private Button resetButton;
| // Path: src/main/java/com/cameronleger/neuralstylegui/model/properties/NeuralBoolean.java
// public class NeuralBoolean extends NeuralProperty<Boolean> {
//
// private BooleanProperty value;
// private final static boolean GLOBAL_DEFAULT = true;
//
// public NeuralBoolean(String name) {
// super(name);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleBooleanProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralBoolean(String name, String prettyName) {
// super(name, prettyName);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleBooleanProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralBoolean(String name, boolean value) {
// super(name);
// this.defaultValue = value;
// this.value = new SimpleBooleanProperty(value);
// }
//
// public NeuralBoolean(String name, String prettyName, boolean value) {
// super(name, prettyName);
// this.defaultValue = value;
// this.value = new SimpleBooleanProperty(value);
// }
//
// @Override
// public Boolean getValue() {
// return this.value.get();
// }
//
// @Override
// public Property<Boolean> valueProperty() {
// return this.value;
// }
//
// @Override
// public void setValue(Boolean value) {
// this.value.set(value);
// }
//
// @Override
// public void reset() {
// this.value.set(defaultValue);
// }
//
// }
// Path: src/main/java/com/cameronleger/neuralstylegui/component/CheckboxView.java
import com.cameronleger.neuralstylegui.model.properties.NeuralBoolean;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Logger;
package com.cameronleger.neuralstylegui.component;
public class CheckboxView extends HBox {
private static final Logger log = Logger.getLogger(CheckboxView.class.getName());
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private CheckBox value;
@FXML
private Button resetButton;
| private NeuralBoolean property; |
cameronleger/neural-style-gui | src/main/java/com/cameronleger/neuralstylegui/component/FullImageView.java | // Path: src/main/java/com/cameronleger/neuralstylegui/helper/MovingImageView.java
// public class MovingImageView {
// private static final Logger log = Logger.getLogger(MovingImageView.class.getName());
// private ImageView imageView;
// private String imageFilePath;
// private double width, height;
// private double scale = 1;
//
// public MovingImageView(ImageView imageView) {
// this.imageView = imageView;
// setupListeners();
// }
//
// private void setupListeners() {
// ObjectProperty<Point2D> mouseDown = new SimpleObjectProperty<>();
//
// EventStreams.eventsOf(imageView, MouseEvent.MOUSE_PRESSED).subscribe(e -> {
// Point2D mousePress = imageViewToImage(new Point2D(e.getX(), e.getY()));
// mouseDown.set(mousePress);
// });
//
// EventStreams.eventsOf(imageView, MouseEvent.MOUSE_DRAGGED).subscribe(e -> {
// Point2D dragPoint = imageViewToImage(new Point2D(e.getX(), e.getY()));
// shift(dragPoint.subtract(mouseDown.get()));
// mouseDown.set(imageViewToImage(new Point2D(e.getX(), e.getY())));
// });
//
// EventStream<ScrollEvent> scrollEvents = EventStreams.eventsOf(imageView, ScrollEvent.SCROLL);
// EventStream<ScrollEvent> scrollEventsUp = scrollEvents.filter(scrollEvent -> scrollEvent.getDeltaY() < 0);
// EventStream<ScrollEvent> scrollEventsDown = scrollEvents.filter(scrollEvent -> scrollEvent.getDeltaY() > 0);
// scrollEventsUp.subscribe(scrollEvent -> scale = Math.min(scale + 0.25, 3));
// scrollEventsDown.subscribe(scrollEvent -> scale = Math.max(scale - 0.25, 0.25));
// EventStreams.merge(scrollEventsUp, scrollEventsDown).subscribe(scrollEvent -> scaleImageViewport(scale));
//
// EventStreams.eventsOf(imageView, MouseEvent.MOUSE_CLICKED)
// .filter(mouseEvent -> mouseEvent.getClickCount() == 2)
// .subscribe(mouseEvent -> fitToView());
// }
//
// public void setImage(File imageFile) {
// if (imageFile == null || imageFile.getAbsolutePath().equals(imageFilePath))
// return;
//
// Image image;
// try {
// image = new Image(new FileInputStream(imageFile));
// } catch (FileNotFoundException e) {
// log.log(Level.SEVERE, e.toString(), e);
// return;
// }
// imageFilePath = imageFile.getAbsolutePath();
// imageView.setImage(image);
// if (width != image.getWidth() || height != image.getHeight()) {
// width = image.getWidth();
// height = image.getHeight();
// fitToView();
// }
// }
//
// public void fitToView() {
// Bounds layoutBounds = imageView.getLayoutBounds();
// if (width > height)
// scale = width / layoutBounds.getWidth();
// else
// scale = height / layoutBounds.getHeight();
// scaleImageViewport(scale);
// }
//
// public void scaleImageViewport(double scale) {
// this.scale = scale;
// Bounds layoutBounds = imageView.getLayoutBounds();
// double layoutWidth = layoutBounds.getWidth();
// double layoutHeight = layoutBounds.getHeight();
//
// // center the image's x&y
// double newWidth = layoutWidth * scale;
// double newHeight = layoutHeight * scale;
// double offsetX = (this.width - newWidth) / 2;
// double offsetY = (this.height - newHeight) / 2;
//
// imageView.setViewport(new Rectangle2D(offsetX, offsetY,
// layoutWidth * scale, layoutHeight * scale));
// }
//
// private void shift(Point2D delta) {
// Rectangle2D viewport = imageView.getViewport();
//
// imageView.setViewport(new Rectangle2D(
// viewport.getMinX() - delta.getX(), viewport.getMinY() - delta.getY(),
// viewport.getWidth(), viewport.getHeight()));
// }
//
// private Point2D imageViewToImage(Point2D imageViewCoordinates) {
// double xProportion = imageViewCoordinates.getX() / imageView.getBoundsInLocal().getWidth();
// double yProportion = imageViewCoordinates.getY() / imageView.getBoundsInLocal().getHeight();
//
// Rectangle2D viewport = imageView.getViewport();
// return new Point2D(
// viewport.getMinX() + xProportion * viewport.getWidth(),
// viewport.getMinY() + yProportion * viewport.getHeight());
// }
// }
| import com.cameronleger.neuralstylegui.helper.MovingImageView;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import org.reactfx.EventStreams;
import java.io.File;
import java.io.IOException;
import java.util.ResourceBundle;
import java.util.function.Consumer;
import java.util.logging.Logger; | package com.cameronleger.neuralstylegui.component;
public class FullImageView extends VBox {
private static final Logger log = Logger.getLogger(FullImageView.class.getName());
@FXML
private ImageView image;
@FXML
private Button style;
@FXML
private Button content;
@FXML
private Button init;
| // Path: src/main/java/com/cameronleger/neuralstylegui/helper/MovingImageView.java
// public class MovingImageView {
// private static final Logger log = Logger.getLogger(MovingImageView.class.getName());
// private ImageView imageView;
// private String imageFilePath;
// private double width, height;
// private double scale = 1;
//
// public MovingImageView(ImageView imageView) {
// this.imageView = imageView;
// setupListeners();
// }
//
// private void setupListeners() {
// ObjectProperty<Point2D> mouseDown = new SimpleObjectProperty<>();
//
// EventStreams.eventsOf(imageView, MouseEvent.MOUSE_PRESSED).subscribe(e -> {
// Point2D mousePress = imageViewToImage(new Point2D(e.getX(), e.getY()));
// mouseDown.set(mousePress);
// });
//
// EventStreams.eventsOf(imageView, MouseEvent.MOUSE_DRAGGED).subscribe(e -> {
// Point2D dragPoint = imageViewToImage(new Point2D(e.getX(), e.getY()));
// shift(dragPoint.subtract(mouseDown.get()));
// mouseDown.set(imageViewToImage(new Point2D(e.getX(), e.getY())));
// });
//
// EventStream<ScrollEvent> scrollEvents = EventStreams.eventsOf(imageView, ScrollEvent.SCROLL);
// EventStream<ScrollEvent> scrollEventsUp = scrollEvents.filter(scrollEvent -> scrollEvent.getDeltaY() < 0);
// EventStream<ScrollEvent> scrollEventsDown = scrollEvents.filter(scrollEvent -> scrollEvent.getDeltaY() > 0);
// scrollEventsUp.subscribe(scrollEvent -> scale = Math.min(scale + 0.25, 3));
// scrollEventsDown.subscribe(scrollEvent -> scale = Math.max(scale - 0.25, 0.25));
// EventStreams.merge(scrollEventsUp, scrollEventsDown).subscribe(scrollEvent -> scaleImageViewport(scale));
//
// EventStreams.eventsOf(imageView, MouseEvent.MOUSE_CLICKED)
// .filter(mouseEvent -> mouseEvent.getClickCount() == 2)
// .subscribe(mouseEvent -> fitToView());
// }
//
// public void setImage(File imageFile) {
// if (imageFile == null || imageFile.getAbsolutePath().equals(imageFilePath))
// return;
//
// Image image;
// try {
// image = new Image(new FileInputStream(imageFile));
// } catch (FileNotFoundException e) {
// log.log(Level.SEVERE, e.toString(), e);
// return;
// }
// imageFilePath = imageFile.getAbsolutePath();
// imageView.setImage(image);
// if (width != image.getWidth() || height != image.getHeight()) {
// width = image.getWidth();
// height = image.getHeight();
// fitToView();
// }
// }
//
// public void fitToView() {
// Bounds layoutBounds = imageView.getLayoutBounds();
// if (width > height)
// scale = width / layoutBounds.getWidth();
// else
// scale = height / layoutBounds.getHeight();
// scaleImageViewport(scale);
// }
//
// public void scaleImageViewport(double scale) {
// this.scale = scale;
// Bounds layoutBounds = imageView.getLayoutBounds();
// double layoutWidth = layoutBounds.getWidth();
// double layoutHeight = layoutBounds.getHeight();
//
// // center the image's x&y
// double newWidth = layoutWidth * scale;
// double newHeight = layoutHeight * scale;
// double offsetX = (this.width - newWidth) / 2;
// double offsetY = (this.height - newHeight) / 2;
//
// imageView.setViewport(new Rectangle2D(offsetX, offsetY,
// layoutWidth * scale, layoutHeight * scale));
// }
//
// private void shift(Point2D delta) {
// Rectangle2D viewport = imageView.getViewport();
//
// imageView.setViewport(new Rectangle2D(
// viewport.getMinX() - delta.getX(), viewport.getMinY() - delta.getY(),
// viewport.getWidth(), viewport.getHeight()));
// }
//
// private Point2D imageViewToImage(Point2D imageViewCoordinates) {
// double xProportion = imageViewCoordinates.getX() / imageView.getBoundsInLocal().getWidth();
// double yProportion = imageViewCoordinates.getY() / imageView.getBoundsInLocal().getHeight();
//
// Rectangle2D viewport = imageView.getViewport();
// return new Point2D(
// viewport.getMinX() + xProportion * viewport.getWidth(),
// viewport.getMinY() + yProportion * viewport.getHeight());
// }
// }
// Path: src/main/java/com/cameronleger/neuralstylegui/component/FullImageView.java
import com.cameronleger.neuralstylegui.helper.MovingImageView;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import org.reactfx.EventStreams;
import java.io.File;
import java.io.IOException;
import java.util.ResourceBundle;
import java.util.function.Consumer;
import java.util.logging.Logger;
package com.cameronleger.neuralstylegui.component;
public class FullImageView extends VBox {
private static final Logger log = Logger.getLogger(FullImageView.class.getName());
@FXML
private ImageView image;
@FXML
private Button style;
@FXML
private Button content;
@FXML
private Button init;
| MovingImageView imageView; |
cameronleger/neural-style-gui | src/main/java/com/cameronleger/neuralstylegui/model/NeuralImage.java | // Path: src/main/java/com/cameronleger/neuralstylegui/helper/AsyncImageProperty.java
// public class AsyncImageProperty extends SimpleObjectProperty<Image> {
// private static final Logger log = Logger.getLogger(AsyncImageProperty.class.getName());
// private final ImageLoadService imageLoadService = new ImageLoadService();
// private final ObjectProperty<File> imageFile = new SimpleObjectProperty<>();
//
// public AsyncImageProperty(int width, int height) {
// imageLoadService.setSize(width, height);
//
// imageLoadService.stateProperty().addListener((observable, oldValue, value) -> {
// if (value == Worker.State.SUCCEEDED)
// set(imageLoadService.getValue());
// if (value == Worker.State.FAILED)
// set(null);
//
// if (value == Worker.State.SUCCEEDED || value == Worker.State.CANCELLED || value == Worker.State.FAILED) {
// File handle = imageFile.get();
// if (handle != null && !handle.equals(imageLoadService.imageFile))
// loadImageInBackground(handle);
// }
// });
//
// imageFile.addListener((observable, oldValue, value) -> {
// if(!imageLoadService.isRunning()) {
// loadImageInBackground(imageFile.getValue());
// }
// });
// }
//
// public ObjectProperty<File> imageFileProperty() {
// return imageFile;
// }
//
// private void loadImageInBackground(File imageFile) {
// synchronized(imageLoadService) {
// if (FileUtils.checkFileExists(imageFile)) {
// imageLoadService.setImageFile(imageFile);
// imageLoadService.restart();
// }
// }
// }
//
// private static class ImageLoadService extends Service<Image> {
// private File imageFile;
// private int width = 0;
// private int height = 0;
//
// public void setImageFile(File imageFile) {
// this.imageFile = imageFile;
// }
//
// public void setSize(int width, int height) {
// this.width = width;
// this.height = height;
// }
//
// @Override
// protected Task<Image> createTask() {
// final File imageFile = this.imageFile;
// final int width = this.width;
// final int height = this.height;
// return new Task<Image>() {
// @Override
// protected Image call() {
// try {
// return new Image(new FileInputStream(imageFile), width, height, true, false);
// } catch (IOException e) {
// log.log(Level.SEVERE, e.toString(), e);
// return null;
// }
// }
// };
// }
// }
// }
| import com.cameronleger.neuralstylegui.helper.AsyncImageProperty;
import javafx.beans.property.*;
import javafx.scene.image.Image;
import java.io.File; | package com.cameronleger.neuralstylegui.model;
public class NeuralImage {
public static final int THUMBNAIL_SIZE = 225;
private BooleanProperty selected;
private StringProperty name;
private ObjectProperty<File> imageFile; | // Path: src/main/java/com/cameronleger/neuralstylegui/helper/AsyncImageProperty.java
// public class AsyncImageProperty extends SimpleObjectProperty<Image> {
// private static final Logger log = Logger.getLogger(AsyncImageProperty.class.getName());
// private final ImageLoadService imageLoadService = new ImageLoadService();
// private final ObjectProperty<File> imageFile = new SimpleObjectProperty<>();
//
// public AsyncImageProperty(int width, int height) {
// imageLoadService.setSize(width, height);
//
// imageLoadService.stateProperty().addListener((observable, oldValue, value) -> {
// if (value == Worker.State.SUCCEEDED)
// set(imageLoadService.getValue());
// if (value == Worker.State.FAILED)
// set(null);
//
// if (value == Worker.State.SUCCEEDED || value == Worker.State.CANCELLED || value == Worker.State.FAILED) {
// File handle = imageFile.get();
// if (handle != null && !handle.equals(imageLoadService.imageFile))
// loadImageInBackground(handle);
// }
// });
//
// imageFile.addListener((observable, oldValue, value) -> {
// if(!imageLoadService.isRunning()) {
// loadImageInBackground(imageFile.getValue());
// }
// });
// }
//
// public ObjectProperty<File> imageFileProperty() {
// return imageFile;
// }
//
// private void loadImageInBackground(File imageFile) {
// synchronized(imageLoadService) {
// if (FileUtils.checkFileExists(imageFile)) {
// imageLoadService.setImageFile(imageFile);
// imageLoadService.restart();
// }
// }
// }
//
// private static class ImageLoadService extends Service<Image> {
// private File imageFile;
// private int width = 0;
// private int height = 0;
//
// public void setImageFile(File imageFile) {
// this.imageFile = imageFile;
// }
//
// public void setSize(int width, int height) {
// this.width = width;
// this.height = height;
// }
//
// @Override
// protected Task<Image> createTask() {
// final File imageFile = this.imageFile;
// final int width = this.width;
// final int height = this.height;
// return new Task<Image>() {
// @Override
// protected Image call() {
// try {
// return new Image(new FileInputStream(imageFile), width, height, true, false);
// } catch (IOException e) {
// log.log(Level.SEVERE, e.toString(), e);
// return null;
// }
// }
// };
// }
// }
// }
// Path: src/main/java/com/cameronleger/neuralstylegui/model/NeuralImage.java
import com.cameronleger.neuralstylegui.helper.AsyncImageProperty;
import javafx.beans.property.*;
import javafx.scene.image.Image;
import java.io.File;
package com.cameronleger.neuralstylegui.model;
public class NeuralImage {
public static final int THUMBNAIL_SIZE = 225;
private BooleanProperty selected;
private StringProperty name;
private ObjectProperty<File> imageFile; | private AsyncImageProperty image; |
cameronleger/neural-style-gui | src/main/java/com/cameronleger/neuralstylegui/component/NeuralImageCell.java | // Path: src/main/java/com/cameronleger/neuralstylegui/model/NeuralImage.java
// public class NeuralImage {
// public static final int THUMBNAIL_SIZE = 225;
// private BooleanProperty selected;
// private StringProperty name;
// private ObjectProperty<File> imageFile;
// private AsyncImageProperty image;
// private DoubleProperty weight;
//
// public NeuralImage(File imageFile) {
// this.selected = new SimpleBooleanProperty(false);
// this.name = new SimpleStringProperty(imageFile.getName());
// this.imageFile = new SimpleObjectProperty<>(imageFile);
// this.image = new AsyncImageProperty(THUMBNAIL_SIZE, THUMBNAIL_SIZE);
// this.image.imageFileProperty().set(imageFile);
// this.weight = new SimpleDoubleProperty(1);
// }
//
// public BooleanProperty selectedProperty() {
// return selected;
// }
//
// public boolean isSelected() {
// return selected.get();
// }
//
// public void setSelected(boolean selected) {
// this.selected.set(selected);
// }
//
// public StringProperty nameProperty() {
// return name;
// }
//
// public String getName() {
// return name.get();
// }
//
// public void setName(String name) {
// this.name.set(name);
// }
//
// public ObjectProperty<File> imageFileProperty() {
// return imageFile;
// }
//
// public File getImageFile() {
// return imageFile.get();
// }
//
// public void setImageFile(File imageFile) {
// this.imageFile.set(imageFile);
// }
//
// public ObjectProperty<Image> imageProperty() {
// return image;
// }
//
// public Image getImage() {
// return image.get();
// }
//
// public void setImage(Image image) {
// this.image.set(image);
// }
//
// public DoubleProperty weightProperty() {
// return weight;
// }
//
// public double getWeight() {
// return weight.get();
// }
//
// public void setWeight(double weight) {
// this.weight.set(weight);
// }
// }
//
// Path: src/main/java/com/cameronleger/neuralstylegui/model/properties/NeuralDouble.java
// public class NeuralDouble extends NeuralProperty<Number> {
//
// private DoubleProperty value;
// private final static double GLOBAL_DEFAULT = 1.0;
// private DoubleProperty ratio = new SimpleDoubleProperty(1.0);
//
// public NeuralDouble(String name) {
// super(name);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleDoubleProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralDouble(String name, String prettyName) {
// super(name, prettyName);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleDoubleProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralDouble(String name, double value) {
// super(name);
// this.defaultValue = value;
// this.value = new SimpleDoubleProperty(value);
// }
//
// public NeuralDouble(String name, String prettyName, double value) {
// super(name, prettyName);
// this.defaultValue = value;
// this.value = new SimpleDoubleProperty(value);
// }
//
// @Override
// public Number getValue() {
// return this.value.getValue();
// }
//
// @Override
// public Property<Number> valueProperty() {
// return this.value;
// }
//
// @Override
// public void setValue(Number value) {
// this.value.setValue(value);
// }
//
// @Override
// public void reset() {
// this.value.setValue(this.defaultValue);
// }
//
// public Double getRatio() {
// return this.ratio.get();
// }
//
// public DoubleProperty ratioProperty() {
// return this.ratio;
// }
//
// public void setRatio(Number ratio) {
// this.ratio.setValue(ratio);
// }
//
// public static StringConverter<Number> DOUBLE_CONVERTER = new StringConverter<Number>() {
// DecimalFormat format = new DecimalFormat("#.#####");
//
// @Override
// public String toString(Number t) {
// return format.format(t);
// }
//
// @Override
// public Number fromString(String string) {
// try {
// return Double.parseDouble(string);
// } catch (Exception e) {
// return 0;
// }
// }
// };
//
// }
| import com.cameronleger.neuralstylegui.model.NeuralImage;
import com.cameronleger.neuralstylegui.model.properties.NeuralDouble;
import javafx.beans.value.ObservableBooleanValue;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import org.reactfx.EventStreams;
import org.reactfx.Subscription;
import java.io.IOException;
import java.util.logging.Logger; | package com.cameronleger.neuralstylegui.component;
public class NeuralImageCell extends AnchorPane {
private static final Logger log = Logger.getLogger(NeuralImageCell.class.getName());
| // Path: src/main/java/com/cameronleger/neuralstylegui/model/NeuralImage.java
// public class NeuralImage {
// public static final int THUMBNAIL_SIZE = 225;
// private BooleanProperty selected;
// private StringProperty name;
// private ObjectProperty<File> imageFile;
// private AsyncImageProperty image;
// private DoubleProperty weight;
//
// public NeuralImage(File imageFile) {
// this.selected = new SimpleBooleanProperty(false);
// this.name = new SimpleStringProperty(imageFile.getName());
// this.imageFile = new SimpleObjectProperty<>(imageFile);
// this.image = new AsyncImageProperty(THUMBNAIL_SIZE, THUMBNAIL_SIZE);
// this.image.imageFileProperty().set(imageFile);
// this.weight = new SimpleDoubleProperty(1);
// }
//
// public BooleanProperty selectedProperty() {
// return selected;
// }
//
// public boolean isSelected() {
// return selected.get();
// }
//
// public void setSelected(boolean selected) {
// this.selected.set(selected);
// }
//
// public StringProperty nameProperty() {
// return name;
// }
//
// public String getName() {
// return name.get();
// }
//
// public void setName(String name) {
// this.name.set(name);
// }
//
// public ObjectProperty<File> imageFileProperty() {
// return imageFile;
// }
//
// public File getImageFile() {
// return imageFile.get();
// }
//
// public void setImageFile(File imageFile) {
// this.imageFile.set(imageFile);
// }
//
// public ObjectProperty<Image> imageProperty() {
// return image;
// }
//
// public Image getImage() {
// return image.get();
// }
//
// public void setImage(Image image) {
// this.image.set(image);
// }
//
// public DoubleProperty weightProperty() {
// return weight;
// }
//
// public double getWeight() {
// return weight.get();
// }
//
// public void setWeight(double weight) {
// this.weight.set(weight);
// }
// }
//
// Path: src/main/java/com/cameronleger/neuralstylegui/model/properties/NeuralDouble.java
// public class NeuralDouble extends NeuralProperty<Number> {
//
// private DoubleProperty value;
// private final static double GLOBAL_DEFAULT = 1.0;
// private DoubleProperty ratio = new SimpleDoubleProperty(1.0);
//
// public NeuralDouble(String name) {
// super(name);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleDoubleProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralDouble(String name, String prettyName) {
// super(name, prettyName);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleDoubleProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralDouble(String name, double value) {
// super(name);
// this.defaultValue = value;
// this.value = new SimpleDoubleProperty(value);
// }
//
// public NeuralDouble(String name, String prettyName, double value) {
// super(name, prettyName);
// this.defaultValue = value;
// this.value = new SimpleDoubleProperty(value);
// }
//
// @Override
// public Number getValue() {
// return this.value.getValue();
// }
//
// @Override
// public Property<Number> valueProperty() {
// return this.value;
// }
//
// @Override
// public void setValue(Number value) {
// this.value.setValue(value);
// }
//
// @Override
// public void reset() {
// this.value.setValue(this.defaultValue);
// }
//
// public Double getRatio() {
// return this.ratio.get();
// }
//
// public DoubleProperty ratioProperty() {
// return this.ratio;
// }
//
// public void setRatio(Number ratio) {
// this.ratio.setValue(ratio);
// }
//
// public static StringConverter<Number> DOUBLE_CONVERTER = new StringConverter<Number>() {
// DecimalFormat format = new DecimalFormat("#.#####");
//
// @Override
// public String toString(Number t) {
// return format.format(t);
// }
//
// @Override
// public Number fromString(String string) {
// try {
// return Double.parseDouble(string);
// } catch (Exception e) {
// return 0;
// }
// }
// };
//
// }
// Path: src/main/java/com/cameronleger/neuralstylegui/component/NeuralImageCell.java
import com.cameronleger.neuralstylegui.model.NeuralImage;
import com.cameronleger.neuralstylegui.model.properties.NeuralDouble;
import javafx.beans.value.ObservableBooleanValue;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import org.reactfx.EventStreams;
import org.reactfx.Subscription;
import java.io.IOException;
import java.util.logging.Logger;
package com.cameronleger.neuralstylegui.component;
public class NeuralImageCell extends AnchorPane {
private static final Logger log = Logger.getLogger(NeuralImageCell.class.getName());
| private NeuralImage neuralImage; |
cameronleger/neural-style-gui | src/main/java/com/cameronleger/neuralstylegui/component/NeuralImageCell.java | // Path: src/main/java/com/cameronleger/neuralstylegui/model/NeuralImage.java
// public class NeuralImage {
// public static final int THUMBNAIL_SIZE = 225;
// private BooleanProperty selected;
// private StringProperty name;
// private ObjectProperty<File> imageFile;
// private AsyncImageProperty image;
// private DoubleProperty weight;
//
// public NeuralImage(File imageFile) {
// this.selected = new SimpleBooleanProperty(false);
// this.name = new SimpleStringProperty(imageFile.getName());
// this.imageFile = new SimpleObjectProperty<>(imageFile);
// this.image = new AsyncImageProperty(THUMBNAIL_SIZE, THUMBNAIL_SIZE);
// this.image.imageFileProperty().set(imageFile);
// this.weight = new SimpleDoubleProperty(1);
// }
//
// public BooleanProperty selectedProperty() {
// return selected;
// }
//
// public boolean isSelected() {
// return selected.get();
// }
//
// public void setSelected(boolean selected) {
// this.selected.set(selected);
// }
//
// public StringProperty nameProperty() {
// return name;
// }
//
// public String getName() {
// return name.get();
// }
//
// public void setName(String name) {
// this.name.set(name);
// }
//
// public ObjectProperty<File> imageFileProperty() {
// return imageFile;
// }
//
// public File getImageFile() {
// return imageFile.get();
// }
//
// public void setImageFile(File imageFile) {
// this.imageFile.set(imageFile);
// }
//
// public ObjectProperty<Image> imageProperty() {
// return image;
// }
//
// public Image getImage() {
// return image.get();
// }
//
// public void setImage(Image image) {
// this.image.set(image);
// }
//
// public DoubleProperty weightProperty() {
// return weight;
// }
//
// public double getWeight() {
// return weight.get();
// }
//
// public void setWeight(double weight) {
// this.weight.set(weight);
// }
// }
//
// Path: src/main/java/com/cameronleger/neuralstylegui/model/properties/NeuralDouble.java
// public class NeuralDouble extends NeuralProperty<Number> {
//
// private DoubleProperty value;
// private final static double GLOBAL_DEFAULT = 1.0;
// private DoubleProperty ratio = new SimpleDoubleProperty(1.0);
//
// public NeuralDouble(String name) {
// super(name);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleDoubleProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralDouble(String name, String prettyName) {
// super(name, prettyName);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleDoubleProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralDouble(String name, double value) {
// super(name);
// this.defaultValue = value;
// this.value = new SimpleDoubleProperty(value);
// }
//
// public NeuralDouble(String name, String prettyName, double value) {
// super(name, prettyName);
// this.defaultValue = value;
// this.value = new SimpleDoubleProperty(value);
// }
//
// @Override
// public Number getValue() {
// return this.value.getValue();
// }
//
// @Override
// public Property<Number> valueProperty() {
// return this.value;
// }
//
// @Override
// public void setValue(Number value) {
// this.value.setValue(value);
// }
//
// @Override
// public void reset() {
// this.value.setValue(this.defaultValue);
// }
//
// public Double getRatio() {
// return this.ratio.get();
// }
//
// public DoubleProperty ratioProperty() {
// return this.ratio;
// }
//
// public void setRatio(Number ratio) {
// this.ratio.setValue(ratio);
// }
//
// public static StringConverter<Number> DOUBLE_CONVERTER = new StringConverter<Number>() {
// DecimalFormat format = new DecimalFormat("#.#####");
//
// @Override
// public String toString(Number t) {
// return format.format(t);
// }
//
// @Override
// public Number fromString(String string) {
// try {
// return Double.parseDouble(string);
// } catch (Exception e) {
// return 0;
// }
// }
// };
//
// }
| import com.cameronleger.neuralstylegui.model.NeuralImage;
import com.cameronleger.neuralstylegui.model.properties.NeuralDouble;
import javafx.beans.value.ObservableBooleanValue;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import org.reactfx.EventStreams;
import org.reactfx.Subscription;
import java.io.IOException;
import java.util.logging.Logger; | assert image != null : "fx:id=\"image\" was not injected.";
assert selected != null : "fx:id=\"selected\" was not injected.";
assert weight != null : "fx:id=\"weight\" was not injected.";
EventStreams.changesOf(selected.selectedProperty()).subscribe(selectedChange -> {
if (selectedChange.getNewValue()) {
getStyleClass().setAll("selected-image-cell");
} else {
getStyleClass().clear();
}
});
}
public void setNeuralImage(NeuralImage newNeuralImage) {
// Remove previous bindings if applicable
image.imageProperty().unbind();
if (neuralImage != null)
selected.selectedProperty().unbindBidirectional(neuralImage.selectedProperty());
if (weightChanges != null)
weightChanges.unsubscribe();
neuralImage = newNeuralImage;
if (neuralImage != null) {
image.imageProperty().bind(neuralImage.imageProperty());
selected.selectedProperty().bindBidirectional(neuralImage.selectedProperty());
// Event Streams for Weight to convert between double and string
weight.setText(String.valueOf(neuralImage.getWeight()));
weightChanges = EventStreams.changesOf(weight.focusedProperty()).subscribe(focusChange -> {
if (!focusChange.getNewValue()) { // focusing away from input | // Path: src/main/java/com/cameronleger/neuralstylegui/model/NeuralImage.java
// public class NeuralImage {
// public static final int THUMBNAIL_SIZE = 225;
// private BooleanProperty selected;
// private StringProperty name;
// private ObjectProperty<File> imageFile;
// private AsyncImageProperty image;
// private DoubleProperty weight;
//
// public NeuralImage(File imageFile) {
// this.selected = new SimpleBooleanProperty(false);
// this.name = new SimpleStringProperty(imageFile.getName());
// this.imageFile = new SimpleObjectProperty<>(imageFile);
// this.image = new AsyncImageProperty(THUMBNAIL_SIZE, THUMBNAIL_SIZE);
// this.image.imageFileProperty().set(imageFile);
// this.weight = new SimpleDoubleProperty(1);
// }
//
// public BooleanProperty selectedProperty() {
// return selected;
// }
//
// public boolean isSelected() {
// return selected.get();
// }
//
// public void setSelected(boolean selected) {
// this.selected.set(selected);
// }
//
// public StringProperty nameProperty() {
// return name;
// }
//
// public String getName() {
// return name.get();
// }
//
// public void setName(String name) {
// this.name.set(name);
// }
//
// public ObjectProperty<File> imageFileProperty() {
// return imageFile;
// }
//
// public File getImageFile() {
// return imageFile.get();
// }
//
// public void setImageFile(File imageFile) {
// this.imageFile.set(imageFile);
// }
//
// public ObjectProperty<Image> imageProperty() {
// return image;
// }
//
// public Image getImage() {
// return image.get();
// }
//
// public void setImage(Image image) {
// this.image.set(image);
// }
//
// public DoubleProperty weightProperty() {
// return weight;
// }
//
// public double getWeight() {
// return weight.get();
// }
//
// public void setWeight(double weight) {
// this.weight.set(weight);
// }
// }
//
// Path: src/main/java/com/cameronleger/neuralstylegui/model/properties/NeuralDouble.java
// public class NeuralDouble extends NeuralProperty<Number> {
//
// private DoubleProperty value;
// private final static double GLOBAL_DEFAULT = 1.0;
// private DoubleProperty ratio = new SimpleDoubleProperty(1.0);
//
// public NeuralDouble(String name) {
// super(name);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleDoubleProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralDouble(String name, String prettyName) {
// super(name, prettyName);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleDoubleProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralDouble(String name, double value) {
// super(name);
// this.defaultValue = value;
// this.value = new SimpleDoubleProperty(value);
// }
//
// public NeuralDouble(String name, String prettyName, double value) {
// super(name, prettyName);
// this.defaultValue = value;
// this.value = new SimpleDoubleProperty(value);
// }
//
// @Override
// public Number getValue() {
// return this.value.getValue();
// }
//
// @Override
// public Property<Number> valueProperty() {
// return this.value;
// }
//
// @Override
// public void setValue(Number value) {
// this.value.setValue(value);
// }
//
// @Override
// public void reset() {
// this.value.setValue(this.defaultValue);
// }
//
// public Double getRatio() {
// return this.ratio.get();
// }
//
// public DoubleProperty ratioProperty() {
// return this.ratio;
// }
//
// public void setRatio(Number ratio) {
// this.ratio.setValue(ratio);
// }
//
// public static StringConverter<Number> DOUBLE_CONVERTER = new StringConverter<Number>() {
// DecimalFormat format = new DecimalFormat("#.#####");
//
// @Override
// public String toString(Number t) {
// return format.format(t);
// }
//
// @Override
// public Number fromString(String string) {
// try {
// return Double.parseDouble(string);
// } catch (Exception e) {
// return 0;
// }
// }
// };
//
// }
// Path: src/main/java/com/cameronleger/neuralstylegui/component/NeuralImageCell.java
import com.cameronleger.neuralstylegui.model.NeuralImage;
import com.cameronleger.neuralstylegui.model.properties.NeuralDouble;
import javafx.beans.value.ObservableBooleanValue;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import org.reactfx.EventStreams;
import org.reactfx.Subscription;
import java.io.IOException;
import java.util.logging.Logger;
assert image != null : "fx:id=\"image\" was not injected.";
assert selected != null : "fx:id=\"selected\" was not injected.";
assert weight != null : "fx:id=\"weight\" was not injected.";
EventStreams.changesOf(selected.selectedProperty()).subscribe(selectedChange -> {
if (selectedChange.getNewValue()) {
getStyleClass().setAll("selected-image-cell");
} else {
getStyleClass().clear();
}
});
}
public void setNeuralImage(NeuralImage newNeuralImage) {
// Remove previous bindings if applicable
image.imageProperty().unbind();
if (neuralImage != null)
selected.selectedProperty().unbindBidirectional(neuralImage.selectedProperty());
if (weightChanges != null)
weightChanges.unsubscribe();
neuralImage = newNeuralImage;
if (neuralImage != null) {
image.imageProperty().bind(neuralImage.imageProperty());
selected.selectedProperty().bindBidirectional(neuralImage.selectedProperty());
// Event Streams for Weight to convert between double and string
weight.setText(String.valueOf(neuralImage.getWeight()));
weightChanges = EventStreams.changesOf(weight.focusedProperty()).subscribe(focusChange -> {
if (!focusChange.getNewValue()) { // focusing away from input | double newWeight = NeuralDouble.DOUBLE_CONVERTER.fromString(weight.getText()).doubleValue(); |
cameronleger/neural-style-gui | src/main/java/com/cameronleger/neuralstylegui/component/ChoiceView.java | // Path: src/main/java/com/cameronleger/neuralstylegui/model/properties/NeuralChoice.java
// public class NeuralChoice extends NeuralProperty<String> {
//
// private StringProperty value;
// private String[] choices;
// private final static String GLOBAL_DEFAULT = "";
//
// public NeuralChoice(String name) {
// super(name);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleStringProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralChoice(String name, String prettyName, String[] choices) {
// super(name, prettyName);
// this.choices = choices;
// this.defaultValue = choices[0];
// this.value = new SimpleStringProperty(choices[0]);
// }
//
// public NeuralChoice(String name, String prettyName, String value, String[] choices) {
// super(name, prettyName);
// this.choices = choices;
// this.defaultValue = value;
// this.value = new SimpleStringProperty(value);
// }
//
// public String[] getChoices() {
// return choices;
// }
//
// public void setChoices(String[] choices) {
// this.choices = choices;
// }
//
// @Override
// public String getValue() {
// return this.value.get();
// }
//
// @Override
// public Property<String> valueProperty() {
// return this.value;
// }
//
// @Override
// public void setValue(String value) {
// this.value.set(value);
// }
//
// @Override
// public void reset() {
// this.value.set(defaultValue);
// }
//
// }
| import com.cameronleger.neuralstylegui.model.properties.NeuralChoice;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Logger; | package com.cameronleger.neuralstylegui.component;
public class ChoiceView extends HBox {
private static final Logger log = Logger.getLogger(ChoiceView.class.getName());
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private Label label;
@FXML
private ChoiceBox<String> value;
@FXML
private Button resetButton;
| // Path: src/main/java/com/cameronleger/neuralstylegui/model/properties/NeuralChoice.java
// public class NeuralChoice extends NeuralProperty<String> {
//
// private StringProperty value;
// private String[] choices;
// private final static String GLOBAL_DEFAULT = "";
//
// public NeuralChoice(String name) {
// super(name);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleStringProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralChoice(String name, String prettyName, String[] choices) {
// super(name, prettyName);
// this.choices = choices;
// this.defaultValue = choices[0];
// this.value = new SimpleStringProperty(choices[0]);
// }
//
// public NeuralChoice(String name, String prettyName, String value, String[] choices) {
// super(name, prettyName);
// this.choices = choices;
// this.defaultValue = value;
// this.value = new SimpleStringProperty(value);
// }
//
// public String[] getChoices() {
// return choices;
// }
//
// public void setChoices(String[] choices) {
// this.choices = choices;
// }
//
// @Override
// public String getValue() {
// return this.value.get();
// }
//
// @Override
// public Property<String> valueProperty() {
// return this.value;
// }
//
// @Override
// public void setValue(String value) {
// this.value.set(value);
// }
//
// @Override
// public void reset() {
// this.value.set(defaultValue);
// }
//
// }
// Path: src/main/java/com/cameronleger/neuralstylegui/component/ChoiceView.java
import com.cameronleger.neuralstylegui.model.properties.NeuralChoice;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Logger;
package com.cameronleger.neuralstylegui.component;
public class ChoiceView extends HBox {
private static final Logger log = Logger.getLogger(ChoiceView.class.getName());
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private Label label;
@FXML
private ChoiceBox<String> value;
@FXML
private Button resetButton;
| private NeuralChoice property; |
cameronleger/neural-style-gui | src/main/java/com/cameronleger/neuralstylegui/component/TextView.java | // Path: src/main/java/com/cameronleger/neuralstylegui/model/properties/NeuralString.java
// public class NeuralString extends NeuralProperty<String> {
//
// private StringProperty value;
// private final static String GLOBAL_DEFAULT = "";
//
// public NeuralString(String name) {
// super(name);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleStringProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralString(String name, String prettyName) {
// super(name, prettyName);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleStringProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralString(String name, String prettyName, String value) {
// super(name, prettyName);
// this.defaultValue = value;
// this.value = new SimpleStringProperty(value);
// }
//
// @Override
// public String getValue() {
// return this.value.getValue();
// }
//
// @Override
// public Property<String> valueProperty() {
// return this.value;
// }
//
// @Override
// public void setValue(String value) {
// this.value.setValue(value);
// }
//
// @Override
// public void reset() {
// this.value.setValue(this.defaultValue);
// }
//
// }
| import com.cameronleger.neuralstylegui.model.properties.NeuralString;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Logger; | package com.cameronleger.neuralstylegui.component;
public class TextView extends HBox {
private static final Logger log = Logger.getLogger(TextView.class.getName());
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private Label label;
@FXML
private TextField value;
@FXML
private Button resetButton;
| // Path: src/main/java/com/cameronleger/neuralstylegui/model/properties/NeuralString.java
// public class NeuralString extends NeuralProperty<String> {
//
// private StringProperty value;
// private final static String GLOBAL_DEFAULT = "";
//
// public NeuralString(String name) {
// super(name);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleStringProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralString(String name, String prettyName) {
// super(name, prettyName);
// this.defaultValue = GLOBAL_DEFAULT;
// this.value = new SimpleStringProperty(GLOBAL_DEFAULT);
// }
//
// public NeuralString(String name, String prettyName, String value) {
// super(name, prettyName);
// this.defaultValue = value;
// this.value = new SimpleStringProperty(value);
// }
//
// @Override
// public String getValue() {
// return this.value.getValue();
// }
//
// @Override
// public Property<String> valueProperty() {
// return this.value;
// }
//
// @Override
// public void setValue(String value) {
// this.value.setValue(value);
// }
//
// @Override
// public void reset() {
// this.value.setValue(this.defaultValue);
// }
//
// }
// Path: src/main/java/com/cameronleger/neuralstylegui/component/TextView.java
import com.cameronleger.neuralstylegui.model.properties.NeuralString;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Logger;
package com.cameronleger.neuralstylegui.component;
public class TextView extends HBox {
private static final Logger log = Logger.getLogger(TextView.class.getName());
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private Label label;
@FXML
private TextField value;
@FXML
private Button resetButton;
| private NeuralString property; |
cameronleger/neural-style-gui | src/main/java/com/cameronleger/neuralstyle/FileUtils.java | // Path: src/main/java/com/cameronleger/neuralstylegui/model/NeuralImage.java
// public class NeuralImage {
// public static final int THUMBNAIL_SIZE = 225;
// private BooleanProperty selected;
// private StringProperty name;
// private ObjectProperty<File> imageFile;
// private AsyncImageProperty image;
// private DoubleProperty weight;
//
// public NeuralImage(File imageFile) {
// this.selected = new SimpleBooleanProperty(false);
// this.name = new SimpleStringProperty(imageFile.getName());
// this.imageFile = new SimpleObjectProperty<>(imageFile);
// this.image = new AsyncImageProperty(THUMBNAIL_SIZE, THUMBNAIL_SIZE);
// this.image.imageFileProperty().set(imageFile);
// this.weight = new SimpleDoubleProperty(1);
// }
//
// public BooleanProperty selectedProperty() {
// return selected;
// }
//
// public boolean isSelected() {
// return selected.get();
// }
//
// public void setSelected(boolean selected) {
// this.selected.set(selected);
// }
//
// public StringProperty nameProperty() {
// return name;
// }
//
// public String getName() {
// return name.get();
// }
//
// public void setName(String name) {
// this.name.set(name);
// }
//
// public ObjectProperty<File> imageFileProperty() {
// return imageFile;
// }
//
// public File getImageFile() {
// return imageFile.get();
// }
//
// public void setImageFile(File imageFile) {
// this.imageFile.set(imageFile);
// }
//
// public ObjectProperty<Image> imageProperty() {
// return image;
// }
//
// public Image getImage() {
// return image.get();
// }
//
// public void setImage(Image image) {
// this.image.set(image);
// }
//
// public DoubleProperty weightProperty() {
// return weight;
// }
//
// public double getWeight() {
// return weight.get();
// }
//
// public void setWeight(double weight) {
// this.weight.set(weight);
// }
// }
| import caffe.Loadcaffe;
import com.cameronleger.neuralstylegui.model.NeuralImage;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.protobuf.TextFormat;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; | }
public static NeuralStyleV4 loadStyle(File styleFile) {
if (!FileUtils.checkFileExists(styleFile)) {
log.log(Level.FINE, "Cannot load a missing file.");
return null;
}
NeuralStyleVersion v = loadStyleVersion(styleFile);
int version = v == null ? 0 : v.getVersion();
try {
NeuralStyleV4 neuralStyle = null;
if (version < 4) {
if ((neuralStyle = loadStyleV3(styleFile)) == null) {
if ((neuralStyle = loadStyleV2(styleFile)) == null) {
if ((neuralStyle = loadStyleV1(styleFile)) == null) {
log.log(Level.SEVERE, "Unable to load input style as any known version.");
}
}
}
} else {
if (v.getVersion() == 4) neuralStyle = loadStyleV4(styleFile);
}
return neuralStyle;
} catch (Exception e) {
log.log(Level.FINE, "Exception loading input style.");
log.log(Level.SEVERE, e.toString(), e);
return null;
}
}
| // Path: src/main/java/com/cameronleger/neuralstylegui/model/NeuralImage.java
// public class NeuralImage {
// public static final int THUMBNAIL_SIZE = 225;
// private BooleanProperty selected;
// private StringProperty name;
// private ObjectProperty<File> imageFile;
// private AsyncImageProperty image;
// private DoubleProperty weight;
//
// public NeuralImage(File imageFile) {
// this.selected = new SimpleBooleanProperty(false);
// this.name = new SimpleStringProperty(imageFile.getName());
// this.imageFile = new SimpleObjectProperty<>(imageFile);
// this.image = new AsyncImageProperty(THUMBNAIL_SIZE, THUMBNAIL_SIZE);
// this.image.imageFileProperty().set(imageFile);
// this.weight = new SimpleDoubleProperty(1);
// }
//
// public BooleanProperty selectedProperty() {
// return selected;
// }
//
// public boolean isSelected() {
// return selected.get();
// }
//
// public void setSelected(boolean selected) {
// this.selected.set(selected);
// }
//
// public StringProperty nameProperty() {
// return name;
// }
//
// public String getName() {
// return name.get();
// }
//
// public void setName(String name) {
// this.name.set(name);
// }
//
// public ObjectProperty<File> imageFileProperty() {
// return imageFile;
// }
//
// public File getImageFile() {
// return imageFile.get();
// }
//
// public void setImageFile(File imageFile) {
// this.imageFile.set(imageFile);
// }
//
// public ObjectProperty<Image> imageProperty() {
// return image;
// }
//
// public Image getImage() {
// return image.get();
// }
//
// public void setImage(Image image) {
// this.image.set(image);
// }
//
// public DoubleProperty weightProperty() {
// return weight;
// }
//
// public double getWeight() {
// return weight.get();
// }
//
// public void setWeight(double weight) {
// this.weight.set(weight);
// }
// }
// Path: src/main/java/com/cameronleger/neuralstyle/FileUtils.java
import caffe.Loadcaffe;
import com.cameronleger.neuralstylegui.model.NeuralImage;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.protobuf.TextFormat;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
}
public static NeuralStyleV4 loadStyle(File styleFile) {
if (!FileUtils.checkFileExists(styleFile)) {
log.log(Level.FINE, "Cannot load a missing file.");
return null;
}
NeuralStyleVersion v = loadStyleVersion(styleFile);
int version = v == null ? 0 : v.getVersion();
try {
NeuralStyleV4 neuralStyle = null;
if (version < 4) {
if ((neuralStyle = loadStyleV3(styleFile)) == null) {
if ((neuralStyle = loadStyleV2(styleFile)) == null) {
if ((neuralStyle = loadStyleV1(styleFile)) == null) {
log.log(Level.SEVERE, "Unable to load input style as any known version.");
}
}
}
} else {
if (v.getVersion() == 4) neuralStyle = loadStyleV4(styleFile);
}
return neuralStyle;
} catch (Exception e) {
log.log(Level.FINE, "Exception loading input style.");
log.log(Level.SEVERE, e.toString(), e);
return null;
}
}
| public static List<NeuralImage> getImages(File dir) { |
gperfutils/gprof | src/main/groovy/groovyx/gprof/callgraph/CallGraphReportMethodElement.java | // Path: src/main/groovy/groovyx/gprof/MethodInfo.java
// public class MethodInfo {
//
// private String className, methodName;
//
// public MethodInfo(String className, String methodName) {
// this.className = className;
// this.methodName = methodName;
// }
//
// public String getClassName() {
// return className;
// }
//
// public String getMethodName() {
// return methodName;
// }
//
// public String getName() {
// return className + "." + methodName;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// MethodInfo that = (MethodInfo) o;
//
// if (className != null ? !className.equals(that.className) : that.className != null) return false;
// if (methodName != null ? !methodName.equals(that.methodName) : that.methodName != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = className != null ? className.hashCode() : 0;
// result = 31 * result + (methodName != null ? methodName.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "MethodInfo{" +
// "className='" + className + '\'' +
// ", methodName='" + methodName + '\'' +
// '}';
// }
//
// }
| import groovyx.gprof.MethodInfo;
import java.util.*; | public long getIndex() {
return index;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Child child = (Child) o;
if (index != child.index) return false;
return true;
}
@Override
public int hashCode() {
return (int) (index ^ (index >>> 32));
}
@Override
public String toString() {
return "Child{" +
"index=" + index +
'}';
}
}
private long index, cycleIndex; | // Path: src/main/groovy/groovyx/gprof/MethodInfo.java
// public class MethodInfo {
//
// private String className, methodName;
//
// public MethodInfo(String className, String methodName) {
// this.className = className;
// this.methodName = methodName;
// }
//
// public String getClassName() {
// return className;
// }
//
// public String getMethodName() {
// return methodName;
// }
//
// public String getName() {
// return className + "." + methodName;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// MethodInfo that = (MethodInfo) o;
//
// if (className != null ? !className.equals(that.className) : that.className != null) return false;
// if (methodName != null ? !methodName.equals(that.methodName) : that.methodName != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = className != null ? className.hashCode() : 0;
// result = 31 * result + (methodName != null ? methodName.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "MethodInfo{" +
// "className='" + className + '\'' +
// ", methodName='" + methodName + '\'' +
// '}';
// }
//
// }
// Path: src/main/groovy/groovyx/gprof/callgraph/CallGraphReportMethodElement.java
import groovyx.gprof.MethodInfo;
import java.util.*;
public long getIndex() {
return index;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Child child = (Child) o;
if (index != child.index) return false;
return true;
}
@Override
public int hashCode() {
return (int) (index ^ (index >>> 32));
}
@Override
public String toString() {
return "Child{" +
"index=" + index +
'}';
}
}
private long index, cycleIndex; | private MethodInfo method; |
gperfutils/gprof | src/main/groovy/groovyx/gprof/flat/FlatReportPrinter.java | // Path: src/main/groovy/groovyx/gprof/ReportPrinter.java
// public interface ReportPrinter<E extends ReportElement> {
//
// void print(List<E> elements, PrintWriter writer);
//
// }
//
// Path: src/main/groovy/groovyx/gprof/ThreadInfo.java
// public class ThreadInfo {
//
// private String threadName;
// private long threadId;
//
// public ThreadInfo(String threadName, long threadId) {
// this.threadName = threadName;
// this.threadId = threadId;
// }
//
// public String getThreadName() {
// return threadName;
// }
//
// public long getThreadId() {
// return threadId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ThreadInfo that = (ThreadInfo) o;
//
// if (threadId != that.threadId) return false;
// if (threadName != null ? !threadName.equals(that.threadName) : that.threadName != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = threadName != null ? threadName.hashCode() : 0;
// result = 31 * result + (int) (threadId ^ (threadId >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// return "ThreadInfo{" +
// "threadName='" + threadName + '\'' +
// ", threadId=" + threadId +
// '}';
// }
// }
| import groovyx.gprof.ReportPrinter;
import groovyx.gprof.ThreadInfo;
import java.io.PrintWriter;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.*;
import static groovyx.gprof.flat.FlatReportPrinter.COLUMN.CALLS; | /*
* Copyright 2013 Masato Nagai
*
* 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 groovyx.gprof.flat;
public class FlatReportPrinter implements ReportPrinter<FlatReportThreadElement> {
private static String SP = " ";
private boolean separateThread;
public void setSeparateThread(boolean separateThread) {
this.separateThread = separateThread;
}
@Override
public void print(List<FlatReportThreadElement> threadElements, PrintWriter writer) {
for (Iterator<FlatReportThreadElement> it = threadElements.iterator(); it.hasNext();) {
FlatReportThreadElement threadElement = it.next();
if (threadElement.getMethodElements().isEmpty()) {
continue;
}
if (separateThread) {
printThreadHeader(threadElement, writer);
}
printThread(threadElement, writer);
if (separateThread && it.hasNext()) {
printThreadSeparator(writer);
}
}
writer.flush();
}
protected void printThreadHeader(FlatReportThreadElement threadElement, PrintWriter writer) { | // Path: src/main/groovy/groovyx/gprof/ReportPrinter.java
// public interface ReportPrinter<E extends ReportElement> {
//
// void print(List<E> elements, PrintWriter writer);
//
// }
//
// Path: src/main/groovy/groovyx/gprof/ThreadInfo.java
// public class ThreadInfo {
//
// private String threadName;
// private long threadId;
//
// public ThreadInfo(String threadName, long threadId) {
// this.threadName = threadName;
// this.threadId = threadId;
// }
//
// public String getThreadName() {
// return threadName;
// }
//
// public long getThreadId() {
// return threadId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ThreadInfo that = (ThreadInfo) o;
//
// if (threadId != that.threadId) return false;
// if (threadName != null ? !threadName.equals(that.threadName) : that.threadName != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = threadName != null ? threadName.hashCode() : 0;
// result = 31 * result + (int) (threadId ^ (threadId >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// return "ThreadInfo{" +
// "threadName='" + threadName + '\'' +
// ", threadId=" + threadId +
// '}';
// }
// }
// Path: src/main/groovy/groovyx/gprof/flat/FlatReportPrinter.java
import groovyx.gprof.ReportPrinter;
import groovyx.gprof.ThreadInfo;
import java.io.PrintWriter;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.*;
import static groovyx.gprof.flat.FlatReportPrinter.COLUMN.CALLS;
/*
* Copyright 2013 Masato Nagai
*
* 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 groovyx.gprof.flat;
public class FlatReportPrinter implements ReportPrinter<FlatReportThreadElement> {
private static String SP = " ";
private boolean separateThread;
public void setSeparateThread(boolean separateThread) {
this.separateThread = separateThread;
}
@Override
public void print(List<FlatReportThreadElement> threadElements, PrintWriter writer) {
for (Iterator<FlatReportThreadElement> it = threadElements.iterator(); it.hasNext();) {
FlatReportThreadElement threadElement = it.next();
if (threadElement.getMethodElements().isEmpty()) {
continue;
}
if (separateThread) {
printThreadHeader(threadElement, writer);
}
printThread(threadElement, writer);
if (separateThread && it.hasNext()) {
printThreadSeparator(writer);
}
}
writer.flush();
}
protected void printThreadHeader(FlatReportThreadElement threadElement, PrintWriter writer) { | ThreadInfo thread = threadElement.getThread(); |
gperfutils/gprof | src/main/groovy/groovyx/gprof/ProxyReport.java | // Path: src/main/groovy/groovyx/gprof/callgraph/CallGraphReport.java
// public class CallGraphReport extends Report {
//
// public CallGraphReport(CallTree callTree) {
// super(callTree);
// }
//
// @Override
// public void prettyPrint(Map args, PrintWriter writer) {
// boolean separateThread =
// args.get("separateThread") instanceof Boolean ?
// (Boolean) args.get("separateThread") : false;
//
// CallGraphReportNormalizer normalizer = new CallGraphReportNormalizer();
// normalizer.setSeparateThread(separateThread);
// List<CallGraphReportThreadElement> elements = normalizer.normalize(callTree);
//
// CallGraphReportPrinter printer = new CallGraphReportPrinter();
// printer.setSeparateThread(separateThread);
// printer.print(elements, writer);
// }
//
// }
//
// Path: src/main/groovy/groovyx/gprof/flat/FlatReport.java
// public class FlatReport extends Report {
//
// public FlatReport(CallTree callTree) {
// super(callTree);
// }
//
// @Override
// public void prettyPrint(Map args, PrintWriter writer) {
// boolean separateThread =
// args.get("separateThread") instanceof Boolean ?
// (Boolean) args.get("separateThread") : false;
//
// FlatReportNormalizer normalizer = new FlatReportNormalizer();
// normalizer.setSeparateThread(separateThread);
// List<FlatReportThreadElement> elements = normalizer.normalize(callTree);
// FlatReportPrinter printer = new FlatReportPrinter();
// printer.setSeparateThread(separateThread);
// printer.print(elements, writer);
// }
//
// }
| import groovyx.gprof.callgraph.CallGraphReport;
import groovyx.gprof.flat.FlatReport;
import java.io.PrintWriter;
import java.util.Map; | /*
* Copyright 2013 Masato Nagai
*
* 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 groovyx.gprof;
public class ProxyReport extends Report {
private Report flat;
private Report callGraph;
public ProxyReport(CallTree callTree) {
super(callTree); | // Path: src/main/groovy/groovyx/gprof/callgraph/CallGraphReport.java
// public class CallGraphReport extends Report {
//
// public CallGraphReport(CallTree callTree) {
// super(callTree);
// }
//
// @Override
// public void prettyPrint(Map args, PrintWriter writer) {
// boolean separateThread =
// args.get("separateThread") instanceof Boolean ?
// (Boolean) args.get("separateThread") : false;
//
// CallGraphReportNormalizer normalizer = new CallGraphReportNormalizer();
// normalizer.setSeparateThread(separateThread);
// List<CallGraphReportThreadElement> elements = normalizer.normalize(callTree);
//
// CallGraphReportPrinter printer = new CallGraphReportPrinter();
// printer.setSeparateThread(separateThread);
// printer.print(elements, writer);
// }
//
// }
//
// Path: src/main/groovy/groovyx/gprof/flat/FlatReport.java
// public class FlatReport extends Report {
//
// public FlatReport(CallTree callTree) {
// super(callTree);
// }
//
// @Override
// public void prettyPrint(Map args, PrintWriter writer) {
// boolean separateThread =
// args.get("separateThread") instanceof Boolean ?
// (Boolean) args.get("separateThread") : false;
//
// FlatReportNormalizer normalizer = new FlatReportNormalizer();
// normalizer.setSeparateThread(separateThread);
// List<FlatReportThreadElement> elements = normalizer.normalize(callTree);
// FlatReportPrinter printer = new FlatReportPrinter();
// printer.setSeparateThread(separateThread);
// printer.print(elements, writer);
// }
//
// }
// Path: src/main/groovy/groovyx/gprof/ProxyReport.java
import groovyx.gprof.callgraph.CallGraphReport;
import groovyx.gprof.flat.FlatReport;
import java.io.PrintWriter;
import java.util.Map;
/*
* Copyright 2013 Masato Nagai
*
* 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 groovyx.gprof;
public class ProxyReport extends Report {
private Report flat;
private Report callGraph;
public ProxyReport(CallTree callTree) {
super(callTree); | flat = new FlatReport(callTree); |
gperfutils/gprof | src/main/groovy/groovyx/gprof/ProxyReport.java | // Path: src/main/groovy/groovyx/gprof/callgraph/CallGraphReport.java
// public class CallGraphReport extends Report {
//
// public CallGraphReport(CallTree callTree) {
// super(callTree);
// }
//
// @Override
// public void prettyPrint(Map args, PrintWriter writer) {
// boolean separateThread =
// args.get("separateThread") instanceof Boolean ?
// (Boolean) args.get("separateThread") : false;
//
// CallGraphReportNormalizer normalizer = new CallGraphReportNormalizer();
// normalizer.setSeparateThread(separateThread);
// List<CallGraphReportThreadElement> elements = normalizer.normalize(callTree);
//
// CallGraphReportPrinter printer = new CallGraphReportPrinter();
// printer.setSeparateThread(separateThread);
// printer.print(elements, writer);
// }
//
// }
//
// Path: src/main/groovy/groovyx/gprof/flat/FlatReport.java
// public class FlatReport extends Report {
//
// public FlatReport(CallTree callTree) {
// super(callTree);
// }
//
// @Override
// public void prettyPrint(Map args, PrintWriter writer) {
// boolean separateThread =
// args.get("separateThread") instanceof Boolean ?
// (Boolean) args.get("separateThread") : false;
//
// FlatReportNormalizer normalizer = new FlatReportNormalizer();
// normalizer.setSeparateThread(separateThread);
// List<FlatReportThreadElement> elements = normalizer.normalize(callTree);
// FlatReportPrinter printer = new FlatReportPrinter();
// printer.setSeparateThread(separateThread);
// printer.print(elements, writer);
// }
//
// }
| import groovyx.gprof.callgraph.CallGraphReport;
import groovyx.gprof.flat.FlatReport;
import java.io.PrintWriter;
import java.util.Map; | /*
* Copyright 2013 Masato Nagai
*
* 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 groovyx.gprof;
public class ProxyReport extends Report {
private Report flat;
private Report callGraph;
public ProxyReport(CallTree callTree) {
super(callTree);
flat = new FlatReport(callTree); | // Path: src/main/groovy/groovyx/gprof/callgraph/CallGraphReport.java
// public class CallGraphReport extends Report {
//
// public CallGraphReport(CallTree callTree) {
// super(callTree);
// }
//
// @Override
// public void prettyPrint(Map args, PrintWriter writer) {
// boolean separateThread =
// args.get("separateThread") instanceof Boolean ?
// (Boolean) args.get("separateThread") : false;
//
// CallGraphReportNormalizer normalizer = new CallGraphReportNormalizer();
// normalizer.setSeparateThread(separateThread);
// List<CallGraphReportThreadElement> elements = normalizer.normalize(callTree);
//
// CallGraphReportPrinter printer = new CallGraphReportPrinter();
// printer.setSeparateThread(separateThread);
// printer.print(elements, writer);
// }
//
// }
//
// Path: src/main/groovy/groovyx/gprof/flat/FlatReport.java
// public class FlatReport extends Report {
//
// public FlatReport(CallTree callTree) {
// super(callTree);
// }
//
// @Override
// public void prettyPrint(Map args, PrintWriter writer) {
// boolean separateThread =
// args.get("separateThread") instanceof Boolean ?
// (Boolean) args.get("separateThread") : false;
//
// FlatReportNormalizer normalizer = new FlatReportNormalizer();
// normalizer.setSeparateThread(separateThread);
// List<FlatReportThreadElement> elements = normalizer.normalize(callTree);
// FlatReportPrinter printer = new FlatReportPrinter();
// printer.setSeparateThread(separateThread);
// printer.print(elements, writer);
// }
//
// }
// Path: src/main/groovy/groovyx/gprof/ProxyReport.java
import groovyx.gprof.callgraph.CallGraphReport;
import groovyx.gprof.flat.FlatReport;
import java.io.PrintWriter;
import java.util.Map;
/*
* Copyright 2013 Masato Nagai
*
* 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 groovyx.gprof;
public class ProxyReport extends Report {
private Report flat;
private Report callGraph;
public ProxyReport(CallTree callTree) {
super(callTree);
flat = new FlatReport(callTree); | callGraph = new CallGraphReport(callTree); |
gperfutils/gprof | src/main/groovy/groovyx/gprof/callgraph/CallGraphReportPrinter.java | // Path: src/main/groovy/groovyx/gprof/ReportPrinter.java
// public interface ReportPrinter<E extends ReportElement> {
//
// void print(List<E> elements, PrintWriter writer);
//
// }
//
// Path: src/main/groovy/groovyx/gprof/ThreadInfo.java
// public class ThreadInfo {
//
// private String threadName;
// private long threadId;
//
// public ThreadInfo(String threadName, long threadId) {
// this.threadName = threadName;
// this.threadId = threadId;
// }
//
// public String getThreadName() {
// return threadName;
// }
//
// public long getThreadId() {
// return threadId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ThreadInfo that = (ThreadInfo) o;
//
// if (threadId != that.threadId) return false;
// if (threadName != null ? !threadName.equals(that.threadName) : that.threadName != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = threadName != null ? threadName.hashCode() : 0;
// result = 31 * result + (int) (threadId ^ (threadId >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// return "ThreadInfo{" +
// "threadName='" + threadName + '\'' +
// ", threadId=" + threadId +
// '}';
// }
// }
//
// Path: src/main/groovy/groovyx/gprof/Utils.java
// public class Utils {
//
// public static HashMap hashMap(Object...kvs) {
// HashMap hashMap = new HashMap();
// for (int i = 0, n = kvs.length; i < n; i += 2) {
// hashMap.put(kvs[i], kvs[i + 1]);
// }
// return hashMap;
// }
//
// public static String join(Collection coll, String separator) {
// StringBuilder sb = new StringBuilder();
// for (Iterator it = coll.iterator();;) {
// sb.append(it.next().toString());
// if (it.hasNext()) {
// sb.append(separator);
// } else {
// break;
// }
// }
// return sb.toString();
// }
//
// }
| import groovyx.gprof.ReportPrinter;
import groovyx.gprof.ThreadInfo;
import groovyx.gprof.Utils;
import java.io.PrintWriter;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.*; |
public static String childCalls(long calls, long totalCalls) {
return String.format("%d/%d", calls, totalCalls);
}
public static String cycleChildCalls(long calls) {
return String.format("%d", calls);
}
}
@Override
public void print(List<CallGraphReportThreadElement> threadElements, PrintWriter writer) {
for (Iterator<CallGraphReportThreadElement> it = threadElements.iterator(); it.hasNext();) {
CallGraphReportThreadElement threadElement = it.next();
if (threadElement.getSubElements().isEmpty()) {
continue;
}
if (separateThread) {
printThreadHeader(threadElement, writer);
}
printThread(threadElement, writer);
if (separateThread && it.hasNext()) {
printThreadSeparator(writer);
}
}
writer.flush();
}
protected void printThreadHeader(CallGraphReportThreadElement threadElement, PrintWriter writer) { | // Path: src/main/groovy/groovyx/gprof/ReportPrinter.java
// public interface ReportPrinter<E extends ReportElement> {
//
// void print(List<E> elements, PrintWriter writer);
//
// }
//
// Path: src/main/groovy/groovyx/gprof/ThreadInfo.java
// public class ThreadInfo {
//
// private String threadName;
// private long threadId;
//
// public ThreadInfo(String threadName, long threadId) {
// this.threadName = threadName;
// this.threadId = threadId;
// }
//
// public String getThreadName() {
// return threadName;
// }
//
// public long getThreadId() {
// return threadId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ThreadInfo that = (ThreadInfo) o;
//
// if (threadId != that.threadId) return false;
// if (threadName != null ? !threadName.equals(that.threadName) : that.threadName != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = threadName != null ? threadName.hashCode() : 0;
// result = 31 * result + (int) (threadId ^ (threadId >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// return "ThreadInfo{" +
// "threadName='" + threadName + '\'' +
// ", threadId=" + threadId +
// '}';
// }
// }
//
// Path: src/main/groovy/groovyx/gprof/Utils.java
// public class Utils {
//
// public static HashMap hashMap(Object...kvs) {
// HashMap hashMap = new HashMap();
// for (int i = 0, n = kvs.length; i < n; i += 2) {
// hashMap.put(kvs[i], kvs[i + 1]);
// }
// return hashMap;
// }
//
// public static String join(Collection coll, String separator) {
// StringBuilder sb = new StringBuilder();
// for (Iterator it = coll.iterator();;) {
// sb.append(it.next().toString());
// if (it.hasNext()) {
// sb.append(separator);
// } else {
// break;
// }
// }
// return sb.toString();
// }
//
// }
// Path: src/main/groovy/groovyx/gprof/callgraph/CallGraphReportPrinter.java
import groovyx.gprof.ReportPrinter;
import groovyx.gprof.ThreadInfo;
import groovyx.gprof.Utils;
import java.io.PrintWriter;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.*;
public static String childCalls(long calls, long totalCalls) {
return String.format("%d/%d", calls, totalCalls);
}
public static String cycleChildCalls(long calls) {
return String.format("%d", calls);
}
}
@Override
public void print(List<CallGraphReportThreadElement> threadElements, PrintWriter writer) {
for (Iterator<CallGraphReportThreadElement> it = threadElements.iterator(); it.hasNext();) {
CallGraphReportThreadElement threadElement = it.next();
if (threadElement.getSubElements().isEmpty()) {
continue;
}
if (separateThread) {
printThreadHeader(threadElement, writer);
}
printThread(threadElement, writer);
if (separateThread && it.hasNext()) {
printThreadSeparator(writer);
}
}
writer.flush();
}
protected void printThreadHeader(CallGraphReportThreadElement threadElement, PrintWriter writer) { | ThreadInfo thread = threadElement.getThread(); |
gperfutils/gprof | src/main/groovy/groovyx/gprof/callgraph/CallGraphReportPrinter.java | // Path: src/main/groovy/groovyx/gprof/ReportPrinter.java
// public interface ReportPrinter<E extends ReportElement> {
//
// void print(List<E> elements, PrintWriter writer);
//
// }
//
// Path: src/main/groovy/groovyx/gprof/ThreadInfo.java
// public class ThreadInfo {
//
// private String threadName;
// private long threadId;
//
// public ThreadInfo(String threadName, long threadId) {
// this.threadName = threadName;
// this.threadId = threadId;
// }
//
// public String getThreadName() {
// return threadName;
// }
//
// public long getThreadId() {
// return threadId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ThreadInfo that = (ThreadInfo) o;
//
// if (threadId != that.threadId) return false;
// if (threadName != null ? !threadName.equals(that.threadName) : that.threadName != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = threadName != null ? threadName.hashCode() : 0;
// result = 31 * result + (int) (threadId ^ (threadId >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// return "ThreadInfo{" +
// "threadName='" + threadName + '\'' +
// ", threadId=" + threadId +
// '}';
// }
// }
//
// Path: src/main/groovy/groovyx/gprof/Utils.java
// public class Utils {
//
// public static HashMap hashMap(Object...kvs) {
// HashMap hashMap = new HashMap();
// for (int i = 0, n = kvs.length; i < n; i += 2) {
// hashMap.put(kvs[i], kvs[i + 1]);
// }
// return hashMap;
// }
//
// public static String join(Collection coll, String separator) {
// StringBuilder sb = new StringBuilder();
// for (Iterator it = coll.iterator();;) {
// sb.append(it.next().toString());
// if (it.hasNext()) {
// sb.append(separator);
// } else {
// break;
// }
// }
// return sb.toString();
// }
//
// }
| import groovyx.gprof.ReportPrinter;
import groovyx.gprof.ThreadInfo;
import groovyx.gprof.Utils;
import java.io.PrintWriter;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.*; | }
protected void printThreadHeader(CallGraphReportThreadElement threadElement, PrintWriter writer) {
ThreadInfo thread = threadElement.getThread();
writer.printf("#%d %s%n%n", thread.getThreadId(), thread.getThreadName());
}
protected void printThreadSeparator(PrintWriter writer) {
writer.println();
}
protected void printThread(CallGraphReportThreadElement te, PrintWriter writer) {
Collection<CallGraphReportMethodElement> elements = te.getSubElements();
Map<Long, CallGraphReportMethodElement> graphTable = new HashMap();
for (CallGraphReportMethodElement entry : elements) {
graphTable.put(entry.getIndex(), entry);
}
List lines = new ArrayList();
Map<Column, String> header = new HashMap();
for (Column col : Column.values()) {
header.put(col, col.toString());
}
lines.add(header);
for (CallGraphReportMethodElement element : elements) {
if (element.getParents().isEmpty()) {
} else {
for (CallGraphReportMethodElement.Parent parent : element.getParents().values()) {
if (parent.getIndex() == 0) {
lines.add( | // Path: src/main/groovy/groovyx/gprof/ReportPrinter.java
// public interface ReportPrinter<E extends ReportElement> {
//
// void print(List<E> elements, PrintWriter writer);
//
// }
//
// Path: src/main/groovy/groovyx/gprof/ThreadInfo.java
// public class ThreadInfo {
//
// private String threadName;
// private long threadId;
//
// public ThreadInfo(String threadName, long threadId) {
// this.threadName = threadName;
// this.threadId = threadId;
// }
//
// public String getThreadName() {
// return threadName;
// }
//
// public long getThreadId() {
// return threadId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ThreadInfo that = (ThreadInfo) o;
//
// if (threadId != that.threadId) return false;
// if (threadName != null ? !threadName.equals(that.threadName) : that.threadName != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = threadName != null ? threadName.hashCode() : 0;
// result = 31 * result + (int) (threadId ^ (threadId >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// return "ThreadInfo{" +
// "threadName='" + threadName + '\'' +
// ", threadId=" + threadId +
// '}';
// }
// }
//
// Path: src/main/groovy/groovyx/gprof/Utils.java
// public class Utils {
//
// public static HashMap hashMap(Object...kvs) {
// HashMap hashMap = new HashMap();
// for (int i = 0, n = kvs.length; i < n; i += 2) {
// hashMap.put(kvs[i], kvs[i + 1]);
// }
// return hashMap;
// }
//
// public static String join(Collection coll, String separator) {
// StringBuilder sb = new StringBuilder();
// for (Iterator it = coll.iterator();;) {
// sb.append(it.next().toString());
// if (it.hasNext()) {
// sb.append(separator);
// } else {
// break;
// }
// }
// return sb.toString();
// }
//
// }
// Path: src/main/groovy/groovyx/gprof/callgraph/CallGraphReportPrinter.java
import groovyx.gprof.ReportPrinter;
import groovyx.gprof.ThreadInfo;
import groovyx.gprof.Utils;
import java.io.PrintWriter;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.*;
}
protected void printThreadHeader(CallGraphReportThreadElement threadElement, PrintWriter writer) {
ThreadInfo thread = threadElement.getThread();
writer.printf("#%d %s%n%n", thread.getThreadId(), thread.getThreadName());
}
protected void printThreadSeparator(PrintWriter writer) {
writer.println();
}
protected void printThread(CallGraphReportThreadElement te, PrintWriter writer) {
Collection<CallGraphReportMethodElement> elements = te.getSubElements();
Map<Long, CallGraphReportMethodElement> graphTable = new HashMap();
for (CallGraphReportMethodElement entry : elements) {
graphTable.put(entry.getIndex(), entry);
}
List lines = new ArrayList();
Map<Column, String> header = new HashMap();
for (Column col : Column.values()) {
header.put(col, col.toString());
}
lines.add(header);
for (CallGraphReportMethodElement element : elements) {
if (element.getParents().isEmpty()) {
} else {
for (CallGraphReportMethodElement.Parent parent : element.getParents().values()) {
if (parent.getIndex() == 0) {
lines.add( | Utils.hashMap( |
nomemory/java-bean-validation-extension | src/main/java/net/andreinc/jbvext/annotations/misc/OneOfDoubles.java | // Path: src/main/java/net/andreinc/jbvext/annotations/misc/validators/OneOfDoublesValidator.java
// public class OneOfDoublesValidator extends OneOfValidator<OneOfDoubles, Double> {
//
// @Override
// public boolean isValid(Double value, ConstraintValidatorContext context) {
// return super.isValid(value, ArrayUtils.toObject(annotation.value()), Objects::equals, context);
// }
//
// }
| import net.andreinc.jbvext.annotations.misc.validators.OneOfDoublesValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME; | package net.andreinc.jbvext.annotations.misc;
@Documented
@Retention(RUNTIME) | // Path: src/main/java/net/andreinc/jbvext/annotations/misc/validators/OneOfDoublesValidator.java
// public class OneOfDoublesValidator extends OneOfValidator<OneOfDoubles, Double> {
//
// @Override
// public boolean isValid(Double value, ConstraintValidatorContext context) {
// return super.isValid(value, ArrayUtils.toObject(annotation.value()), Objects::equals, context);
// }
//
// }
// Path: src/main/java/net/andreinc/jbvext/annotations/misc/OneOfDoubles.java
import net.andreinc.jbvext.annotations.misc.validators.OneOfDoublesValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
package net.andreinc.jbvext.annotations.misc;
@Documented
@Retention(RUNTIME) | @Constraint(validatedBy = OneOfDoublesValidator.class) |
nomemory/java-bean-validation-extension | src/main/java/net/andreinc/jbvext/annotations/misc/OneOfIntegers.java | // Path: src/main/java/net/andreinc/jbvext/annotations/misc/validators/OneOfIntegersValidator.java
// public class OneOfIntegersValidator extends OneOfValidator<OneOfIntegers, Integer> {
//
// @Override
// public boolean isValid(Integer value, ConstraintValidatorContext context) {
// return super.isValid(value, ArrayUtils.toObject(annotation.value()), Objects::equals, context);
// }
// }
| import net.andreinc.jbvext.annotations.misc.validators.OneOfIntegersValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME; | package net.andreinc.jbvext.annotations.misc;
@Documented
@Retention(RUNTIME) | // Path: src/main/java/net/andreinc/jbvext/annotations/misc/validators/OneOfIntegersValidator.java
// public class OneOfIntegersValidator extends OneOfValidator<OneOfIntegers, Integer> {
//
// @Override
// public boolean isValid(Integer value, ConstraintValidatorContext context) {
// return super.isValid(value, ArrayUtils.toObject(annotation.value()), Objects::equals, context);
// }
// }
// Path: src/main/java/net/andreinc/jbvext/annotations/misc/OneOfIntegers.java
import net.andreinc.jbvext.annotations.misc.validators.OneOfIntegersValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
package net.andreinc.jbvext.annotations.misc;
@Documented
@Retention(RUNTIME) | @Constraint(validatedBy = OneOfIntegersValidator.class) |
nomemory/java-bean-validation-extension | src/main/java/net/andreinc/jbvext/annotations/misc/OneOfStrings.java | // Path: src/main/java/net/andreinc/jbvext/annotations/misc/validators/OneOfStringsValidator.java
// public class OneOfStringsValidator extends OneOfValidator<OneOfStrings, String> {
//
// @Override
// public boolean isValid(String value, ConstraintValidatorContext context) {
// return super.isValid(value, annotation.value(), StringUtils::equals, context);
// }
// }
| import net.andreinc.jbvext.annotations.misc.validators.OneOfStringsValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME; | package net.andreinc.jbvext.annotations.misc;
@Documented
@Retention(RUNTIME) | // Path: src/main/java/net/andreinc/jbvext/annotations/misc/validators/OneOfStringsValidator.java
// public class OneOfStringsValidator extends OneOfValidator<OneOfStrings, String> {
//
// @Override
// public boolean isValid(String value, ConstraintValidatorContext context) {
// return super.isValid(value, annotation.value(), StringUtils::equals, context);
// }
// }
// Path: src/main/java/net/andreinc/jbvext/annotations/misc/OneOfStrings.java
import net.andreinc.jbvext.annotations.misc.validators.OneOfStringsValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
package net.andreinc.jbvext.annotations.misc;
@Documented
@Retention(RUNTIME) | @Constraint(validatedBy = OneOfStringsValidator.class) |
nomemory/java-bean-validation-extension | src/main/java/net/andreinc/jbvext/annotations/str/validators/CCValidator.java | // Path: src/main/java/net/andreinc/jbvext/annotations/str/CreditCardType.java
// public enum CreditCardType {
//
// AMEX(CreditCardValidator.AMEX),
// DINERS(CreditCardValidator.DINERS),
// DISCOVER(CreditCardValidator.DISCOVER),
// MASTERCARD(CreditCardValidator.MASTERCARD),
// VISA(CreditCardValidator.VISA),
// VPAY(CreditCardValidator.VPAY),
// ALL(
// CreditCardValidator.AMEX +
// CreditCardValidator.DINERS +
// CreditCardValidator.DISCOVER +
// CreditCardValidator.MASTERCARD +
// CreditCardValidator.VISA +
// CreditCardValidator.VPAY
// );
//
// private Long internalValue;
//
// CreditCardType(Long internalValue) {
// this.internalValue = internalValue;
// }
//
// public Long getInternalValue() {
// return internalValue;
// }
// }
| import net.andreinc.jbvext.annotations.str.CC;
import net.andreinc.jbvext.annotations.str.CreditCardType;
import org.apache.commons.validator.routines.CreditCardValidator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext; | package net.andreinc.jbvext.annotations.str.validators;
public class CCValidator implements ConstraintValidator<CC, String> {
private CC annotation;
@Override
public void initialize(CC constraintAnnotation) {
this.annotation = constraintAnnotation;
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (null == value) {
return false;
}
| // Path: src/main/java/net/andreinc/jbvext/annotations/str/CreditCardType.java
// public enum CreditCardType {
//
// AMEX(CreditCardValidator.AMEX),
// DINERS(CreditCardValidator.DINERS),
// DISCOVER(CreditCardValidator.DISCOVER),
// MASTERCARD(CreditCardValidator.MASTERCARD),
// VISA(CreditCardValidator.VISA),
// VPAY(CreditCardValidator.VPAY),
// ALL(
// CreditCardValidator.AMEX +
// CreditCardValidator.DINERS +
// CreditCardValidator.DISCOVER +
// CreditCardValidator.MASTERCARD +
// CreditCardValidator.VISA +
// CreditCardValidator.VPAY
// );
//
// private Long internalValue;
//
// CreditCardType(Long internalValue) {
// this.internalValue = internalValue;
// }
//
// public Long getInternalValue() {
// return internalValue;
// }
// }
// Path: src/main/java/net/andreinc/jbvext/annotations/str/validators/CCValidator.java
import net.andreinc.jbvext.annotations.str.CC;
import net.andreinc.jbvext.annotations.str.CreditCardType;
import org.apache.commons.validator.routines.CreditCardValidator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
package net.andreinc.jbvext.annotations.str.validators;
public class CCValidator implements ConstraintValidator<CC, String> {
private CC annotation;
@Override
public void initialize(CC constraintAnnotation) {
this.annotation = constraintAnnotation;
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (null == value) {
return false;
}
| CreditCardType[] types = annotation.value(); |
nomemory/java-bean-validation-extension | src/main/java/net/andreinc/jbvext/annotations/misc/OneOfChars.java | // Path: src/main/java/net/andreinc/jbvext/annotations/misc/validators/OneOfCharsValidator.java
// public class OneOfCharsValidator extends OneOfValidator<OneOfChars, Character> {
// @Override
// public boolean isValid(Character value, ConstraintValidatorContext context) {
// return super.isValid(value, ArrayUtils.toObject(annotation.value()), Objects::equals, context);
// }
// }
| import net.andreinc.jbvext.annotations.misc.validators.OneOfCharsValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME; | package net.andreinc.jbvext.annotations.misc;
@Documented
@Retention(RUNTIME) | // Path: src/main/java/net/andreinc/jbvext/annotations/misc/validators/OneOfCharsValidator.java
// public class OneOfCharsValidator extends OneOfValidator<OneOfChars, Character> {
// @Override
// public boolean isValid(Character value, ConstraintValidatorContext context) {
// return super.isValid(value, ArrayUtils.toObject(annotation.value()), Objects::equals, context);
// }
// }
// Path: src/main/java/net/andreinc/jbvext/annotations/misc/OneOfChars.java
import net.andreinc.jbvext.annotations.misc.validators.OneOfCharsValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
package net.andreinc.jbvext.annotations.misc;
@Documented
@Retention(RUNTIME) | @Constraint(validatedBy = OneOfCharsValidator.class) |
nomemory/java-bean-validation-extension | src/main/java/net/andreinc/jbvext/annotations/misc/OneOfLongs.java | // Path: src/main/java/net/andreinc/jbvext/annotations/misc/validators/OneOfLongsValidator.java
// public class OneOfLongsValidator extends OneOfValidator<OneOfLongs, Long> {
//
// @Override
// public boolean isValid(Long value, ConstraintValidatorContext context) {
// return super.isValid(value, ArrayUtils.toObject(annotation.value()), Objects::equals, context);
// }
// }
| import net.andreinc.jbvext.annotations.misc.validators.OneOfLongsValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME; | package net.andreinc.jbvext.annotations.misc;
@Documented
@Retention(RUNTIME) | // Path: src/main/java/net/andreinc/jbvext/annotations/misc/validators/OneOfLongsValidator.java
// public class OneOfLongsValidator extends OneOfValidator<OneOfLongs, Long> {
//
// @Override
// public boolean isValid(Long value, ConstraintValidatorContext context) {
// return super.isValid(value, ArrayUtils.toObject(annotation.value()), Objects::equals, context);
// }
// }
// Path: src/main/java/net/andreinc/jbvext/annotations/misc/OneOfLongs.java
import net.andreinc.jbvext.annotations.misc.validators.OneOfLongsValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
package net.andreinc.jbvext.annotations.misc;
@Documented
@Retention(RUNTIME) | @Constraint(validatedBy = OneOfLongsValidator.class) |
nomemory/java-bean-validation-extension | src/main/java/net/andreinc/jbvext/annotations/str/validators/ParseableValidator.java | // Path: src/main/java/net/andreinc/jbvext/annotations/str/ParseableType.java
// @AllArgsConstructor
// public enum ParseableType {
// TO_SHORT("Short"),
// TO_INT("Integer"),
// TO_LONG("Long"),
// TO_DOUBLE("Double"),
// TO_FLOAT("Float");
// @Getter
// private String friendlyName;
// }
| import net.andreinc.jbvext.annotations.str.Parseable;
import net.andreinc.jbvext.annotations.str.ParseableType;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.function.Function; | package net.andreinc.jbvext.annotations.str.validators;
public class ParseableValidator implements ConstraintValidator<Parseable, String> {
private Parseable annotation;
@Override
public void initialize(Parseable constraintAnnotation) {
this.annotation = constraintAnnotation;
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (null == value) {
return false;
}
| // Path: src/main/java/net/andreinc/jbvext/annotations/str/ParseableType.java
// @AllArgsConstructor
// public enum ParseableType {
// TO_SHORT("Short"),
// TO_INT("Integer"),
// TO_LONG("Long"),
// TO_DOUBLE("Double"),
// TO_FLOAT("Float");
// @Getter
// private String friendlyName;
// }
// Path: src/main/java/net/andreinc/jbvext/annotations/str/validators/ParseableValidator.java
import net.andreinc.jbvext.annotations.str.Parseable;
import net.andreinc.jbvext.annotations.str.ParseableType;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.function.Function;
package net.andreinc.jbvext.annotations.str.validators;
public class ParseableValidator implements ConstraintValidator<Parseable, String> {
private Parseable annotation;
@Override
public void initialize(Parseable constraintAnnotation) {
this.annotation = constraintAnnotation;
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (null == value) {
return false;
}
| ParseableType type = annotation.value(); |
wtud/tsap | tsap/src/org/tribler/tsap/OnQuitDialog.java | // Path: tsap/src/org/renpy/android/PythonService.java
// public class PythonService extends Service implements Runnable {
//
// // Thread for Python code
// private Thread pythonThread = null;
//
// // Python environment variables
// private String androidPrivate;
// private String androidArgument;
// private String pythonHome;
// private String pythonPath;
//
// // Argument to pass to Python code,
// private String pythonServiceArgument;
//
// private Notification notification;
// private String serviceTitle;
// private static PythonService pyService;
//
// @Override
// public IBinder onBind(Intent arg0) {
// return null;
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// if (pythonThread != null) {
// Log.v("python service", "service exists, do not start again");
// return START_NOT_STICKY;
// }
//
// pyService = this;
// Bundle extras = intent.getExtras();
// androidPrivate = extras.getString("androidPrivate");
// // service code is located in current directory (not in /service
// // anymore!)
// androidArgument = extras.getString("androidArgument");
// pythonHome = extras.getString("pythonHome");
// pythonPath = extras.getString("pythonPath");
// pythonServiceArgument = extras.getString("pythonServiceArgument");
// serviceTitle = extras.getString("serviceTitle");
// String serviceDescription = extras.getString("serviceDescription");
//
// pythonThread = new Thread(this);
// pythonThread.start();
//
// updateNotification(serviceDescription);
//
// return START_NOT_STICKY;
// }
//
// private void updateNotification(CharSequence text) {
// Context context = getApplicationContext();
// notification = new Notification(context.getApplicationInfo().icon,
// serviceTitle, System.currentTimeMillis());
// Intent contextIntent = new Intent(context, MainActivity.class);
// PendingIntent pIntent = PendingIntent.getActivity(context, 0,
// contextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// notification.setLatestEventInfo(context, serviceTitle, text, pIntent);
// startForeground(1, notification);
// }
//
// public static void updateNotificationText(CharSequence newText) {
// pyService.updateNotification(newText);
// }
//
// @Override
// public void onDestroy() {
// Log.d("python service", "Service destroyed");
// super.onDestroy();
// pythonThread = null;
// Process.killProcess(Process.myPid());
// }
//
// @Override
// public void run() {
//
// // libraries loading
// System.loadLibrary("sdl");
// System.loadLibrary("sdl_image");
// System.loadLibrary("sdl_ttf");
// System.loadLibrary("sdl_mixer");
// System.loadLibrary("python2.7");
// System.loadLibrary("application");
// System.loadLibrary("sdl_main");
//
// System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_io.so");
// System.load(getFilesDir() + "/lib/python2.7/lib-dynload/unicodedata.so");
//
// try {
// System.loadLibrary("sqlite3");
// System.load(getFilesDir()
// + "/lib/python2.7/lib-dynload/_sqlite3.so");
// } catch (UnsatisfiedLinkError e) {
// }
//
// nativeInitJavaEnv();
// nativeSetEnv("ANDROID_SDK", Integer.toString(Build.VERSION.SDK_INT));
// nativeSetEnv(
// "ANDROID_DOWNLOAD_DIRECTORY",
// Environment.getExternalStoragePublicDirectory(
// Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
// setSettings();
// nativeStart(androidPrivate, androidArgument, pythonHome, pythonPath,
// pythonServiceArgument);
// }
//
// private void setSettings() {
// Settings.setup(getApplicationContext());
// nativeSetEnv("TRIBLER_SETTING_FAMILY_FILTER",
// Boolean.toString(Settings.getFamilyFilterOn()));
// nativeSetEnv("TRIBLER_SETTING_MAX_DOWNLOAD", Integer.toString(Settings.getMaxDownloadRate()));
// nativeSetEnv("TRIBLER_SETTING_MAX_UPLOAD", Integer.toString(Settings.getMaxUploadRate()));
// }
//
// public static void stop() {
// pyService.stopSelf();
// }
//
// // Native part (don't remove!)
// public static native void nativeStart(String androidPrivate,
// String androidArgument, String pythonHome, String pythonPath,
// String pythonServiceArgument);
//
// public static native void nativeInitJavaEnv();
//
// public static native void nativeSetEnv(String name, String value);
//
// }
| import java.net.MalformedURLException;
import java.net.URL;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;
import org.renpy.android.PythonService;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.util.Log; | }
/**
* Show a new non-cancelable dialog
*/
private void showDialog() {
new AlertDialog.Builder(mContext)
.setMessage(
mContext.getString(R.string.on_quit_shutdown_message))
.setCancelable(false)
.setTitle(mContext.getString(R.string.on_quit_title)).show();
}
/**
* Shuts down the Tribler service and this app (when the XML-RPC call
* returns)
*/
@Override
public void update(Observable observable, Object data) {
shutdownService();
}
/**
* Shuts down the Tribler service and returns to the home screen
*/
private void shutdownService() {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(startMain); | // Path: tsap/src/org/renpy/android/PythonService.java
// public class PythonService extends Service implements Runnable {
//
// // Thread for Python code
// private Thread pythonThread = null;
//
// // Python environment variables
// private String androidPrivate;
// private String androidArgument;
// private String pythonHome;
// private String pythonPath;
//
// // Argument to pass to Python code,
// private String pythonServiceArgument;
//
// private Notification notification;
// private String serviceTitle;
// private static PythonService pyService;
//
// @Override
// public IBinder onBind(Intent arg0) {
// return null;
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// if (pythonThread != null) {
// Log.v("python service", "service exists, do not start again");
// return START_NOT_STICKY;
// }
//
// pyService = this;
// Bundle extras = intent.getExtras();
// androidPrivate = extras.getString("androidPrivate");
// // service code is located in current directory (not in /service
// // anymore!)
// androidArgument = extras.getString("androidArgument");
// pythonHome = extras.getString("pythonHome");
// pythonPath = extras.getString("pythonPath");
// pythonServiceArgument = extras.getString("pythonServiceArgument");
// serviceTitle = extras.getString("serviceTitle");
// String serviceDescription = extras.getString("serviceDescription");
//
// pythonThread = new Thread(this);
// pythonThread.start();
//
// updateNotification(serviceDescription);
//
// return START_NOT_STICKY;
// }
//
// private void updateNotification(CharSequence text) {
// Context context = getApplicationContext();
// notification = new Notification(context.getApplicationInfo().icon,
// serviceTitle, System.currentTimeMillis());
// Intent contextIntent = new Intent(context, MainActivity.class);
// PendingIntent pIntent = PendingIntent.getActivity(context, 0,
// contextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// notification.setLatestEventInfo(context, serviceTitle, text, pIntent);
// startForeground(1, notification);
// }
//
// public static void updateNotificationText(CharSequence newText) {
// pyService.updateNotification(newText);
// }
//
// @Override
// public void onDestroy() {
// Log.d("python service", "Service destroyed");
// super.onDestroy();
// pythonThread = null;
// Process.killProcess(Process.myPid());
// }
//
// @Override
// public void run() {
//
// // libraries loading
// System.loadLibrary("sdl");
// System.loadLibrary("sdl_image");
// System.loadLibrary("sdl_ttf");
// System.loadLibrary("sdl_mixer");
// System.loadLibrary("python2.7");
// System.loadLibrary("application");
// System.loadLibrary("sdl_main");
//
// System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_io.so");
// System.load(getFilesDir() + "/lib/python2.7/lib-dynload/unicodedata.so");
//
// try {
// System.loadLibrary("sqlite3");
// System.load(getFilesDir()
// + "/lib/python2.7/lib-dynload/_sqlite3.so");
// } catch (UnsatisfiedLinkError e) {
// }
//
// nativeInitJavaEnv();
// nativeSetEnv("ANDROID_SDK", Integer.toString(Build.VERSION.SDK_INT));
// nativeSetEnv(
// "ANDROID_DOWNLOAD_DIRECTORY",
// Environment.getExternalStoragePublicDirectory(
// Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
// setSettings();
// nativeStart(androidPrivate, androidArgument, pythonHome, pythonPath,
// pythonServiceArgument);
// }
//
// private void setSettings() {
// Settings.setup(getApplicationContext());
// nativeSetEnv("TRIBLER_SETTING_FAMILY_FILTER",
// Boolean.toString(Settings.getFamilyFilterOn()));
// nativeSetEnv("TRIBLER_SETTING_MAX_DOWNLOAD", Integer.toString(Settings.getMaxDownloadRate()));
// nativeSetEnv("TRIBLER_SETTING_MAX_UPLOAD", Integer.toString(Settings.getMaxUploadRate()));
// }
//
// public static void stop() {
// pyService.stopSelf();
// }
//
// // Native part (don't remove!)
// public static native void nativeStart(String androidPrivate,
// String androidArgument, String pythonHome, String pythonPath,
// String pythonServiceArgument);
//
// public static native void nativeInitJavaEnv();
//
// public static native void nativeSetEnv(String name, String value);
//
// }
// Path: tsap/src/org/tribler/tsap/OnQuitDialog.java
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;
import org.renpy.android.PythonService;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.util.Log;
}
/**
* Show a new non-cancelable dialog
*/
private void showDialog() {
new AlertDialog.Builder(mContext)
.setMessage(
mContext.getString(R.string.on_quit_shutdown_message))
.setCancelable(false)
.setTitle(mContext.getString(R.string.on_quit_title)).show();
}
/**
* Shuts down the Tribler service and this app (when the XML-RPC call
* returns)
*/
@Override
public void update(Observable observable, Object data) {
shutdownService();
}
/**
* Shuts down the Tribler service and returns to the home screen
*/
private void shutdownService() {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(startMain); | PythonService.stop(); |
wtud/tsap | tsap/src/org/tribler/tsap/streaming/VODDialogFragment.java | // Path: tsap/src/org/tribler/tsap/util/Poller.java
// public class Poller {
// protected IPollListener mListener;
// private Timer mTimer = null;
// private TimerTask mTask;
// private long mPollingInterval;
//
// /**
// * Sets up the poller to poll from a new thread. If you want to poll from
// * another thread (like the UI thread), use the other constructor.
// *
// * @param listener
// * The listener whose onPoll function will be called each
// * interval
// * @param interval
// * The interval between two onPoll calls
// */
// public Poller(IPollListener listener, long interval) {
// mListener = listener;
// mPollingInterval = interval;
// }
//
// /**
// * Pauses the polling.
// */
// public synchronized void stop() {
// if (mTimer != null) {
// mTimer.cancel();
// mTimer = null;
// }
// }
//
// /**
// * @return a timer task that runs the onPoll method of the listener when the
// * timer expires
// */
// protected TimerTask MakeTimerTask() {
// return new TimerTask() {
// public void run() {
// mListener.onPoll();
// }
// };
// }
//
// /**
// * Starts the polling. If the Poller is already polling, nothing changes.
// */
// public synchronized void start() {
// if (mTimer == null) {
// mTimer = new Timer();
// mTask = MakeTimerTask();
// mTimer.scheduleAtFixedRate(mTask, 0, mPollingInterval);
// }
// }
//
// /**
// * Interface to implement when you want a poller attached to your class
// *
// * @author Dirk Schut
// *
// */
// public interface IPollListener {
// public void onPoll();
// }
// }
| import org.tribler.tsap.R;
import org.tribler.tsap.util.Poller;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Button; | package org.tribler.tsap.streaming;
/**
* Class showing a dialog (when the 'Play video' button is pressed) that is used
* to inform the user about the status of a download and when it can be streamed
*
* @author Niels Spruit
*
*/
@SuppressLint("ValidFragment")
public class VODDialogFragment extends DialogFragment {
| // Path: tsap/src/org/tribler/tsap/util/Poller.java
// public class Poller {
// protected IPollListener mListener;
// private Timer mTimer = null;
// private TimerTask mTask;
// private long mPollingInterval;
//
// /**
// * Sets up the poller to poll from a new thread. If you want to poll from
// * another thread (like the UI thread), use the other constructor.
// *
// * @param listener
// * The listener whose onPoll function will be called each
// * interval
// * @param interval
// * The interval between two onPoll calls
// */
// public Poller(IPollListener listener, long interval) {
// mListener = listener;
// mPollingInterval = interval;
// }
//
// /**
// * Pauses the polling.
// */
// public synchronized void stop() {
// if (mTimer != null) {
// mTimer.cancel();
// mTimer = null;
// }
// }
//
// /**
// * @return a timer task that runs the onPoll method of the listener when the
// * timer expires
// */
// protected TimerTask MakeTimerTask() {
// return new TimerTask() {
// public void run() {
// mListener.onPoll();
// }
// };
// }
//
// /**
// * Starts the polling. If the Poller is already polling, nothing changes.
// */
// public synchronized void start() {
// if (mTimer == null) {
// mTimer = new Timer();
// mTask = MakeTimerTask();
// mTimer.scheduleAtFixedRate(mTask, 0, mPollingInterval);
// }
// }
//
// /**
// * Interface to implement when you want a poller attached to your class
// *
// * @author Dirk Schut
// *
// */
// public interface IPollListener {
// public void onPoll();
// }
// }
// Path: tsap/src/org/tribler/tsap/streaming/VODDialogFragment.java
import org.tribler.tsap.R;
import org.tribler.tsap.util.Poller;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Button;
package org.tribler.tsap.streaming;
/**
* Class showing a dialog (when the 'Play video' button is pressed) that is used
* to inform the user about the status of a download and when it can be streamed
*
* @author Niels Spruit
*
*/
@SuppressLint("ValidFragment")
public class VODDialogFragment extends DialogFragment {
| private Poller mPoller; |
wtud/tsap | tsap-tests/src/org/tribler/tsap/util/tests/UtilityTest.java | // Path: tsap/src/org/tribler/tsap/util/Utility.java
// public class Utility {
//
// /**
// * Converts a number of seconds to a sensible string that can be shown to
// * the user.
// *
// * @param seconds
// * Number of seconds
// * @return A user friendly string
// */
// public static String convertSecondsToString(double seconds) {
// if (seconds < 10) {
// return "a few seconds";
// } else if (seconds < 60) {
// return "about " + (Math.round(seconds / 10) * 10) + " seconds";
// } else if (seconds < 3600) {
// long value = Math.round(seconds / 60);
// return "about " + value + " minute" + ((value > 1) ? "s" : "");
// } else if (seconds < 24 * 3600) {
// long value = (Math.round(seconds / 3600));
// return "about " + value + " hour" + ((value > 1) ? "s" : "");
// } else {
// return "more than a day";
// }
// }
//
// /**
// * Converts an amount of bytes into a nicely formatted String. It adds the
// * correct prefix like KB or GB and limits the precision to one number
// * behind the point.
// *
// * @param size
// * The amount of bytes.
// * @return A string in the format NNN.NXB
// */
// public static String convertBytesToString(double size) {
// String prefixes[] = { " B", " kB", " MB", " GB", " TB", " PB" };
// int prefix = 0;
// String minus;
// if (size < 0) {
// size = -size;
// minus = "-";
// } else {
// minus = "";
// }
// while (size > 1000 && prefix < prefixes.length - 1) {
// size /= 1000;
// prefix++;
// }
// String intString = minus + String.valueOf((int) size);
// if (prefix == 0 || size == (int) size) {
// return intString + prefixes[prefix];
// } else {
// return intString + "."
// + String.valueOf(size - (int) size).charAt(2)
// + prefixes[prefix];
// }
// }
//
// /**
// * Does the same as convertBytesToString, but adds /s to indicate it's bytes
// * per second
// *
// * @param speed
// * the amount of bytes per second
// * @return A string in the format NNN.NXB/s
// */
// public static String convertBytesPerSecToString(double speed) {
// return convertBytesToString(speed) + "/s";
// }
//
// /**
// * Converts the Tribler state code of a download into a readable message.
// *
// * @param state
// * Tribler state code
// * @return The message corresponding to the code
// */
// public static String convertDownloadStateIntToMessage(int state) {
// switch (state) {
// case 1:
// return "Allocating disk space";
// case 2:
// return "Waiting for hash check";
// case 3:
// return "Downloading";
// case 4:
// return "Seeding";
// case 5:
// return "Stopped";
// case 6:
// return "Stopped because of an error";
// case 7:
// return "Acquiring metadata";
// default:
// return "Invalid state";
// }
// }
//
// /**
// * Returns the value belonging to key if it exists in the map, otherwise it
// * retursn defaultValue
// *
// * @param map
// * The map to search for the value
// * @param key
// * The key to look for
// * @param defaultValue
// * The value that is returned when the map doesn't contain the
// * key
// * @return
// */
// @SuppressWarnings("unchecked")
// public static <T> T getFromMap(Map<String, Object> map, String key,
// T defaultValue) {
// T returnValue = (T) map.get(key);
// if (returnValue == null) {
// return defaultValue;
// } else {
// return returnValue;
// }
// }
// }
| import java.util.Map;
import java.util.HashMap;
import org.tribler.tsap.util.Utility;
import android.test.AndroidTestCase; | package org.tribler.tsap.util.tests;
public class UtilityTest extends AndroidTestCase {
private Map<String, Object> testMap;
@Override
protected void setUp() {
testMap = new HashMap<String, Object>();
testMap.put("integertest", 33);
testMap.put("stringtest", "hello");
testMap.put("booltest", false);
testMap.put("doubletest", 33.2);
}
public void testBytesToStringConversion() {
assertEquals("bytes formatted incorrectly", "0 B", | // Path: tsap/src/org/tribler/tsap/util/Utility.java
// public class Utility {
//
// /**
// * Converts a number of seconds to a sensible string that can be shown to
// * the user.
// *
// * @param seconds
// * Number of seconds
// * @return A user friendly string
// */
// public static String convertSecondsToString(double seconds) {
// if (seconds < 10) {
// return "a few seconds";
// } else if (seconds < 60) {
// return "about " + (Math.round(seconds / 10) * 10) + " seconds";
// } else if (seconds < 3600) {
// long value = Math.round(seconds / 60);
// return "about " + value + " minute" + ((value > 1) ? "s" : "");
// } else if (seconds < 24 * 3600) {
// long value = (Math.round(seconds / 3600));
// return "about " + value + " hour" + ((value > 1) ? "s" : "");
// } else {
// return "more than a day";
// }
// }
//
// /**
// * Converts an amount of bytes into a nicely formatted String. It adds the
// * correct prefix like KB or GB and limits the precision to one number
// * behind the point.
// *
// * @param size
// * The amount of bytes.
// * @return A string in the format NNN.NXB
// */
// public static String convertBytesToString(double size) {
// String prefixes[] = { " B", " kB", " MB", " GB", " TB", " PB" };
// int prefix = 0;
// String minus;
// if (size < 0) {
// size = -size;
// minus = "-";
// } else {
// minus = "";
// }
// while (size > 1000 && prefix < prefixes.length - 1) {
// size /= 1000;
// prefix++;
// }
// String intString = minus + String.valueOf((int) size);
// if (prefix == 0 || size == (int) size) {
// return intString + prefixes[prefix];
// } else {
// return intString + "."
// + String.valueOf(size - (int) size).charAt(2)
// + prefixes[prefix];
// }
// }
//
// /**
// * Does the same as convertBytesToString, but adds /s to indicate it's bytes
// * per second
// *
// * @param speed
// * the amount of bytes per second
// * @return A string in the format NNN.NXB/s
// */
// public static String convertBytesPerSecToString(double speed) {
// return convertBytesToString(speed) + "/s";
// }
//
// /**
// * Converts the Tribler state code of a download into a readable message.
// *
// * @param state
// * Tribler state code
// * @return The message corresponding to the code
// */
// public static String convertDownloadStateIntToMessage(int state) {
// switch (state) {
// case 1:
// return "Allocating disk space";
// case 2:
// return "Waiting for hash check";
// case 3:
// return "Downloading";
// case 4:
// return "Seeding";
// case 5:
// return "Stopped";
// case 6:
// return "Stopped because of an error";
// case 7:
// return "Acquiring metadata";
// default:
// return "Invalid state";
// }
// }
//
// /**
// * Returns the value belonging to key if it exists in the map, otherwise it
// * retursn defaultValue
// *
// * @param map
// * The map to search for the value
// * @param key
// * The key to look for
// * @param defaultValue
// * The value that is returned when the map doesn't contain the
// * key
// * @return
// */
// @SuppressWarnings("unchecked")
// public static <T> T getFromMap(Map<String, Object> map, String key,
// T defaultValue) {
// T returnValue = (T) map.get(key);
// if (returnValue == null) {
// return defaultValue;
// } else {
// return returnValue;
// }
// }
// }
// Path: tsap-tests/src/org/tribler/tsap/util/tests/UtilityTest.java
import java.util.Map;
import java.util.HashMap;
import org.tribler.tsap.util.Utility;
import android.test.AndroidTestCase;
package org.tribler.tsap.util.tests;
public class UtilityTest extends AndroidTestCase {
private Map<String, Object> testMap;
@Override
protected void setUp() {
testMap = new HashMap<String, Object>();
testMap.put("integertest", 33);
testMap.put("stringtest", "hello");
testMap.put("booltest", false);
testMap.put("doubletest", 33.2);
}
public void testBytesToStringConversion() {
assertEquals("bytes formatted incorrectly", "0 B", | Utility.convertBytesToString(0)); |
wtud/tsap | tsap/src/org/tribler/tsap/util/ThumbnailUtils.java | // Path: tsap/src/org/tribler/tsap/settings/Settings.java
// public class Settings {
// public enum TorrentType {
// VIDEO, ALL
// };
//
// private static File mThumbFolder = null;
// private static Context mContext;
// @SuppressWarnings("unused")
// private static XMLRPCThumbFolderManager mFolderManager;
//
// /**
// * @return the file location of the thumbnail folder
// */
// public static File getThumbFolder() {
// return mThumbFolder;
// }
//
// /**
// * Set the thumbnail folder setting to thumbFolder
// *
// * @param thumbFolder
// */
// public static void XMLRPCSetThumbFolder(File thumbFolder) {
// mThumbFolder = thumbFolder;
// }
//
// /**
// * @return the value of the maximum download rate setting
// */
// public static int getMaxDownloadRate() {
// SharedPreferences sharedPref = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// return Integer.valueOf(sharedPref
// .getString("pref_maxDownloadRate", "0"));
// }
//
// /**
// * @return the value of the maximum upload rate setting
// */
// public static int getMaxUploadRate() {
// SharedPreferences sharedPref = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// return Integer.valueOf(sharedPref.getString("pref_maxUploadRate", "0"));
// }
//
// /**
// * @return a boolean indicating whether Tribler's family filter is enabled
// * or disabled
// */
// public static boolean getFamilyFilterOn() {
// SharedPreferences sharedPref = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// return sharedPref.getBoolean("pref_familyFilter", true);
// }
//
// public static TorrentType getFilteredTorrentTypes() {
// SharedPreferences sharedPref = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// String typeString = sharedPref.getString("pref_supportedTorrentTypes",
// "@string/pref_supported_types_default");
// if (typeString.equals("Video"))
// return TorrentType.VIDEO;
// if (typeString.equals("All"))
// return TorrentType.ALL;
// return TorrentType.ALL;
// }
//
// /**
// * Sets up this class (initializes context and connection)
// *
// * @param context
// * @param connection
// */
// public static void setup(Context context, XMLRPCConnection connection) {
// mFolderManager = new XMLRPCThumbFolderManager(connection);
// mContext = context;
// }
//
// /**
// * Sets up this class (initializes context)
// *
// * @param context
// */
// public static void setup(Context context) {
// mContext = context;
// }
// }
| import java.io.File;
import java.io.FilenameFilter;
import org.tribler.tsap.R;
import org.tribler.tsap.settings.Settings;
import android.content.Context;
import android.util.Log;
import android.widget.ImageView;
import com.squareup.picasso.Picasso; | package org.tribler.tsap.util;
/**
* Utility function for locating and loading thumbnails
*
* @author Niels Spruit
*
*/
public class ThumbnailUtils {
/**
* Loads the thumbnail of the file into mImageView
*
* @param file
* The location of the thumbnail
* @param mImageView
* The view to load the image into
* @param context
* The context of the view
*/
public static void loadThumbnail(File file, ImageView mImageView,
Context context) {
float dens = context.getResources().getDisplayMetrics().density;
int thumbWidth = (int) (100 * dens);
int thumbHeight = (int) (150 * dens);
Picasso.with(context).load(file).placeholder(R.drawable.default_thumb)
.resize(thumbWidth, thumbHeight).into(mImageView);
}
/**
* Loads the default thumbnail into imageView
*
* @param imageView
* The view to load the image into
* @param context
* The context of the view
*/
public static void loadDefaultThumbnail(ImageView imageView, Context context) {
loadThumbnail(null, imageView, context);
}
/**
* Returns the thumbnail location of the torrent specified by infoHash (if
* it exists)
*
* @param infoHash
* The infohash of the torrent
* @return the thumbnail location of the torrent specified by infoHash (if
* it exists)
*/
public static File getThumbnailLocation(final String infoHash) { | // Path: tsap/src/org/tribler/tsap/settings/Settings.java
// public class Settings {
// public enum TorrentType {
// VIDEO, ALL
// };
//
// private static File mThumbFolder = null;
// private static Context mContext;
// @SuppressWarnings("unused")
// private static XMLRPCThumbFolderManager mFolderManager;
//
// /**
// * @return the file location of the thumbnail folder
// */
// public static File getThumbFolder() {
// return mThumbFolder;
// }
//
// /**
// * Set the thumbnail folder setting to thumbFolder
// *
// * @param thumbFolder
// */
// public static void XMLRPCSetThumbFolder(File thumbFolder) {
// mThumbFolder = thumbFolder;
// }
//
// /**
// * @return the value of the maximum download rate setting
// */
// public static int getMaxDownloadRate() {
// SharedPreferences sharedPref = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// return Integer.valueOf(sharedPref
// .getString("pref_maxDownloadRate", "0"));
// }
//
// /**
// * @return the value of the maximum upload rate setting
// */
// public static int getMaxUploadRate() {
// SharedPreferences sharedPref = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// return Integer.valueOf(sharedPref.getString("pref_maxUploadRate", "0"));
// }
//
// /**
// * @return a boolean indicating whether Tribler's family filter is enabled
// * or disabled
// */
// public static boolean getFamilyFilterOn() {
// SharedPreferences sharedPref = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// return sharedPref.getBoolean("pref_familyFilter", true);
// }
//
// public static TorrentType getFilteredTorrentTypes() {
// SharedPreferences sharedPref = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// String typeString = sharedPref.getString("pref_supportedTorrentTypes",
// "@string/pref_supported_types_default");
// if (typeString.equals("Video"))
// return TorrentType.VIDEO;
// if (typeString.equals("All"))
// return TorrentType.ALL;
// return TorrentType.ALL;
// }
//
// /**
// * Sets up this class (initializes context and connection)
// *
// * @param context
// * @param connection
// */
// public static void setup(Context context, XMLRPCConnection connection) {
// mFolderManager = new XMLRPCThumbFolderManager(connection);
// mContext = context;
// }
//
// /**
// * Sets up this class (initializes context)
// *
// * @param context
// */
// public static void setup(Context context) {
// mContext = context;
// }
// }
// Path: tsap/src/org/tribler/tsap/util/ThumbnailUtils.java
import java.io.File;
import java.io.FilenameFilter;
import org.tribler.tsap.R;
import org.tribler.tsap.settings.Settings;
import android.content.Context;
import android.util.Log;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
package org.tribler.tsap.util;
/**
* Utility function for locating and loading thumbnails
*
* @author Niels Spruit
*
*/
public class ThumbnailUtils {
/**
* Loads the thumbnail of the file into mImageView
*
* @param file
* The location of the thumbnail
* @param mImageView
* The view to load the image into
* @param context
* The context of the view
*/
public static void loadThumbnail(File file, ImageView mImageView,
Context context) {
float dens = context.getResources().getDisplayMetrics().density;
int thumbWidth = (int) (100 * dens);
int thumbHeight = (int) (150 * dens);
Picasso.with(context).load(file).placeholder(R.drawable.default_thumb)
.resize(thumbWidth, thumbHeight).into(mImageView);
}
/**
* Loads the default thumbnail into imageView
*
* @param imageView
* The view to load the image into
* @param context
* The context of the view
*/
public static void loadDefaultThumbnail(ImageView imageView, Context context) {
loadThumbnail(null, imageView, context);
}
/**
* Returns the thumbnail location of the torrent specified by infoHash (if
* it exists)
*
* @param infoHash
* The infohash of the torrent
* @return the thumbnail location of the torrent specified by infoHash (if
* it exists)
*/
public static File getThumbnailLocation(final String infoHash) { | File baseDirectory = Settings.getThumbFolder(); |
wtud/tsap | tsap-tests/src/org/tribler/tsap/thumbgrid/tests/TorrentHealthTest.java | // Path: tsap/src/org/tribler/tsap/thumbgrid/TORRENT_HEALTH.java
// public enum TORRENT_HEALTH implements Serializable {
// UNKNOWN, RED, YELLOW, GREEN;
//
// /**
// * Returns the color value belonging to health value
// *
// * @param health
// * The health of torrent
// * @return The color belonging to the health
// */
// public static int toColor(TORRENT_HEALTH health) {
// switch (health) {
// case RED:
// return Color.RED;
// case YELLOW:
// return Color.YELLOW;
// case GREEN:
// return Color.GREEN;
// default:
// return Color.GRAY;
// }
// }
// }
| import org.tribler.tsap.thumbgrid.TORRENT_HEALTH;
import android.graphics.Color;
import android.test.AndroidTestCase; | package org.tribler.tsap.thumbgrid.tests;
/**
* Unit tests for the TORRENT_HEALTH class
*
* @author Wendo Sabée
*/
public class TorrentHealthTest extends AndroidTestCase {
public void testToColorUnknown() { | // Path: tsap/src/org/tribler/tsap/thumbgrid/TORRENT_HEALTH.java
// public enum TORRENT_HEALTH implements Serializable {
// UNKNOWN, RED, YELLOW, GREEN;
//
// /**
// * Returns the color value belonging to health value
// *
// * @param health
// * The health of torrent
// * @return The color belonging to the health
// */
// public static int toColor(TORRENT_HEALTH health) {
// switch (health) {
// case RED:
// return Color.RED;
// case YELLOW:
// return Color.YELLOW;
// case GREEN:
// return Color.GREEN;
// default:
// return Color.GRAY;
// }
// }
// }
// Path: tsap-tests/src/org/tribler/tsap/thumbgrid/tests/TorrentHealthTest.java
import org.tribler.tsap.thumbgrid.TORRENT_HEALTH;
import android.graphics.Color;
import android.test.AndroidTestCase;
package org.tribler.tsap.thumbgrid.tests;
/**
* Unit tests for the TORRENT_HEALTH class
*
* @author Wendo Sabée
*/
public class TorrentHealthTest extends AndroidTestCase {
public void testToColorUnknown() { | TORRENT_HEALTH health = TORRENT_HEALTH.UNKNOWN; |
wtud/tsap | tsap/src/org/tribler/tsap/downloads/Download.java | // Path: tsap/src/org/tribler/tsap/Torrent.java
// public class Torrent implements Serializable {
//
// private static final long serialVersionUID = 1619276011406943212L;
//
// private String name;
// private String infoHash;
// private long size;
// private int seeders;
// private int leechers;
// private File thumbnailFile = null;
// private String category;
//
// /**
// * Constructor: initializes the instance variables
// *
// * @param name
// * The name of the torrent
// * @param infoHash
// * The infohash of the torrent
// * @param size
// * The size of the torrent
// * @param seeders
// * The number of seeders of the torrent
// * @param leechers
// * The number of leechers of the torrent
// * @param category
// * The category of the torrent
// */
// public Torrent(String name, String infoHash, long size, int seeders,
// int leechers, String category) {
// this.name = name;
// this.infoHash = infoHash;
// this.size = size;
// this.seeders = seeders;
// this.leechers = leechers;
// this.category = category;
// }
//
// /**
// * @return the name
// */
// public String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public void setName(String name) {
// this.name = name;
// }
//
// /**
// * @return the infoHash
// */
// public String getInfoHash() {
// return infoHash;
// }
//
// /**
// * @param infoHash
// * the infoHash to set
// */
// public void setInfoHash(String infoHash) {
// this.infoHash = infoHash;
// }
//
// /**
// * @return the size
// */
// public long getSize() {
// return size;
// }
//
// /**
// * @param size
// * the size to set
// */
// public void setSize(long size) {
// this.size = size;
// }
//
// /**
// * @return the seeders
// */
// public int getSeeders() {
// return seeders;
// }
//
// /**
// * @param seeders
// * the seeders to set
// */
// public void setSeeders(int seeders) {
// this.seeders = seeders;
// }
//
// /**
// * @return the leechers
// */
// public int getLeechers() {
// return leechers;
// }
//
// /**
// * @param leechers
// * the leechers to set
// */
// public void setLeechers(int leechers) {
// this.leechers = leechers;
// }
//
// /**
// * @return the thumbnailFile
// */
// public File getThumbnailFile() {
// return thumbnailFile;
// }
//
// /**
// * @param thumbnailFile
// * the thumbnailFile to set
// */
// public void setThumbnailFile(File thumbnailFile) {
// this.thumbnailFile = thumbnailFile;
// }
//
// /**
// * @return the category
// */
// public String getCategory() {
// return category;
// }
//
// /**
// * @param category
// * the category to set
// */
// public void setCategory(String category) {
// this.category = category;
// }
//
// /**
// * @return the health of the torrent
// */
// public TORRENT_HEALTH getHealth() {
// if (seeders == -1 || leechers == -1) {
// return TORRENT_HEALTH.UNKNOWN;
// }
//
// if (seeders == 0) {
// return TORRENT_HEALTH.RED;
// }
//
// return ((leechers / seeders) > 0.5) ? TORRENT_HEALTH.YELLOW
// : TORRENT_HEALTH.GREEN;
// }
//
// /**
// * @return the string representation of a torrent (=name)
// */
// @Override
// public String toString() {
// return name;
// }
//
// /**
// * The default equals function, only checks on infohash
// * @param obj The object to be compared with
// * @return True if equal infohashes, otherwise false.
// */
// public boolean equals(Object obj)
// {
// // Pre-check if we are the same
// if (this == obj)
// return true;
//
// // Only check infohash if it's actually a ThumbItem
// if (!(obj instanceof Torrent))
// return false;
//
// // Compare infohashes
// return ((Torrent) obj).getInfoHash().equals(this.getInfoHash());
// }
//
// }
| import java.io.Serializable;
import org.tribler.tsap.Torrent; | package org.tribler.tsap.downloads;
/**
* Class for storing data on a download that is finished or currently running.
*
* @author Dirk Schut & Niels Spruit
*
*/
public class Download implements Serializable {
private static final long serialVersionUID = 5511967201437733003L;
| // Path: tsap/src/org/tribler/tsap/Torrent.java
// public class Torrent implements Serializable {
//
// private static final long serialVersionUID = 1619276011406943212L;
//
// private String name;
// private String infoHash;
// private long size;
// private int seeders;
// private int leechers;
// private File thumbnailFile = null;
// private String category;
//
// /**
// * Constructor: initializes the instance variables
// *
// * @param name
// * The name of the torrent
// * @param infoHash
// * The infohash of the torrent
// * @param size
// * The size of the torrent
// * @param seeders
// * The number of seeders of the torrent
// * @param leechers
// * The number of leechers of the torrent
// * @param category
// * The category of the torrent
// */
// public Torrent(String name, String infoHash, long size, int seeders,
// int leechers, String category) {
// this.name = name;
// this.infoHash = infoHash;
// this.size = size;
// this.seeders = seeders;
// this.leechers = leechers;
// this.category = category;
// }
//
// /**
// * @return the name
// */
// public String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public void setName(String name) {
// this.name = name;
// }
//
// /**
// * @return the infoHash
// */
// public String getInfoHash() {
// return infoHash;
// }
//
// /**
// * @param infoHash
// * the infoHash to set
// */
// public void setInfoHash(String infoHash) {
// this.infoHash = infoHash;
// }
//
// /**
// * @return the size
// */
// public long getSize() {
// return size;
// }
//
// /**
// * @param size
// * the size to set
// */
// public void setSize(long size) {
// this.size = size;
// }
//
// /**
// * @return the seeders
// */
// public int getSeeders() {
// return seeders;
// }
//
// /**
// * @param seeders
// * the seeders to set
// */
// public void setSeeders(int seeders) {
// this.seeders = seeders;
// }
//
// /**
// * @return the leechers
// */
// public int getLeechers() {
// return leechers;
// }
//
// /**
// * @param leechers
// * the leechers to set
// */
// public void setLeechers(int leechers) {
// this.leechers = leechers;
// }
//
// /**
// * @return the thumbnailFile
// */
// public File getThumbnailFile() {
// return thumbnailFile;
// }
//
// /**
// * @param thumbnailFile
// * the thumbnailFile to set
// */
// public void setThumbnailFile(File thumbnailFile) {
// this.thumbnailFile = thumbnailFile;
// }
//
// /**
// * @return the category
// */
// public String getCategory() {
// return category;
// }
//
// /**
// * @param category
// * the category to set
// */
// public void setCategory(String category) {
// this.category = category;
// }
//
// /**
// * @return the health of the torrent
// */
// public TORRENT_HEALTH getHealth() {
// if (seeders == -1 || leechers == -1) {
// return TORRENT_HEALTH.UNKNOWN;
// }
//
// if (seeders == 0) {
// return TORRENT_HEALTH.RED;
// }
//
// return ((leechers / seeders) > 0.5) ? TORRENT_HEALTH.YELLOW
// : TORRENT_HEALTH.GREEN;
// }
//
// /**
// * @return the string representation of a torrent (=name)
// */
// @Override
// public String toString() {
// return name;
// }
//
// /**
// * The default equals function, only checks on infohash
// * @param obj The object to be compared with
// * @return True if equal infohashes, otherwise false.
// */
// public boolean equals(Object obj)
// {
// // Pre-check if we are the same
// if (this == obj)
// return true;
//
// // Only check infohash if it's actually a ThumbItem
// if (!(obj instanceof Torrent))
// return false;
//
// // Compare infohashes
// return ((Torrent) obj).getInfoHash().equals(this.getInfoHash());
// }
//
// }
// Path: tsap/src/org/tribler/tsap/downloads/Download.java
import java.io.Serializable;
import org.tribler.tsap.Torrent;
package org.tribler.tsap.downloads;
/**
* Class for storing data on a download that is finished or currently running.
*
* @author Dirk Schut & Niels Spruit
*
*/
public class Download implements Serializable {
private static final long serialVersionUID = 5511967201437733003L;
| private Torrent torrent; |
wtud/tsap | tsap/src/org/tribler/tsap/Torrent.java | // Path: tsap/src/org/tribler/tsap/thumbgrid/TORRENT_HEALTH.java
// public enum TORRENT_HEALTH implements Serializable {
// UNKNOWN, RED, YELLOW, GREEN;
//
// /**
// * Returns the color value belonging to health value
// *
// * @param health
// * The health of torrent
// * @return The color belonging to the health
// */
// public static int toColor(TORRENT_HEALTH health) {
// switch (health) {
// case RED:
// return Color.RED;
// case YELLOW:
// return Color.YELLOW;
// case GREEN:
// return Color.GREEN;
// default:
// return Color.GRAY;
// }
// }
// }
| import java.io.File;
import java.io.Serializable;
import org.tribler.tsap.thumbgrid.TORRENT_HEALTH; | public File getThumbnailFile() {
return thumbnailFile;
}
/**
* @param thumbnailFile
* the thumbnailFile to set
*/
public void setThumbnailFile(File thumbnailFile) {
this.thumbnailFile = thumbnailFile;
}
/**
* @return the category
*/
public String getCategory() {
return category;
}
/**
* @param category
* the category to set
*/
public void setCategory(String category) {
this.category = category;
}
/**
* @return the health of the torrent
*/ | // Path: tsap/src/org/tribler/tsap/thumbgrid/TORRENT_HEALTH.java
// public enum TORRENT_HEALTH implements Serializable {
// UNKNOWN, RED, YELLOW, GREEN;
//
// /**
// * Returns the color value belonging to health value
// *
// * @param health
// * The health of torrent
// * @return The color belonging to the health
// */
// public static int toColor(TORRENT_HEALTH health) {
// switch (health) {
// case RED:
// return Color.RED;
// case YELLOW:
// return Color.YELLOW;
// case GREEN:
// return Color.GREEN;
// default:
// return Color.GRAY;
// }
// }
// }
// Path: tsap/src/org/tribler/tsap/Torrent.java
import java.io.File;
import java.io.Serializable;
import org.tribler.tsap.thumbgrid.TORRENT_HEALTH;
public File getThumbnailFile() {
return thumbnailFile;
}
/**
* @param thumbnailFile
* the thumbnailFile to set
*/
public void setThumbnailFile(File thumbnailFile) {
this.thumbnailFile = thumbnailFile;
}
/**
* @return the category
*/
public String getCategory() {
return category;
}
/**
* @param category
* the category to set
*/
public void setCategory(String category) {
this.category = category;
}
/**
* @return the health of the torrent
*/ | public TORRENT_HEALTH getHealth() { |
MagicMicky/HabitRPGJavaAPI | HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/habits/ToDo.java | // Path: HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/habits/Checklist.java
// public static class ChecklistItem {
// private String text;
// private String id;
// private boolean completed;
// public ChecklistItem() {
// this(null,null);
// }
// public ChecklistItem(String id, String text) {
// this(text,id,false);
// }
// public ChecklistItem(String id,String text, boolean completed) {
// this.setText(text);
// this.setId(id);
// this.setCompleted(completed);
// }
// public String getText() {
// return text;
// }
// public void setText(String text) {
// this.text = text;
// }
// public String getId() {
// return id;
// }
// public void setId(String id) {
// this.id = id;
// }
// public boolean isCompleted() {
// return completed;
// }
// public void setCompleted(boolean completed) {
// this.completed = completed;
// }
// }
| import java.util.List;
import org.json.JSONObject;
import com.magicmicky.habitrpglibrary.habits.Checklist.ChecklistItem; | * @return the checklist
*/
public Checklist getChecklist() {
return this.checklist;
}
/**
* Sets the checklist
* @param checklist the new checklist
*/
public void setChecklist(Checklist checklist) {
this.checklist = checklist;
}
@Override
protected String getType() {
return type.toString();
}
@Override
public String getJSONString() {
StringBuilder json = new StringBuilder()
.append("{")
.append(super.getJSONBaseString());
if(this.getDate()!=null && this.getDate()!="")
json.append("\"date\":\"").append(this.getDate()).append("\",");
json.append("\"completed\":").append((this.isCompleted() ? "true":"false"));
json.append(",")
.append("\"checklist\":[");
if(this.getChecklist() != null && !this.getChecklist().getItems().isEmpty()) { | // Path: HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/habits/Checklist.java
// public static class ChecklistItem {
// private String text;
// private String id;
// private boolean completed;
// public ChecklistItem() {
// this(null,null);
// }
// public ChecklistItem(String id, String text) {
// this(text,id,false);
// }
// public ChecklistItem(String id,String text, boolean completed) {
// this.setText(text);
// this.setId(id);
// this.setCompleted(completed);
// }
// public String getText() {
// return text;
// }
// public void setText(String text) {
// this.text = text;
// }
// public String getId() {
// return id;
// }
// public void setId(String id) {
// this.id = id;
// }
// public boolean isCompleted() {
// return completed;
// }
// public void setCompleted(boolean completed) {
// this.completed = completed;
// }
// }
// Path: HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/habits/ToDo.java
import java.util.List;
import org.json.JSONObject;
import com.magicmicky.habitrpglibrary.habits.Checklist.ChecklistItem;
* @return the checklist
*/
public Checklist getChecklist() {
return this.checklist;
}
/**
* Sets the checklist
* @param checklist the new checklist
*/
public void setChecklist(Checklist checklist) {
this.checklist = checklist;
}
@Override
protected String getType() {
return type.toString();
}
@Override
public String getJSONString() {
StringBuilder json = new StringBuilder()
.append("{")
.append(super.getJSONBaseString());
if(this.getDate()!=null && this.getDate()!="")
json.append("\"date\":\"").append(this.getDate()).append("\",");
json.append("\"completed\":").append((this.isCompleted() ? "true":"false"));
json.append(",")
.append("\"checklist\":[");
if(this.getChecklist() != null && !this.getChecklist().getItems().isEmpty()) { | for(ChecklistItem item : this.getChecklist().getItems()) { |
MagicMicky/HabitRPGJavaAPI | HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/habits/Daily.java | // Path: HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/habits/Checklist.java
// public static class ChecklistItem {
// private String text;
// private String id;
// private boolean completed;
// public ChecklistItem() {
// this(null,null);
// }
// public ChecklistItem(String id, String text) {
// this(text,id,false);
// }
// public ChecklistItem(String id,String text, boolean completed) {
// this.setText(text);
// this.setId(id);
// this.setCompleted(completed);
// }
// public String getText() {
// return text;
// }
// public void setText(String text) {
// this.text = text;
// }
// public String getId() {
// return id;
// }
// public void setId(String id) {
// this.id = id;
// }
// public boolean isCompleted() {
// return completed;
// }
// public void setCompleted(boolean completed) {
// this.completed = completed;
// }
// }
| import java.text.SimpleDateFormat;
import org.json.JSONObject;
import com.magicmicky.habitrpglibrary.habits.Checklist.ChecklistItem; | * Sets the checklist
* @param checklist the new checklist
*/
public void setChecklist(Checklist checklist) {
this.checklist = checklist;
}
@Override
protected String getType() {
return type.toString();
}
@Override
public String getJSONString() {
StringBuilder json = new StringBuilder()
.append("{")
.append(super.getJSONBaseString());
if(this.getRepeat() != null) {
json.append("\"repeat\":{");
for(int i=0;i<7;i++) {
json.append("\"").append(Daily.days[i]).append("\": ").append(this.getRepeat()[i]).append(",");
}
json =json.deleteCharAt(json.length()-1);
json.append("},");
}
json.append("\"streak\":").append(this.getStreak()).append(",");
json.append("\"completed\":" + (this.isCompleted() ? "true":"false"));
json.append(",")
.append("\"checklist\":[");
if(this.getChecklist() != null && !this.getChecklist().getItems().isEmpty()) { | // Path: HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/habits/Checklist.java
// public static class ChecklistItem {
// private String text;
// private String id;
// private boolean completed;
// public ChecklistItem() {
// this(null,null);
// }
// public ChecklistItem(String id, String text) {
// this(text,id,false);
// }
// public ChecklistItem(String id,String text, boolean completed) {
// this.setText(text);
// this.setId(id);
// this.setCompleted(completed);
// }
// public String getText() {
// return text;
// }
// public void setText(String text) {
// this.text = text;
// }
// public String getId() {
// return id;
// }
// public void setId(String id) {
// this.id = id;
// }
// public boolean isCompleted() {
// return completed;
// }
// public void setCompleted(boolean completed) {
// this.completed = completed;
// }
// }
// Path: HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/habits/Daily.java
import java.text.SimpleDateFormat;
import org.json.JSONObject;
import com.magicmicky.habitrpglibrary.habits.Checklist.ChecklistItem;
* Sets the checklist
* @param checklist the new checklist
*/
public void setChecklist(Checklist checklist) {
this.checklist = checklist;
}
@Override
protected String getType() {
return type.toString();
}
@Override
public String getJSONString() {
StringBuilder json = new StringBuilder()
.append("{")
.append(super.getJSONBaseString());
if(this.getRepeat() != null) {
json.append("\"repeat\":{");
for(int i=0;i<7;i++) {
json.append("\"").append(Daily.days[i]).append("\": ").append(this.getRepeat()[i]).append(",");
}
json =json.deleteCharAt(json.length()-1);
json.append("},");
}
json.append("\"streak\":").append(this.getStreak()).append(",");
json.append("\"completed\":" + (this.isCompleted() ? "true":"false"));
json.append(",")
.append("\"checklist\":[");
if(this.getChecklist() != null && !this.getChecklist().getItems().isEmpty()) { | for(ChecklistItem item : this.getChecklist().getItems()) { |
MagicMicky/HabitRPGJavaAPI | HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/onlineapi/WebServiceInteraction.java | // Path: HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/onlineapi/helper/HabitRPGException.java
// public class HabitRPGException extends Exception {
// /**
// * Happens when the server api call wasn't found.
// */
// public final static int HABITRPG_SERVER_API_CALL_NOT_FOUND=-1;
//
// /**
// * Happens when the server is experiencing issues
// */
// public final static int SERV_EXPERIENCING_ISSUES = 2;
// /**
// * Happens when something couldn't be parsed
// * /
// public final static int PARSING_ERROR = 3;
// /**
// * Happens when the user seems to have no connection
// */
// public final static int INTERNAL_NO_CONNECTION=4;
//
// /**
// * Could happend when a user cut the connection while requesting some info.
// */
// public final static int INTERNAL_OTHER = 5;
// public static final int INTERNAL_WRONG_URL = 6;
// public static final int HABITRPG_REGISTRATION_ERROR = 7;
//
//
// private int currentError;
//
// public HabitRPGException(int id) {
// this(id,errorToString(id));
// this.currentError=id;
// }
// public HabitRPGException(int error, String details) {
// super(details);
// this.currentError=error;
// }
// public int getErrorNumber() {
// return currentError;
// }
// private static String errorToString(int id) {
// String errorMessage="";
// switch(id) {
// case HABITRPG_SERVER_API_CALL_NOT_FOUND:
// case INTERNAL_WRONG_URL:
// errorMessage="The server wasn't found. Please check your hosts settings.";
// break;
// case SERV_EXPERIENCING_ISSUES:
// errorMessage="HabitRPG's server is having some trouble. Feel free to switch to the beta server";
// break;
// case INTERNAL_NO_CONNECTION:
// errorMessage="Error. Please check your connection";
// break;
// case INTERNAL_OTHER:
// errorMessage="An internal unknown error happend!";
// break;
// case HABITRPG_REGISTRATION_ERROR:
// errorMessage="There has been an error during the registration process! Please try again.";
// default:
// errorMessage="An unknown error happened!";
// break;
//
// }
// return errorMessage;
// }
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import com.magicmicky.habitrpglibrary.onlineapi.helper.HabitRPGException; | }
/**
* Get the data from the WebService
* @return the {@link Answer}
*/
public final Answer getData() {
Answer result=null;
HttpClient client;
HttpRequestBase request = null;
// Making HTTP request
try {
String address = config.getAddress();
address = address.concat(address.charAt(address.length()-1) == '/' ? SUFFIX + this.CMD : '/' + SUFFIX + this.CMD);
client = new DefaultHttpClient();
request = this.getRequest();
request.setURI(new URI(address));
request.addHeader("x-api-key", config.getApi());
request.addHeader("x-api-user", config.getUser());
request.addHeader("Accept-Encoding", "gzip");
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode() == 204) {//Tasks deleted
String jsonstr = "{\"task_deleted\":true}";
JSONObject jsonObj = new JSONObject(jsonstr);
result = findAnswer(jsonObj);
}
else {
if(response.getStatusLine().getStatusCode() == 404) { | // Path: HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/onlineapi/helper/HabitRPGException.java
// public class HabitRPGException extends Exception {
// /**
// * Happens when the server api call wasn't found.
// */
// public final static int HABITRPG_SERVER_API_CALL_NOT_FOUND=-1;
//
// /**
// * Happens when the server is experiencing issues
// */
// public final static int SERV_EXPERIENCING_ISSUES = 2;
// /**
// * Happens when something couldn't be parsed
// * /
// public final static int PARSING_ERROR = 3;
// /**
// * Happens when the user seems to have no connection
// */
// public final static int INTERNAL_NO_CONNECTION=4;
//
// /**
// * Could happend when a user cut the connection while requesting some info.
// */
// public final static int INTERNAL_OTHER = 5;
// public static final int INTERNAL_WRONG_URL = 6;
// public static final int HABITRPG_REGISTRATION_ERROR = 7;
//
//
// private int currentError;
//
// public HabitRPGException(int id) {
// this(id,errorToString(id));
// this.currentError=id;
// }
// public HabitRPGException(int error, String details) {
// super(details);
// this.currentError=error;
// }
// public int getErrorNumber() {
// return currentError;
// }
// private static String errorToString(int id) {
// String errorMessage="";
// switch(id) {
// case HABITRPG_SERVER_API_CALL_NOT_FOUND:
// case INTERNAL_WRONG_URL:
// errorMessage="The server wasn't found. Please check your hosts settings.";
// break;
// case SERV_EXPERIENCING_ISSUES:
// errorMessage="HabitRPG's server is having some trouble. Feel free to switch to the beta server";
// break;
// case INTERNAL_NO_CONNECTION:
// errorMessage="Error. Please check your connection";
// break;
// case INTERNAL_OTHER:
// errorMessage="An internal unknown error happend!";
// break;
// case HABITRPG_REGISTRATION_ERROR:
// errorMessage="There has been an error during the registration process! Please try again.";
// default:
// errorMessage="An unknown error happened!";
// break;
//
// }
// return errorMessage;
// }
// }
// Path: HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/onlineapi/WebServiceInteraction.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import com.magicmicky.habitrpglibrary.onlineapi.helper.HabitRPGException;
}
/**
* Get the data from the WebService
* @return the {@link Answer}
*/
public final Answer getData() {
Answer result=null;
HttpClient client;
HttpRequestBase request = null;
// Making HTTP request
try {
String address = config.getAddress();
address = address.concat(address.charAt(address.length()-1) == '/' ? SUFFIX + this.CMD : '/' + SUFFIX + this.CMD);
client = new DefaultHttpClient();
request = this.getRequest();
request.setURI(new URI(address));
request.addHeader("x-api-key", config.getApi());
request.addHeader("x-api-user", config.getUser());
request.addHeader("Accept-Encoding", "gzip");
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode() == 204) {//Tasks deleted
String jsonstr = "{\"task_deleted\":true}";
JSONObject jsonObj = new JSONObject(jsonstr);
result = findAnswer(jsonObj);
}
else {
if(response.getStatusLine().getStatusCode() == 404) { | throw new HabitRPGException(HabitRPGException.HABITRPG_SERVER_API_CALL_NOT_FOUND); |
MagicMicky/HabitRPGJavaAPI | HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/onlineapi/helper/ParserHelper.java | // Path: HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/habits/Checklist.java
// public static class ChecklistItem {
// private String text;
// private String id;
// private boolean completed;
// public ChecklistItem() {
// this(null,null);
// }
// public ChecklistItem(String id, String text) {
// this(text,id,false);
// }
// public ChecklistItem(String id,String text, boolean completed) {
// this.setText(text);
// this.setId(id);
// this.setCompleted(completed);
// }
// public String getText() {
// return text;
// }
// public void setText(String text) {
// this.text = text;
// }
// public String getId() {
// return id;
// }
// public void setId(String id) {
// this.id = id;
// }
// public boolean isCompleted() {
// return completed;
// }
// public void setCompleted(boolean completed) {
// this.completed = completed;
// }
// }
| import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.magicmicky.habitrpglibrary.habits.*;
import com.magicmicky.habitrpglibrary.habits.Checklist.ChecklistItem; | }
}
return it;
} catch (JSONException e) {
e.printStackTrace();
ParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_TODO_UNPARSABLE);
throw(ex);
}
}
private static Reward parseReward(JSONObject obj) throws ParseErrorException {
try {
Reward it = new Reward();
parseBase(it, obj);
return it;
} catch (JSONException e) {
e.printStackTrace();
ParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_REWARD_UNPARSABLE);
throw(ex);
}
}
private static Checklist parseChecklist(JSONArray obj) throws ParseErrorException {
Checklist cl = new Checklist();
try {
for(int i=0;i<obj.length();i++) {
JSONObject current_item = obj.getJSONObject(i);
String id = current_item.getString(TAG_CHECKLIST_ID);
String text = current_item.getString(TAG_CHECKLIST_TEXT);
boolean cmplt = current_item.getBoolean(TAG_CHECKLIST_COMPLETED); | // Path: HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/habits/Checklist.java
// public static class ChecklistItem {
// private String text;
// private String id;
// private boolean completed;
// public ChecklistItem() {
// this(null,null);
// }
// public ChecklistItem(String id, String text) {
// this(text,id,false);
// }
// public ChecklistItem(String id,String text, boolean completed) {
// this.setText(text);
// this.setId(id);
// this.setCompleted(completed);
// }
// public String getText() {
// return text;
// }
// public void setText(String text) {
// this.text = text;
// }
// public String getId() {
// return id;
// }
// public void setId(String id) {
// this.id = id;
// }
// public boolean isCompleted() {
// return completed;
// }
// public void setCompleted(boolean completed) {
// this.completed = completed;
// }
// }
// Path: HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/onlineapi/helper/ParserHelper.java
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.magicmicky.habitrpglibrary.habits.*;
import com.magicmicky.habitrpglibrary.habits.Checklist.ChecklistItem;
}
}
return it;
} catch (JSONException e) {
e.printStackTrace();
ParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_TODO_UNPARSABLE);
throw(ex);
}
}
private static Reward parseReward(JSONObject obj) throws ParseErrorException {
try {
Reward it = new Reward();
parseBase(it, obj);
return it;
} catch (JSONException e) {
e.printStackTrace();
ParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_REWARD_UNPARSABLE);
throw(ex);
}
}
private static Checklist parseChecklist(JSONArray obj) throws ParseErrorException {
Checklist cl = new Checklist();
try {
for(int i=0;i<obj.length();i++) {
JSONObject current_item = obj.getJSONObject(i);
String id = current_item.getString(TAG_CHECKLIST_ID);
String text = current_item.getString(TAG_CHECKLIST_TEXT);
boolean cmplt = current_item.getBoolean(TAG_CHECKLIST_COMPLETED); | ChecklistItem it = new ChecklistItem(id, text,cmplt); |
lawloretienne/QuickReturn | sample/src/main/java/com/etiennelawlor/quickreturn/utils/TypefaceUtil.java | // Path: sample/src/main/java/com/etiennelawlor/quickreturn/QuickReturnApplication.java
// public class QuickReturnApplication extends Application {
//
// // region Static Variables
// private static QuickReturnApplication sCurrentApplication = null;
// // endregion
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// sCurrentApplication = this;
// }
//
// // region Getters
// public static QuickReturnApplication getInstance() {
// return sCurrentApplication;
// }
// // endregion
// }
| import android.graphics.Typeface;
import android.widget.TextView;
import com.etiennelawlor.quickreturn.QuickReturnApplication;
import com.google.common.collect.Maps;
import java.util.HashMap; | package com.etiennelawlor.quickreturn.utils;
/**
* Created by etiennelawlor on 1/20/15.
*/
public class TypefaceUtil {
// region Static Variables
private static HashMap<TypefaceId, Typeface> sTypefaceCache = Maps.newHashMap();
// endregion
public static void apply(TypefaceId id, TextView tv) {
if (tv == null || tv.isInEditMode()) {
return;
}
tv.setTypeface(getTypeface(id));
}
public static Typeface getTypeface(TypefaceId id) {
Typeface typeface = sTypefaceCache.get(id);
if (typeface == null) { | // Path: sample/src/main/java/com/etiennelawlor/quickreturn/QuickReturnApplication.java
// public class QuickReturnApplication extends Application {
//
// // region Static Variables
// private static QuickReturnApplication sCurrentApplication = null;
// // endregion
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// sCurrentApplication = this;
// }
//
// // region Getters
// public static QuickReturnApplication getInstance() {
// return sCurrentApplication;
// }
// // endregion
// }
// Path: sample/src/main/java/com/etiennelawlor/quickreturn/utils/TypefaceUtil.java
import android.graphics.Typeface;
import android.widget.TextView;
import com.etiennelawlor.quickreturn.QuickReturnApplication;
import com.google.common.collect.Maps;
import java.util.HashMap;
package com.etiennelawlor.quickreturn.utils;
/**
* Created by etiennelawlor on 1/20/15.
*/
public class TypefaceUtil {
// region Static Variables
private static HashMap<TypefaceId, Typeface> sTypefaceCache = Maps.newHashMap();
// endregion
public static void apply(TypefaceId id, TextView tv) {
if (tv == null || tv.isInEditMode()) {
return;
}
tv.setTypeface(getTypeface(id));
}
public static Typeface getTypeface(TypefaceId id) {
Typeface typeface = sTypefaceCache.get(id);
if (typeface == null) { | typeface = Typeface.createFromAsset(QuickReturnApplication.getInstance().getAssets(), id.getFilePath()); |
lawloretienne/QuickReturn | sample/src/main/java/com/etiennelawlor/quickreturn/fragments/QuickReturnFragment.java | // Path: library/src/main/java/com/etiennelawlor/quickreturn/library/listeners/QuickReturnScrollViewOnScrollChangedListener.java
// public class QuickReturnScrollViewOnScrollChangedListener implements NotifyingScrollView.OnScrollChangedListener {
//
// // region Member Variables
// private final QuickReturnViewType mQuickReturnViewType;
// private final View mHeader;
// private final int mMinHeaderTranslation;
// private final View mFooter;
// private final int mMinFooterTranslation;
//
// private int mHeaderDiffTotal = 0;
// private int mFooterDiffTotal = 0;
// // endregion
//
// // region Constructors
// private QuickReturnScrollViewOnScrollChangedListener(Builder builder) {
// mQuickReturnViewType = builder.mQuickReturnViewType;
// mHeader = builder.mHeader;
// mMinHeaderTranslation = builder.mMinHeaderTranslation;
// mFooter = builder.mFooter;
// mMinFooterTranslation = builder.mMinFooterTranslation;
// }
// // endregion
//
// @Override
// public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
// int diff = oldt - t;
//
// switch (mQuickReturnViewType) {
// case HEADER:
// if (diff <= 0) { // scrolling down
// mHeaderDiffTotal = Math.max(mHeaderDiffTotal + diff, mMinHeaderTranslation);
// } else { // scrolling up
// mHeaderDiffTotal = Math.min(Math.max(mHeaderDiffTotal + diff, mMinHeaderTranslation), 0);
// }
//
// mHeader.setTranslationY(mHeaderDiffTotal);
// break;
// case FOOTER:
// if (diff <= 0) { // scrolling down
// mFooterDiffTotal = Math.max(mFooterDiffTotal + diff, -mMinFooterTranslation);
// } else { // scrolling up
// mFooterDiffTotal = Math.min(Math.max(mFooterDiffTotal + diff, -mMinFooterTranslation), 0);
// }
//
// mFooter.setTranslationY(-mFooterDiffTotal);
// break;
// case BOTH:
// if (diff <= 0) { // scrolling down
// mHeaderDiffTotal = Math.max(mHeaderDiffTotal + diff, mMinHeaderTranslation);
// mFooterDiffTotal = Math.max(mFooterDiffTotal + diff, -mMinFooterTranslation);
// } else { // scrolling up
// mHeaderDiffTotal = Math.min(Math.max(mHeaderDiffTotal + diff, mMinHeaderTranslation), 0);
// mFooterDiffTotal = Math.min(Math.max(mFooterDiffTotal + diff, -mMinFooterTranslation), 0);
// }
//
// mHeader.setTranslationY(mHeaderDiffTotal);
// mFooter.setTranslationY(-mFooterDiffTotal);
// break;
// }
// }
//
// // region Inner Classes
//
// public static class Builder {
// // Required parameters
// private final QuickReturnViewType mQuickReturnViewType;
//
// // Optional parameters - initialized to default values
// private View mHeader = null;
// private int mMinHeaderTranslation = 0;
// private View mFooter = null;
// private int mMinFooterTranslation = 0;
//
// public Builder(QuickReturnViewType quickReturnViewType) {
// mQuickReturnViewType = quickReturnViewType;
// }
//
// public Builder header(View header) {
// mHeader = header;
// return this;
// }
//
// public Builder minHeaderTranslation(int minHeaderTranslation) {
// mMinHeaderTranslation = minHeaderTranslation;
// return this;
// }
//
// public Builder footer(View footer) {
// mFooter = footer;
// return this;
// }
//
// public Builder minFooterTranslation(int minFooterTranslation) {
// mMinFooterTranslation = minFooterTranslation;
// return this;
// }
//
// public QuickReturnScrollViewOnScrollChangedListener build() {
// return new QuickReturnScrollViewOnScrollChangedListener(this);
// }
// }
//
// // endregion
// }
| import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.etiennelawlor.quickreturn.R;
import com.etiennelawlor.quickreturn.library.enums.QuickReturnViewType;
import com.etiennelawlor.quickreturn.library.listeners.QuickReturnScrollViewOnScrollChangedListener;
import com.etiennelawlor.quickreturn.library.views.NotifyingScrollView;
import butterknife.Bind;
import butterknife.ButterKnife; | // endregion
// region Lifecycle Methods
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mQuickReturnViewType = QuickReturnViewType.valueOf(getArguments().getString("quick_return_view_type"));
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_quick_return, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
int headerHeight = getResources().getDimensionPixelSize(R.dimen.header_height2);
int headerTranslation = -(headerHeight);
int footerTranslation = getResources().getDimensionPixelSize(R.dimen.footer_height);
| // Path: library/src/main/java/com/etiennelawlor/quickreturn/library/listeners/QuickReturnScrollViewOnScrollChangedListener.java
// public class QuickReturnScrollViewOnScrollChangedListener implements NotifyingScrollView.OnScrollChangedListener {
//
// // region Member Variables
// private final QuickReturnViewType mQuickReturnViewType;
// private final View mHeader;
// private final int mMinHeaderTranslation;
// private final View mFooter;
// private final int mMinFooterTranslation;
//
// private int mHeaderDiffTotal = 0;
// private int mFooterDiffTotal = 0;
// // endregion
//
// // region Constructors
// private QuickReturnScrollViewOnScrollChangedListener(Builder builder) {
// mQuickReturnViewType = builder.mQuickReturnViewType;
// mHeader = builder.mHeader;
// mMinHeaderTranslation = builder.mMinHeaderTranslation;
// mFooter = builder.mFooter;
// mMinFooterTranslation = builder.mMinFooterTranslation;
// }
// // endregion
//
// @Override
// public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
// int diff = oldt - t;
//
// switch (mQuickReturnViewType) {
// case HEADER:
// if (diff <= 0) { // scrolling down
// mHeaderDiffTotal = Math.max(mHeaderDiffTotal + diff, mMinHeaderTranslation);
// } else { // scrolling up
// mHeaderDiffTotal = Math.min(Math.max(mHeaderDiffTotal + diff, mMinHeaderTranslation), 0);
// }
//
// mHeader.setTranslationY(mHeaderDiffTotal);
// break;
// case FOOTER:
// if (diff <= 0) { // scrolling down
// mFooterDiffTotal = Math.max(mFooterDiffTotal + diff, -mMinFooterTranslation);
// } else { // scrolling up
// mFooterDiffTotal = Math.min(Math.max(mFooterDiffTotal + diff, -mMinFooterTranslation), 0);
// }
//
// mFooter.setTranslationY(-mFooterDiffTotal);
// break;
// case BOTH:
// if (diff <= 0) { // scrolling down
// mHeaderDiffTotal = Math.max(mHeaderDiffTotal + diff, mMinHeaderTranslation);
// mFooterDiffTotal = Math.max(mFooterDiffTotal + diff, -mMinFooterTranslation);
// } else { // scrolling up
// mHeaderDiffTotal = Math.min(Math.max(mHeaderDiffTotal + diff, mMinHeaderTranslation), 0);
// mFooterDiffTotal = Math.min(Math.max(mFooterDiffTotal + diff, -mMinFooterTranslation), 0);
// }
//
// mHeader.setTranslationY(mHeaderDiffTotal);
// mFooter.setTranslationY(-mFooterDiffTotal);
// break;
// }
// }
//
// // region Inner Classes
//
// public static class Builder {
// // Required parameters
// private final QuickReturnViewType mQuickReturnViewType;
//
// // Optional parameters - initialized to default values
// private View mHeader = null;
// private int mMinHeaderTranslation = 0;
// private View mFooter = null;
// private int mMinFooterTranslation = 0;
//
// public Builder(QuickReturnViewType quickReturnViewType) {
// mQuickReturnViewType = quickReturnViewType;
// }
//
// public Builder header(View header) {
// mHeader = header;
// return this;
// }
//
// public Builder minHeaderTranslation(int minHeaderTranslation) {
// mMinHeaderTranslation = minHeaderTranslation;
// return this;
// }
//
// public Builder footer(View footer) {
// mFooter = footer;
// return this;
// }
//
// public Builder minFooterTranslation(int minFooterTranslation) {
// mMinFooterTranslation = minFooterTranslation;
// return this;
// }
//
// public QuickReturnScrollViewOnScrollChangedListener build() {
// return new QuickReturnScrollViewOnScrollChangedListener(this);
// }
// }
//
// // endregion
// }
// Path: sample/src/main/java/com/etiennelawlor/quickreturn/fragments/QuickReturnFragment.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.etiennelawlor.quickreturn.R;
import com.etiennelawlor.quickreturn.library.enums.QuickReturnViewType;
import com.etiennelawlor.quickreturn.library.listeners.QuickReturnScrollViewOnScrollChangedListener;
import com.etiennelawlor.quickreturn.library.views.NotifyingScrollView;
import butterknife.Bind;
import butterknife.ButterKnife;
// endregion
// region Lifecycle Methods
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mQuickReturnViewType = QuickReturnViewType.valueOf(getArguments().getString("quick_return_view_type"));
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_quick_return, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
int headerHeight = getResources().getDimensionPixelSize(R.dimen.header_height2);
int headerTranslation = -(headerHeight);
int footerTranslation = getResources().getDimensionPixelSize(R.dimen.footer_height);
| QuickReturnScrollViewOnScrollChangedListener scrollListener; |
mihaicostin/hibernate-l2-memcached | src/test/java/com/integration/com/mc/hibernate/memcached/CacheTimeout.java | // Path: src/test/java/com/integration/com/mc/hibernate/memcached/entities/Person.java
// @Entity
// @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
// public class Person {
//
// @Id
// private Long id;
//
// @Column
// private String name;
//
// @Column
// private String phoneNr;
//
// public Person(Long id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
| import com.integration.com.mc.hibernate.memcached.entities.Person;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Assert;
import org.junit.Test;
import java.util.Properties; | package com.integration.com.mc.hibernate.memcached;
public class CacheTimeout extends AbstractHibernateTestCase {
@Test
public void testQueryCacheQuickExpire() throws Exception {
Properties extraProp = new Properties();
extraProp.put("hibernate.memcached.com.integration.com.mc.hibernate.memcached.entities.Person.cacheTimeSeconds", "2");
SessionFactory sessionFactory = getConfiguration(extraProp).buildSessionFactory();
| // Path: src/test/java/com/integration/com/mc/hibernate/memcached/entities/Person.java
// @Entity
// @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
// public class Person {
//
// @Id
// private Long id;
//
// @Column
// private String name;
//
// @Column
// private String phoneNr;
//
// public Person(Long id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
// Path: src/test/java/com/integration/com/mc/hibernate/memcached/CacheTimeout.java
import com.integration.com.mc.hibernate.memcached.entities.Person;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Assert;
import org.junit.Test;
import java.util.Properties;
package com.integration.com.mc.hibernate.memcached;
public class CacheTimeout extends AbstractHibernateTestCase {
@Test
public void testQueryCacheQuickExpire() throws Exception {
Properties extraProp = new Properties();
extraProp.put("hibernate.memcached.com.integration.com.mc.hibernate.memcached.entities.Person.cacheTimeSeconds", "2");
SessionFactory sessionFactory = getConfiguration(extraProp).buildSessionFactory();
| Person p = new Person(10L, "John"); |
mihaicostin/hibernate-l2-memcached | src/main/java/com/mc/hibernate/memcached/Config.java | // Path: src/main/java/com/mc/hibernate/memcached/keystrategy/KeyStrategy.java
// public interface KeyStrategy {
//
// String toKey(String regionName, long clearIndex, Object key);
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java
// public class Sha1KeyStrategy extends DigestKeyStrategy {
// protected String digest(String key) {
// return StringUtils.sha1Hex(key);
// }
// }
| import com.mc.hibernate.memcached.keystrategy.KeyStrategy;
import com.mc.hibernate.memcached.keystrategy.Sha1KeyStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached;
public class Config {
private final Logger log = LoggerFactory.getLogger(Config.class);
public static final String PROP_PREFIX = "hibernate.memcached.";
private static final String CACHE_TIME_SECONDS = "cacheTimeSeconds";
private static final String LOCK_TIMEOUT_MS = "cacheLockTimeout";
private static final String CLEAR_SUPPORTED = "clearSupported";
private static final String MEMCACHE_CLIENT_FACTORY = "memcacheClientFactory";
private static final String DOGPILE_PREVENTION = "dogpilePrevention";
private static final String DOGPILE_PREVENTION_EXPIRATION_FACTOR = "dogpilePrevention.expirationFactor";
private static final String KEY_STRATEGY = "keyStrategy";
private static final int DEFAULT_CACHE_TIME_SECONDS = 300;
private static final int DEFAULT_CACHE_LOCK_TIMEOUT_MS = 60000;
private static final boolean DEFAULT_CLEAR_SUPPORTED = false;
private static final boolean DEFAULT_DOGPILE_PREVENTION = false;
private static final int DEFAULT_DOGPILE_EXPIRATION_FACTOR = 2;
private static final String DEFAULT_MEMCACHE_CLIENT_FACTORY = "com.mc.hibernate.memcached.spymemcached.SpyMemcacheClientFactory";
private PropertiesHelper props;
public Config(PropertiesHelper props) {
this.props = props;
}
public int getCacheTimeSeconds(String cacheRegion) {
int globalCacheTimeSeconds = props.getInt(PROP_PREFIX + CACHE_TIME_SECONDS, DEFAULT_CACHE_TIME_SECONDS);
return props.getInt(cacheRegionPrefix(cacheRegion) + CACHE_TIME_SECONDS, globalCacheTimeSeconds);
}
public int getCacheLockTimeout(String cacheRegion) {
int globalLockTimeout = props.getInt(PROP_PREFIX + LOCK_TIMEOUT_MS, DEFAULT_CACHE_LOCK_TIMEOUT_MS);
return props.getInt(cacheRegionPrefix(cacheRegion) + LOCK_TIMEOUT_MS, globalLockTimeout);
}
public String getKeyStrategyName(String cacheRegion) { | // Path: src/main/java/com/mc/hibernate/memcached/keystrategy/KeyStrategy.java
// public interface KeyStrategy {
//
// String toKey(String regionName, long clearIndex, Object key);
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java
// public class Sha1KeyStrategy extends DigestKeyStrategy {
// protected String digest(String key) {
// return StringUtils.sha1Hex(key);
// }
// }
// Path: src/main/java/com/mc/hibernate/memcached/Config.java
import com.mc.hibernate.memcached.keystrategy.KeyStrategy;
import com.mc.hibernate.memcached.keystrategy.Sha1KeyStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached;
public class Config {
private final Logger log = LoggerFactory.getLogger(Config.class);
public static final String PROP_PREFIX = "hibernate.memcached.";
private static final String CACHE_TIME_SECONDS = "cacheTimeSeconds";
private static final String LOCK_TIMEOUT_MS = "cacheLockTimeout";
private static final String CLEAR_SUPPORTED = "clearSupported";
private static final String MEMCACHE_CLIENT_FACTORY = "memcacheClientFactory";
private static final String DOGPILE_PREVENTION = "dogpilePrevention";
private static final String DOGPILE_PREVENTION_EXPIRATION_FACTOR = "dogpilePrevention.expirationFactor";
private static final String KEY_STRATEGY = "keyStrategy";
private static final int DEFAULT_CACHE_TIME_SECONDS = 300;
private static final int DEFAULT_CACHE_LOCK_TIMEOUT_MS = 60000;
private static final boolean DEFAULT_CLEAR_SUPPORTED = false;
private static final boolean DEFAULT_DOGPILE_PREVENTION = false;
private static final int DEFAULT_DOGPILE_EXPIRATION_FACTOR = 2;
private static final String DEFAULT_MEMCACHE_CLIENT_FACTORY = "com.mc.hibernate.memcached.spymemcached.SpyMemcacheClientFactory";
private PropertiesHelper props;
public Config(PropertiesHelper props) {
this.props = props;
}
public int getCacheTimeSeconds(String cacheRegion) {
int globalCacheTimeSeconds = props.getInt(PROP_PREFIX + CACHE_TIME_SECONDS, DEFAULT_CACHE_TIME_SECONDS);
return props.getInt(cacheRegionPrefix(cacheRegion) + CACHE_TIME_SECONDS, globalCacheTimeSeconds);
}
public int getCacheLockTimeout(String cacheRegion) {
int globalLockTimeout = props.getInt(PROP_PREFIX + LOCK_TIMEOUT_MS, DEFAULT_CACHE_LOCK_TIMEOUT_MS);
return props.getInt(cacheRegionPrefix(cacheRegion) + LOCK_TIMEOUT_MS, globalLockTimeout);
}
public String getKeyStrategyName(String cacheRegion) { | String globalKeyStrategy = props.get(PROP_PREFIX + KEY_STRATEGY, Sha1KeyStrategy.class.getName()); |
mihaicostin/hibernate-l2-memcached | src/main/java/com/mc/hibernate/memcached/Config.java | // Path: src/main/java/com/mc/hibernate/memcached/keystrategy/KeyStrategy.java
// public interface KeyStrategy {
//
// String toKey(String regionName, long clearIndex, Object key);
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java
// public class Sha1KeyStrategy extends DigestKeyStrategy {
// protected String digest(String key) {
// return StringUtils.sha1Hex(key);
// }
// }
| import com.mc.hibernate.memcached.keystrategy.KeyStrategy;
import com.mc.hibernate.memcached.keystrategy.Sha1KeyStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | private static final String KEY_STRATEGY = "keyStrategy";
private static final int DEFAULT_CACHE_TIME_SECONDS = 300;
private static final int DEFAULT_CACHE_LOCK_TIMEOUT_MS = 60000;
private static final boolean DEFAULT_CLEAR_SUPPORTED = false;
private static final boolean DEFAULT_DOGPILE_PREVENTION = false;
private static final int DEFAULT_DOGPILE_EXPIRATION_FACTOR = 2;
private static final String DEFAULT_MEMCACHE_CLIENT_FACTORY = "com.mc.hibernate.memcached.spymemcached.SpyMemcacheClientFactory";
private PropertiesHelper props;
public Config(PropertiesHelper props) {
this.props = props;
}
public int getCacheTimeSeconds(String cacheRegion) {
int globalCacheTimeSeconds = props.getInt(PROP_PREFIX + CACHE_TIME_SECONDS, DEFAULT_CACHE_TIME_SECONDS);
return props.getInt(cacheRegionPrefix(cacheRegion) + CACHE_TIME_SECONDS, globalCacheTimeSeconds);
}
public int getCacheLockTimeout(String cacheRegion) {
int globalLockTimeout = props.getInt(PROP_PREFIX + LOCK_TIMEOUT_MS, DEFAULT_CACHE_LOCK_TIMEOUT_MS);
return props.getInt(cacheRegionPrefix(cacheRegion) + LOCK_TIMEOUT_MS, globalLockTimeout);
}
public String getKeyStrategyName(String cacheRegion) {
String globalKeyStrategy = props.get(PROP_PREFIX + KEY_STRATEGY, Sha1KeyStrategy.class.getName());
return props.get(cacheRegionPrefix(cacheRegion) + KEY_STRATEGY, globalKeyStrategy);
}
| // Path: src/main/java/com/mc/hibernate/memcached/keystrategy/KeyStrategy.java
// public interface KeyStrategy {
//
// String toKey(String regionName, long clearIndex, Object key);
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java
// public class Sha1KeyStrategy extends DigestKeyStrategy {
// protected String digest(String key) {
// return StringUtils.sha1Hex(key);
// }
// }
// Path: src/main/java/com/mc/hibernate/memcached/Config.java
import com.mc.hibernate.memcached.keystrategy.KeyStrategy;
import com.mc.hibernate.memcached.keystrategy.Sha1KeyStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final String KEY_STRATEGY = "keyStrategy";
private static final int DEFAULT_CACHE_TIME_SECONDS = 300;
private static final int DEFAULT_CACHE_LOCK_TIMEOUT_MS = 60000;
private static final boolean DEFAULT_CLEAR_SUPPORTED = false;
private static final boolean DEFAULT_DOGPILE_PREVENTION = false;
private static final int DEFAULT_DOGPILE_EXPIRATION_FACTOR = 2;
private static final String DEFAULT_MEMCACHE_CLIENT_FACTORY = "com.mc.hibernate.memcached.spymemcached.SpyMemcacheClientFactory";
private PropertiesHelper props;
public Config(PropertiesHelper props) {
this.props = props;
}
public int getCacheTimeSeconds(String cacheRegion) {
int globalCacheTimeSeconds = props.getInt(PROP_PREFIX + CACHE_TIME_SECONDS, DEFAULT_CACHE_TIME_SECONDS);
return props.getInt(cacheRegionPrefix(cacheRegion) + CACHE_TIME_SECONDS, globalCacheTimeSeconds);
}
public int getCacheLockTimeout(String cacheRegion) {
int globalLockTimeout = props.getInt(PROP_PREFIX + LOCK_TIMEOUT_MS, DEFAULT_CACHE_LOCK_TIMEOUT_MS);
return props.getInt(cacheRegionPrefix(cacheRegion) + LOCK_TIMEOUT_MS, globalLockTimeout);
}
public String getKeyStrategyName(String cacheRegion) {
String globalKeyStrategy = props.get(PROP_PREFIX + KEY_STRATEGY, Sha1KeyStrategy.class.getName());
return props.get(cacheRegionPrefix(cacheRegion) + KEY_STRATEGY, globalKeyStrategy);
}
| private KeyStrategy instantiateKeyStrategy(String cls) { |
mihaicostin/hibernate-l2-memcached | src/main/java/com/mc/hibernate/memcached/MemcachedCache.java | // Path: src/main/java/com/mc/hibernate/memcached/keystrategy/KeyStrategy.java
// public interface KeyStrategy {
//
// String toKey(String regionName, long clearIndex, Object key);
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java
// public class Sha1KeyStrategy extends DigestKeyStrategy {
// protected String digest(String key) {
// return StringUtils.sha1Hex(key);
// }
// }
| import com.mc.hibernate.memcached.keystrategy.KeyStrategy;
import com.mc.hibernate.memcached.keystrategy.Sha1KeyStrategy;
import org.hibernate.cache.CacheException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map; | /* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached;
/**
* Wrapper around MemcachedClient instance to provide the bridge between Hibernate and Memcached.
* Uses the regionName given by Hibernate via the {@link MemcachedRegionFactory}
* when generating cache keys.
* All cache operations rely on using a {@link KeyStrategy}
* to generate cache keys for use in memcached.
* <p>
* Support for the {@link #clear()} operation is disabled by default.<br>
* There is no way for this instance of MemcachedCache to know what cache values to "clear" in a given Memcached instance.
* Clear functionality is implemented by incrementing a "clearIndex" value that is always included in the cache-key generation.
* When clear is called the memcached increment function is used to increment the global clean index. When clear is enabled,
* every cache action taken starts with a call to memcached to 'get' the clearIndex counter. That value is then
* applied to the cache key for the cache operation being taken. When the clearIndex is incremented this causes
* the MemcachedCache to generate different cache-keys than it was before. This results in previously cached data being
* abandoned in the cache, and left for memcached to deal with.
* <p>
* For these reasons it is not recommended to rely on clear() as a regular production functionality,
* it is very expensive and generally not very useful anyway.
* <p>
* The MemcachedCache treats Hibernate cache regions as namespaces in Memcached. For more information see the
* <a href="https://code.google.com/p/memcached/wiki/NewProgrammingTricks#Namespacing">memcached FAQ</a>.
*
* @author Ray Krueger
*/
public class MemcachedCache {
private final Logger log = LoggerFactory.getLogger(MemcachedCache.class);
private final String regionName;
private final Memcache memcache;
private final String clearIndexKey;
private int cacheTimeSeconds = 300;
private boolean clearSupported = false; | // Path: src/main/java/com/mc/hibernate/memcached/keystrategy/KeyStrategy.java
// public interface KeyStrategy {
//
// String toKey(String regionName, long clearIndex, Object key);
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java
// public class Sha1KeyStrategy extends DigestKeyStrategy {
// protected String digest(String key) {
// return StringUtils.sha1Hex(key);
// }
// }
// Path: src/main/java/com/mc/hibernate/memcached/MemcachedCache.java
import com.mc.hibernate.memcached.keystrategy.KeyStrategy;
import com.mc.hibernate.memcached.keystrategy.Sha1KeyStrategy;
import org.hibernate.cache.CacheException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached;
/**
* Wrapper around MemcachedClient instance to provide the bridge between Hibernate and Memcached.
* Uses the regionName given by Hibernate via the {@link MemcachedRegionFactory}
* when generating cache keys.
* All cache operations rely on using a {@link KeyStrategy}
* to generate cache keys for use in memcached.
* <p>
* Support for the {@link #clear()} operation is disabled by default.<br>
* There is no way for this instance of MemcachedCache to know what cache values to "clear" in a given Memcached instance.
* Clear functionality is implemented by incrementing a "clearIndex" value that is always included in the cache-key generation.
* When clear is called the memcached increment function is used to increment the global clean index. When clear is enabled,
* every cache action taken starts with a call to memcached to 'get' the clearIndex counter. That value is then
* applied to the cache key for the cache operation being taken. When the clearIndex is incremented this causes
* the MemcachedCache to generate different cache-keys than it was before. This results in previously cached data being
* abandoned in the cache, and left for memcached to deal with.
* <p>
* For these reasons it is not recommended to rely on clear() as a regular production functionality,
* it is very expensive and generally not very useful anyway.
* <p>
* The MemcachedCache treats Hibernate cache regions as namespaces in Memcached. For more information see the
* <a href="https://code.google.com/p/memcached/wiki/NewProgrammingTricks#Namespacing">memcached FAQ</a>.
*
* @author Ray Krueger
*/
public class MemcachedCache {
private final Logger log = LoggerFactory.getLogger(MemcachedCache.class);
private final String regionName;
private final Memcache memcache;
private final String clearIndexKey;
private int cacheTimeSeconds = 300;
private boolean clearSupported = false; | private KeyStrategy keyStrategy = new Sha1KeyStrategy(); |
mihaicostin/hibernate-l2-memcached | src/main/java/com/mc/hibernate/memcached/MemcachedCache.java | // Path: src/main/java/com/mc/hibernate/memcached/keystrategy/KeyStrategy.java
// public interface KeyStrategy {
//
// String toKey(String regionName, long clearIndex, Object key);
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java
// public class Sha1KeyStrategy extends DigestKeyStrategy {
// protected String digest(String key) {
// return StringUtils.sha1Hex(key);
// }
// }
| import com.mc.hibernate.memcached.keystrategy.KeyStrategy;
import com.mc.hibernate.memcached.keystrategy.Sha1KeyStrategy;
import org.hibernate.cache.CacheException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map; | /* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached;
/**
* Wrapper around MemcachedClient instance to provide the bridge between Hibernate and Memcached.
* Uses the regionName given by Hibernate via the {@link MemcachedRegionFactory}
* when generating cache keys.
* All cache operations rely on using a {@link KeyStrategy}
* to generate cache keys for use in memcached.
* <p>
* Support for the {@link #clear()} operation is disabled by default.<br>
* There is no way for this instance of MemcachedCache to know what cache values to "clear" in a given Memcached instance.
* Clear functionality is implemented by incrementing a "clearIndex" value that is always included in the cache-key generation.
* When clear is called the memcached increment function is used to increment the global clean index. When clear is enabled,
* every cache action taken starts with a call to memcached to 'get' the clearIndex counter. That value is then
* applied to the cache key for the cache operation being taken. When the clearIndex is incremented this causes
* the MemcachedCache to generate different cache-keys than it was before. This results in previously cached data being
* abandoned in the cache, and left for memcached to deal with.
* <p>
* For these reasons it is not recommended to rely on clear() as a regular production functionality,
* it is very expensive and generally not very useful anyway.
* <p>
* The MemcachedCache treats Hibernate cache regions as namespaces in Memcached. For more information see the
* <a href="https://code.google.com/p/memcached/wiki/NewProgrammingTricks#Namespacing">memcached FAQ</a>.
*
* @author Ray Krueger
*/
public class MemcachedCache {
private final Logger log = LoggerFactory.getLogger(MemcachedCache.class);
private final String regionName;
private final Memcache memcache;
private final String clearIndexKey;
private int cacheTimeSeconds = 300;
private boolean clearSupported = false; | // Path: src/main/java/com/mc/hibernate/memcached/keystrategy/KeyStrategy.java
// public interface KeyStrategy {
//
// String toKey(String regionName, long clearIndex, Object key);
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java
// public class Sha1KeyStrategy extends DigestKeyStrategy {
// protected String digest(String key) {
// return StringUtils.sha1Hex(key);
// }
// }
// Path: src/main/java/com/mc/hibernate/memcached/MemcachedCache.java
import com.mc.hibernate.memcached.keystrategy.KeyStrategy;
import com.mc.hibernate.memcached.keystrategy.Sha1KeyStrategy;
import org.hibernate.cache.CacheException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached;
/**
* Wrapper around MemcachedClient instance to provide the bridge between Hibernate and Memcached.
* Uses the regionName given by Hibernate via the {@link MemcachedRegionFactory}
* when generating cache keys.
* All cache operations rely on using a {@link KeyStrategy}
* to generate cache keys for use in memcached.
* <p>
* Support for the {@link #clear()} operation is disabled by default.<br>
* There is no way for this instance of MemcachedCache to know what cache values to "clear" in a given Memcached instance.
* Clear functionality is implemented by incrementing a "clearIndex" value that is always included in the cache-key generation.
* When clear is called the memcached increment function is used to increment the global clean index. When clear is enabled,
* every cache action taken starts with a call to memcached to 'get' the clearIndex counter. That value is then
* applied to the cache key for the cache operation being taken. When the clearIndex is incremented this causes
* the MemcachedCache to generate different cache-keys than it was before. This results in previously cached data being
* abandoned in the cache, and left for memcached to deal with.
* <p>
* For these reasons it is not recommended to rely on clear() as a regular production functionality,
* it is very expensive and generally not very useful anyway.
* <p>
* The MemcachedCache treats Hibernate cache regions as namespaces in Memcached. For more information see the
* <a href="https://code.google.com/p/memcached/wiki/NewProgrammingTricks#Namespacing">memcached FAQ</a>.
*
* @author Ray Krueger
*/
public class MemcachedCache {
private final Logger log = LoggerFactory.getLogger(MemcachedCache.class);
private final String regionName;
private final Memcache memcache;
private final String clearIndexKey;
private int cacheTimeSeconds = 300;
private boolean clearSupported = false; | private KeyStrategy keyStrategy = new Sha1KeyStrategy(); |
mihaicostin/hibernate-l2-memcached | src/main/java/com/mc/hibernate/memcached/spymemcached/SpyMemcache.java | // Path: src/main/java/com/mc/hibernate/memcached/LoggingMemcacheExceptionHandler.java
// public class LoggingMemcacheExceptionHandler implements MemcacheExceptionHandler {
//
// private static final Logger log = LoggerFactory.getLogger(LoggingMemcacheExceptionHandler.class);
//
// public void handleErrorOnGet(String key, Exception e) {
// log.warn("Cache 'get' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnSet(String key, int cacheTimeSeconds, Object o, Exception e) {
// log.warn("Cache 'set' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnDelete(String key, Exception e) {
// log.warn("Cache 'delete' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnIncr(String key, int factor, int startingValue, Exception e) {
// log.warn("Cache 'incr' failed for key [" + key + "]", e);
// }
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/Memcache.java
// public interface Memcache {
//
// Object get(String key);
//
// Map<String, Object> getMulti(String... keys);
//
// void set(String key, int cacheTimeSeconds, Object o);
//
// void delete(String key);
//
// void incr(String key, int factor, int startingValue);
//
// void shutdown();
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/MemcacheExceptionHandler.java
// public interface MemcacheExceptionHandler {
//
// void handleErrorOnGet(String key, Exception e);
//
// void handleErrorOnSet(String key, int cacheTimeSeconds, Object o, Exception e);
//
// void handleErrorOnDelete(String key, Exception e);
//
// void handleErrorOnIncr(String key, int factor, int startingValue, Exception e);
//
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/utils/StringUtils.java
// public class StringUtils {
//
// private static final char[] DIGITS = {
// '0', '1', '2', '3', '4', '5', '6', '7',
// '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
// };
//
// public static String join(Object[] array, String separator) {
// if (array == null) {
// return null;
// }
// int arraySize = array.length;
// StringBuilder buffer = new StringBuilder();
//
// for (int i = 0; i < arraySize; i++) {
// if (i > 0) {
// buffer.append(separator);
// }
// if (array[i] != null) {
// buffer.append(array[i]);
// }
// }
// return buffer.toString();
// }
//
// public static String md5Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("MD5", data);
//
// return toHexString(bytes);
// }
//
// public static String sha1Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("SHA1", data);
//
// return toHexString(bytes);
// }
//
// private static String toHexString(byte[] bytes) {
// int l = bytes.length;
//
// char[] out = new char[l << 1];
//
// for (int i = 0, j = 0; i < l; i++) {
// out[j++] = DIGITS[(0xF0 & bytes[i]) >>> 4];
// out[j++] = DIGITS[0x0F & bytes[i]];
// }
//
// return new String(out);
// }
//
// private static byte[] digest(String algorithm, String data) {
// MessageDigest digest;
// try {
// digest = MessageDigest.getInstance(algorithm);
// } catch (NoSuchAlgorithmException e) {
// throw new RuntimeException(e);
// }
//
// return digest.digest(data.getBytes());
// }
// }
| import com.mc.hibernate.memcached.LoggingMemcacheExceptionHandler;
import com.mc.hibernate.memcached.Memcache;
import com.mc.hibernate.memcached.MemcacheExceptionHandler;
import com.mc.hibernate.memcached.utils.StringUtils;
import net.spy.memcached.MemcachedClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map; | /* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached.spymemcached;
public class SpyMemcache implements Memcache {
private static final Logger log = LoggerFactory.getLogger(SpyMemcache.class); | // Path: src/main/java/com/mc/hibernate/memcached/LoggingMemcacheExceptionHandler.java
// public class LoggingMemcacheExceptionHandler implements MemcacheExceptionHandler {
//
// private static final Logger log = LoggerFactory.getLogger(LoggingMemcacheExceptionHandler.class);
//
// public void handleErrorOnGet(String key, Exception e) {
// log.warn("Cache 'get' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnSet(String key, int cacheTimeSeconds, Object o, Exception e) {
// log.warn("Cache 'set' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnDelete(String key, Exception e) {
// log.warn("Cache 'delete' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnIncr(String key, int factor, int startingValue, Exception e) {
// log.warn("Cache 'incr' failed for key [" + key + "]", e);
// }
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/Memcache.java
// public interface Memcache {
//
// Object get(String key);
//
// Map<String, Object> getMulti(String... keys);
//
// void set(String key, int cacheTimeSeconds, Object o);
//
// void delete(String key);
//
// void incr(String key, int factor, int startingValue);
//
// void shutdown();
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/MemcacheExceptionHandler.java
// public interface MemcacheExceptionHandler {
//
// void handleErrorOnGet(String key, Exception e);
//
// void handleErrorOnSet(String key, int cacheTimeSeconds, Object o, Exception e);
//
// void handleErrorOnDelete(String key, Exception e);
//
// void handleErrorOnIncr(String key, int factor, int startingValue, Exception e);
//
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/utils/StringUtils.java
// public class StringUtils {
//
// private static final char[] DIGITS = {
// '0', '1', '2', '3', '4', '5', '6', '7',
// '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
// };
//
// public static String join(Object[] array, String separator) {
// if (array == null) {
// return null;
// }
// int arraySize = array.length;
// StringBuilder buffer = new StringBuilder();
//
// for (int i = 0; i < arraySize; i++) {
// if (i > 0) {
// buffer.append(separator);
// }
// if (array[i] != null) {
// buffer.append(array[i]);
// }
// }
// return buffer.toString();
// }
//
// public static String md5Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("MD5", data);
//
// return toHexString(bytes);
// }
//
// public static String sha1Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("SHA1", data);
//
// return toHexString(bytes);
// }
//
// private static String toHexString(byte[] bytes) {
// int l = bytes.length;
//
// char[] out = new char[l << 1];
//
// for (int i = 0, j = 0; i < l; i++) {
// out[j++] = DIGITS[(0xF0 & bytes[i]) >>> 4];
// out[j++] = DIGITS[0x0F & bytes[i]];
// }
//
// return new String(out);
// }
//
// private static byte[] digest(String algorithm, String data) {
// MessageDigest digest;
// try {
// digest = MessageDigest.getInstance(algorithm);
// } catch (NoSuchAlgorithmException e) {
// throw new RuntimeException(e);
// }
//
// return digest.digest(data.getBytes());
// }
// }
// Path: src/main/java/com/mc/hibernate/memcached/spymemcached/SpyMemcache.java
import com.mc.hibernate.memcached.LoggingMemcacheExceptionHandler;
import com.mc.hibernate.memcached.Memcache;
import com.mc.hibernate.memcached.MemcacheExceptionHandler;
import com.mc.hibernate.memcached.utils.StringUtils;
import net.spy.memcached.MemcachedClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached.spymemcached;
public class SpyMemcache implements Memcache {
private static final Logger log = LoggerFactory.getLogger(SpyMemcache.class); | private MemcacheExceptionHandler exceptionHandler = new LoggingMemcacheExceptionHandler(); |
mihaicostin/hibernate-l2-memcached | src/main/java/com/mc/hibernate/memcached/spymemcached/SpyMemcache.java | // Path: src/main/java/com/mc/hibernate/memcached/LoggingMemcacheExceptionHandler.java
// public class LoggingMemcacheExceptionHandler implements MemcacheExceptionHandler {
//
// private static final Logger log = LoggerFactory.getLogger(LoggingMemcacheExceptionHandler.class);
//
// public void handleErrorOnGet(String key, Exception e) {
// log.warn("Cache 'get' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnSet(String key, int cacheTimeSeconds, Object o, Exception e) {
// log.warn("Cache 'set' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnDelete(String key, Exception e) {
// log.warn("Cache 'delete' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnIncr(String key, int factor, int startingValue, Exception e) {
// log.warn("Cache 'incr' failed for key [" + key + "]", e);
// }
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/Memcache.java
// public interface Memcache {
//
// Object get(String key);
//
// Map<String, Object> getMulti(String... keys);
//
// void set(String key, int cacheTimeSeconds, Object o);
//
// void delete(String key);
//
// void incr(String key, int factor, int startingValue);
//
// void shutdown();
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/MemcacheExceptionHandler.java
// public interface MemcacheExceptionHandler {
//
// void handleErrorOnGet(String key, Exception e);
//
// void handleErrorOnSet(String key, int cacheTimeSeconds, Object o, Exception e);
//
// void handleErrorOnDelete(String key, Exception e);
//
// void handleErrorOnIncr(String key, int factor, int startingValue, Exception e);
//
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/utils/StringUtils.java
// public class StringUtils {
//
// private static final char[] DIGITS = {
// '0', '1', '2', '3', '4', '5', '6', '7',
// '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
// };
//
// public static String join(Object[] array, String separator) {
// if (array == null) {
// return null;
// }
// int arraySize = array.length;
// StringBuilder buffer = new StringBuilder();
//
// for (int i = 0; i < arraySize; i++) {
// if (i > 0) {
// buffer.append(separator);
// }
// if (array[i] != null) {
// buffer.append(array[i]);
// }
// }
// return buffer.toString();
// }
//
// public static String md5Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("MD5", data);
//
// return toHexString(bytes);
// }
//
// public static String sha1Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("SHA1", data);
//
// return toHexString(bytes);
// }
//
// private static String toHexString(byte[] bytes) {
// int l = bytes.length;
//
// char[] out = new char[l << 1];
//
// for (int i = 0, j = 0; i < l; i++) {
// out[j++] = DIGITS[(0xF0 & bytes[i]) >>> 4];
// out[j++] = DIGITS[0x0F & bytes[i]];
// }
//
// return new String(out);
// }
//
// private static byte[] digest(String algorithm, String data) {
// MessageDigest digest;
// try {
// digest = MessageDigest.getInstance(algorithm);
// } catch (NoSuchAlgorithmException e) {
// throw new RuntimeException(e);
// }
//
// return digest.digest(data.getBytes());
// }
// }
| import com.mc.hibernate.memcached.LoggingMemcacheExceptionHandler;
import com.mc.hibernate.memcached.Memcache;
import com.mc.hibernate.memcached.MemcacheExceptionHandler;
import com.mc.hibernate.memcached.utils.StringUtils;
import net.spy.memcached.MemcachedClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map; | /* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached.spymemcached;
public class SpyMemcache implements Memcache {
private static final Logger log = LoggerFactory.getLogger(SpyMemcache.class); | // Path: src/main/java/com/mc/hibernate/memcached/LoggingMemcacheExceptionHandler.java
// public class LoggingMemcacheExceptionHandler implements MemcacheExceptionHandler {
//
// private static final Logger log = LoggerFactory.getLogger(LoggingMemcacheExceptionHandler.class);
//
// public void handleErrorOnGet(String key, Exception e) {
// log.warn("Cache 'get' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnSet(String key, int cacheTimeSeconds, Object o, Exception e) {
// log.warn("Cache 'set' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnDelete(String key, Exception e) {
// log.warn("Cache 'delete' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnIncr(String key, int factor, int startingValue, Exception e) {
// log.warn("Cache 'incr' failed for key [" + key + "]", e);
// }
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/Memcache.java
// public interface Memcache {
//
// Object get(String key);
//
// Map<String, Object> getMulti(String... keys);
//
// void set(String key, int cacheTimeSeconds, Object o);
//
// void delete(String key);
//
// void incr(String key, int factor, int startingValue);
//
// void shutdown();
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/MemcacheExceptionHandler.java
// public interface MemcacheExceptionHandler {
//
// void handleErrorOnGet(String key, Exception e);
//
// void handleErrorOnSet(String key, int cacheTimeSeconds, Object o, Exception e);
//
// void handleErrorOnDelete(String key, Exception e);
//
// void handleErrorOnIncr(String key, int factor, int startingValue, Exception e);
//
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/utils/StringUtils.java
// public class StringUtils {
//
// private static final char[] DIGITS = {
// '0', '1', '2', '3', '4', '5', '6', '7',
// '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
// };
//
// public static String join(Object[] array, String separator) {
// if (array == null) {
// return null;
// }
// int arraySize = array.length;
// StringBuilder buffer = new StringBuilder();
//
// for (int i = 0; i < arraySize; i++) {
// if (i > 0) {
// buffer.append(separator);
// }
// if (array[i] != null) {
// buffer.append(array[i]);
// }
// }
// return buffer.toString();
// }
//
// public static String md5Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("MD5", data);
//
// return toHexString(bytes);
// }
//
// public static String sha1Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("SHA1", data);
//
// return toHexString(bytes);
// }
//
// private static String toHexString(byte[] bytes) {
// int l = bytes.length;
//
// char[] out = new char[l << 1];
//
// for (int i = 0, j = 0; i < l; i++) {
// out[j++] = DIGITS[(0xF0 & bytes[i]) >>> 4];
// out[j++] = DIGITS[0x0F & bytes[i]];
// }
//
// return new String(out);
// }
//
// private static byte[] digest(String algorithm, String data) {
// MessageDigest digest;
// try {
// digest = MessageDigest.getInstance(algorithm);
// } catch (NoSuchAlgorithmException e) {
// throw new RuntimeException(e);
// }
//
// return digest.digest(data.getBytes());
// }
// }
// Path: src/main/java/com/mc/hibernate/memcached/spymemcached/SpyMemcache.java
import com.mc.hibernate.memcached.LoggingMemcacheExceptionHandler;
import com.mc.hibernate.memcached.Memcache;
import com.mc.hibernate.memcached.MemcacheExceptionHandler;
import com.mc.hibernate.memcached.utils.StringUtils;
import net.spy.memcached.MemcachedClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached.spymemcached;
public class SpyMemcache implements Memcache {
private static final Logger log = LoggerFactory.getLogger(SpyMemcache.class); | private MemcacheExceptionHandler exceptionHandler = new LoggingMemcacheExceptionHandler(); |
mihaicostin/hibernate-l2-memcached | src/main/java/com/mc/hibernate/memcached/spymemcached/SpyMemcache.java | // Path: src/main/java/com/mc/hibernate/memcached/LoggingMemcacheExceptionHandler.java
// public class LoggingMemcacheExceptionHandler implements MemcacheExceptionHandler {
//
// private static final Logger log = LoggerFactory.getLogger(LoggingMemcacheExceptionHandler.class);
//
// public void handleErrorOnGet(String key, Exception e) {
// log.warn("Cache 'get' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnSet(String key, int cacheTimeSeconds, Object o, Exception e) {
// log.warn("Cache 'set' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnDelete(String key, Exception e) {
// log.warn("Cache 'delete' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnIncr(String key, int factor, int startingValue, Exception e) {
// log.warn("Cache 'incr' failed for key [" + key + "]", e);
// }
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/Memcache.java
// public interface Memcache {
//
// Object get(String key);
//
// Map<String, Object> getMulti(String... keys);
//
// void set(String key, int cacheTimeSeconds, Object o);
//
// void delete(String key);
//
// void incr(String key, int factor, int startingValue);
//
// void shutdown();
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/MemcacheExceptionHandler.java
// public interface MemcacheExceptionHandler {
//
// void handleErrorOnGet(String key, Exception e);
//
// void handleErrorOnSet(String key, int cacheTimeSeconds, Object o, Exception e);
//
// void handleErrorOnDelete(String key, Exception e);
//
// void handleErrorOnIncr(String key, int factor, int startingValue, Exception e);
//
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/utils/StringUtils.java
// public class StringUtils {
//
// private static final char[] DIGITS = {
// '0', '1', '2', '3', '4', '5', '6', '7',
// '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
// };
//
// public static String join(Object[] array, String separator) {
// if (array == null) {
// return null;
// }
// int arraySize = array.length;
// StringBuilder buffer = new StringBuilder();
//
// for (int i = 0; i < arraySize; i++) {
// if (i > 0) {
// buffer.append(separator);
// }
// if (array[i] != null) {
// buffer.append(array[i]);
// }
// }
// return buffer.toString();
// }
//
// public static String md5Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("MD5", data);
//
// return toHexString(bytes);
// }
//
// public static String sha1Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("SHA1", data);
//
// return toHexString(bytes);
// }
//
// private static String toHexString(byte[] bytes) {
// int l = bytes.length;
//
// char[] out = new char[l << 1];
//
// for (int i = 0, j = 0; i < l; i++) {
// out[j++] = DIGITS[(0xF0 & bytes[i]) >>> 4];
// out[j++] = DIGITS[0x0F & bytes[i]];
// }
//
// return new String(out);
// }
//
// private static byte[] digest(String algorithm, String data) {
// MessageDigest digest;
// try {
// digest = MessageDigest.getInstance(algorithm);
// } catch (NoSuchAlgorithmException e) {
// throw new RuntimeException(e);
// }
//
// return digest.digest(data.getBytes());
// }
// }
| import com.mc.hibernate.memcached.LoggingMemcacheExceptionHandler;
import com.mc.hibernate.memcached.Memcache;
import com.mc.hibernate.memcached.MemcacheExceptionHandler;
import com.mc.hibernate.memcached.utils.StringUtils;
import net.spy.memcached.MemcachedClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map; | /* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached.spymemcached;
public class SpyMemcache implements Memcache {
private static final Logger log = LoggerFactory.getLogger(SpyMemcache.class);
private MemcacheExceptionHandler exceptionHandler = new LoggingMemcacheExceptionHandler();
private final MemcachedClient memcachedClient;
public SpyMemcache(MemcachedClient memcachedClient) {
this.memcachedClient = memcachedClient;
}
public Object get(String key) {
try {
log.debug("MemcachedClient.get({})", key);
return memcachedClient.get(key);
} catch (Exception e) {
exceptionHandler.handleErrorOnGet(key, e);
}
return null;
}
public Map<String, Object> getMulti(String... keys) {
try {
return memcachedClient.getBulk(keys);
} catch (Exception e) { | // Path: src/main/java/com/mc/hibernate/memcached/LoggingMemcacheExceptionHandler.java
// public class LoggingMemcacheExceptionHandler implements MemcacheExceptionHandler {
//
// private static final Logger log = LoggerFactory.getLogger(LoggingMemcacheExceptionHandler.class);
//
// public void handleErrorOnGet(String key, Exception e) {
// log.warn("Cache 'get' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnSet(String key, int cacheTimeSeconds, Object o, Exception e) {
// log.warn("Cache 'set' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnDelete(String key, Exception e) {
// log.warn("Cache 'delete' failed for key [" + key + "]", e);
// }
//
// public void handleErrorOnIncr(String key, int factor, int startingValue, Exception e) {
// log.warn("Cache 'incr' failed for key [" + key + "]", e);
// }
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/Memcache.java
// public interface Memcache {
//
// Object get(String key);
//
// Map<String, Object> getMulti(String... keys);
//
// void set(String key, int cacheTimeSeconds, Object o);
//
// void delete(String key);
//
// void incr(String key, int factor, int startingValue);
//
// void shutdown();
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/MemcacheExceptionHandler.java
// public interface MemcacheExceptionHandler {
//
// void handleErrorOnGet(String key, Exception e);
//
// void handleErrorOnSet(String key, int cacheTimeSeconds, Object o, Exception e);
//
// void handleErrorOnDelete(String key, Exception e);
//
// void handleErrorOnIncr(String key, int factor, int startingValue, Exception e);
//
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/utils/StringUtils.java
// public class StringUtils {
//
// private static final char[] DIGITS = {
// '0', '1', '2', '3', '4', '5', '6', '7',
// '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
// };
//
// public static String join(Object[] array, String separator) {
// if (array == null) {
// return null;
// }
// int arraySize = array.length;
// StringBuilder buffer = new StringBuilder();
//
// for (int i = 0; i < arraySize; i++) {
// if (i > 0) {
// buffer.append(separator);
// }
// if (array[i] != null) {
// buffer.append(array[i]);
// }
// }
// return buffer.toString();
// }
//
// public static String md5Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("MD5", data);
//
// return toHexString(bytes);
// }
//
// public static String sha1Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("SHA1", data);
//
// return toHexString(bytes);
// }
//
// private static String toHexString(byte[] bytes) {
// int l = bytes.length;
//
// char[] out = new char[l << 1];
//
// for (int i = 0, j = 0; i < l; i++) {
// out[j++] = DIGITS[(0xF0 & bytes[i]) >>> 4];
// out[j++] = DIGITS[0x0F & bytes[i]];
// }
//
// return new String(out);
// }
//
// private static byte[] digest(String algorithm, String data) {
// MessageDigest digest;
// try {
// digest = MessageDigest.getInstance(algorithm);
// } catch (NoSuchAlgorithmException e) {
// throw new RuntimeException(e);
// }
//
// return digest.digest(data.getBytes());
// }
// }
// Path: src/main/java/com/mc/hibernate/memcached/spymemcached/SpyMemcache.java
import com.mc.hibernate.memcached.LoggingMemcacheExceptionHandler;
import com.mc.hibernate.memcached.Memcache;
import com.mc.hibernate.memcached.MemcacheExceptionHandler;
import com.mc.hibernate.memcached.utils.StringUtils;
import net.spy.memcached.MemcachedClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached.spymemcached;
public class SpyMemcache implements Memcache {
private static final Logger log = LoggerFactory.getLogger(SpyMemcache.class);
private MemcacheExceptionHandler exceptionHandler = new LoggingMemcacheExceptionHandler();
private final MemcachedClient memcachedClient;
public SpyMemcache(MemcachedClient memcachedClient) {
this.memcachedClient = memcachedClient;
}
public Object get(String key) {
try {
log.debug("MemcachedClient.get({})", key);
return memcachedClient.get(key);
} catch (Exception e) {
exceptionHandler.handleErrorOnGet(key, e);
}
return null;
}
public Map<String, Object> getMulti(String... keys) {
try {
return memcachedClient.getBulk(keys);
} catch (Exception e) { | exceptionHandler.handleErrorOnGet(StringUtils.join(keys, ", "), e); |
mihaicostin/hibernate-l2-memcached | src/test/java/com/mc/hibernate/memcached/MemcachedCacheTest.java | // Path: src/main/java/com/mc/hibernate/memcached/keystrategy/KeyStrategy.java
// public interface KeyStrategy {
//
// String toKey(String regionName, long clearIndex, Object key);
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java
// public class Sha1KeyStrategy extends DigestKeyStrategy {
// protected String digest(String key) {
// return StringUtils.sha1Hex(key);
// }
// }
//
// Path: src/test/java/com/mc/hibernate/memcached/mock/MockMemcached.java
// public class MockMemcached implements Memcache {
//
// private Map<String, Object> cache = new HashMap<>();
//
// public Object get(String key) {
// return cache.get(key);
// }
//
// public void set(String key, int cacheTimeSeconds, Object o) {
// cache.put(key, o);
// }
//
// public void delete(String key) {
// cache.remove(key);
// }
//
// public void incr(String key, int factor, int startingValue) {
// String counter = (String) cache.get(key);
// if (counter != null) {
// cache.put(key, Long.parseLong(counter) + 1);
// } else {
// cache.put(key, String.valueOf(startingValue));
// }
// }
//
// public void shutdown() {
//
// }
//
// public Map<String, Object> getMulti(String... keys) {
// Map<String, Object> result = new HashMap<>();
// for (String key : keys) {
// result.put(key, cache.get(key));
// }
// return result;
// }
//
// }
| import com.mc.hibernate.memcached.keystrategy.KeyStrategy;
import com.mc.hibernate.memcached.keystrategy.Sha1KeyStrategy;
import com.mc.hibernate.memcached.mock.MockMemcached;
import org.junit.Test;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull; | package com.mc.hibernate.memcached;
public class MemcachedCacheTest extends BaseTest {
private MemcachedCache cache;
private Config emptyConfig = new Config(new PropertiesHelper(new Properties()));
@Test
public void testBasics() { | // Path: src/main/java/com/mc/hibernate/memcached/keystrategy/KeyStrategy.java
// public interface KeyStrategy {
//
// String toKey(String regionName, long clearIndex, Object key);
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java
// public class Sha1KeyStrategy extends DigestKeyStrategy {
// protected String digest(String key) {
// return StringUtils.sha1Hex(key);
// }
// }
//
// Path: src/test/java/com/mc/hibernate/memcached/mock/MockMemcached.java
// public class MockMemcached implements Memcache {
//
// private Map<String, Object> cache = new HashMap<>();
//
// public Object get(String key) {
// return cache.get(key);
// }
//
// public void set(String key, int cacheTimeSeconds, Object o) {
// cache.put(key, o);
// }
//
// public void delete(String key) {
// cache.remove(key);
// }
//
// public void incr(String key, int factor, int startingValue) {
// String counter = (String) cache.get(key);
// if (counter != null) {
// cache.put(key, Long.parseLong(counter) + 1);
// } else {
// cache.put(key, String.valueOf(startingValue));
// }
// }
//
// public void shutdown() {
//
// }
//
// public Map<String, Object> getMulti(String... keys) {
// Map<String, Object> result = new HashMap<>();
// for (String key : keys) {
// result.put(key, cache.get(key));
// }
// return result;
// }
//
// }
// Path: src/test/java/com/mc/hibernate/memcached/MemcachedCacheTest.java
import com.mc.hibernate.memcached.keystrategy.KeyStrategy;
import com.mc.hibernate.memcached.keystrategy.Sha1KeyStrategy;
import com.mc.hibernate.memcached.mock.MockMemcached;
import org.junit.Test;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
package com.mc.hibernate.memcached;
public class MemcachedCacheTest extends BaseTest {
private MemcachedCache cache;
private Config emptyConfig = new Config(new PropertiesHelper(new Properties()));
@Test
public void testBasics() { | cache = new MemcachedCache("region", new MockMemcached(), emptyConfig); |
mihaicostin/hibernate-l2-memcached | src/test/java/com/mc/hibernate/memcached/MemcachedCacheTest.java | // Path: src/main/java/com/mc/hibernate/memcached/keystrategy/KeyStrategy.java
// public interface KeyStrategy {
//
// String toKey(String regionName, long clearIndex, Object key);
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java
// public class Sha1KeyStrategy extends DigestKeyStrategy {
// protected String digest(String key) {
// return StringUtils.sha1Hex(key);
// }
// }
//
// Path: src/test/java/com/mc/hibernate/memcached/mock/MockMemcached.java
// public class MockMemcached implements Memcache {
//
// private Map<String, Object> cache = new HashMap<>();
//
// public Object get(String key) {
// return cache.get(key);
// }
//
// public void set(String key, int cacheTimeSeconds, Object o) {
// cache.put(key, o);
// }
//
// public void delete(String key) {
// cache.remove(key);
// }
//
// public void incr(String key, int factor, int startingValue) {
// String counter = (String) cache.get(key);
// if (counter != null) {
// cache.put(key, Long.parseLong(counter) + 1);
// } else {
// cache.put(key, String.valueOf(startingValue));
// }
// }
//
// public void shutdown() {
//
// }
//
// public Map<String, Object> getMulti(String... keys) {
// Map<String, Object> result = new HashMap<>();
// for (String key : keys) {
// result.put(key, cache.get(key));
// }
// return result;
// }
//
// }
| import com.mc.hibernate.memcached.keystrategy.KeyStrategy;
import com.mc.hibernate.memcached.keystrategy.Sha1KeyStrategy;
import com.mc.hibernate.memcached.mock.MockMemcached;
import org.junit.Test;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull; | package com.mc.hibernate.memcached;
public class MemcachedCacheTest extends BaseTest {
private MemcachedCache cache;
private Config emptyConfig = new Config(new PropertiesHelper(new Properties()));
@Test
public void testBasics() {
cache = new MemcachedCache("region", new MockMemcached(), emptyConfig);
assertNull(cache.get("test"));
cache.put("test", "value");
assertEquals("value", cache.get("test"));
cache.update("test", "blah");
assertEquals("blah", cache.read("test"));
cache.remove("test");
assertNull(cache.get("test"));
}
@Test
public void testDogpileCacheMiss() {
MockMemcached mockCache = new MockMemcached();
cache = new MemcachedCache("region", mockCache, emptyConfig); | // Path: src/main/java/com/mc/hibernate/memcached/keystrategy/KeyStrategy.java
// public interface KeyStrategy {
//
// String toKey(String regionName, long clearIndex, Object key);
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java
// public class Sha1KeyStrategy extends DigestKeyStrategy {
// protected String digest(String key) {
// return StringUtils.sha1Hex(key);
// }
// }
//
// Path: src/test/java/com/mc/hibernate/memcached/mock/MockMemcached.java
// public class MockMemcached implements Memcache {
//
// private Map<String, Object> cache = new HashMap<>();
//
// public Object get(String key) {
// return cache.get(key);
// }
//
// public void set(String key, int cacheTimeSeconds, Object o) {
// cache.put(key, o);
// }
//
// public void delete(String key) {
// cache.remove(key);
// }
//
// public void incr(String key, int factor, int startingValue) {
// String counter = (String) cache.get(key);
// if (counter != null) {
// cache.put(key, Long.parseLong(counter) + 1);
// } else {
// cache.put(key, String.valueOf(startingValue));
// }
// }
//
// public void shutdown() {
//
// }
//
// public Map<String, Object> getMulti(String... keys) {
// Map<String, Object> result = new HashMap<>();
// for (String key : keys) {
// result.put(key, cache.get(key));
// }
// return result;
// }
//
// }
// Path: src/test/java/com/mc/hibernate/memcached/MemcachedCacheTest.java
import com.mc.hibernate.memcached.keystrategy.KeyStrategy;
import com.mc.hibernate.memcached.keystrategy.Sha1KeyStrategy;
import com.mc.hibernate.memcached.mock.MockMemcached;
import org.junit.Test;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
package com.mc.hibernate.memcached;
public class MemcachedCacheTest extends BaseTest {
private MemcachedCache cache;
private Config emptyConfig = new Config(new PropertiesHelper(new Properties()));
@Test
public void testBasics() {
cache = new MemcachedCache("region", new MockMemcached(), emptyConfig);
assertNull(cache.get("test"));
cache.put("test", "value");
assertEquals("value", cache.get("test"));
cache.update("test", "blah");
assertEquals("blah", cache.read("test"));
cache.remove("test");
assertNull(cache.get("test"));
}
@Test
public void testDogpileCacheMiss() {
MockMemcached mockCache = new MockMemcached();
cache = new MemcachedCache("region", mockCache, emptyConfig); | Sha1KeyStrategy strategy = new Sha1KeyStrategy(); |
mihaicostin/hibernate-l2-memcached | src/test/java/com/mc/hibernate/memcached/MemcachedCacheTest.java | // Path: src/main/java/com/mc/hibernate/memcached/keystrategy/KeyStrategy.java
// public interface KeyStrategy {
//
// String toKey(String regionName, long clearIndex, Object key);
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java
// public class Sha1KeyStrategy extends DigestKeyStrategy {
// protected String digest(String key) {
// return StringUtils.sha1Hex(key);
// }
// }
//
// Path: src/test/java/com/mc/hibernate/memcached/mock/MockMemcached.java
// public class MockMemcached implements Memcache {
//
// private Map<String, Object> cache = new HashMap<>();
//
// public Object get(String key) {
// return cache.get(key);
// }
//
// public void set(String key, int cacheTimeSeconds, Object o) {
// cache.put(key, o);
// }
//
// public void delete(String key) {
// cache.remove(key);
// }
//
// public void incr(String key, int factor, int startingValue) {
// String counter = (String) cache.get(key);
// if (counter != null) {
// cache.put(key, Long.parseLong(counter) + 1);
// } else {
// cache.put(key, String.valueOf(startingValue));
// }
// }
//
// public void shutdown() {
//
// }
//
// public Map<String, Object> getMulti(String... keys) {
// Map<String, Object> result = new HashMap<>();
// for (String key : keys) {
// result.put(key, cache.get(key));
// }
// return result;
// }
//
// }
| import com.mc.hibernate.memcached.keystrategy.KeyStrategy;
import com.mc.hibernate.memcached.keystrategy.Sha1KeyStrategy;
import com.mc.hibernate.memcached.mock.MockMemcached;
import org.junit.Test;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull; |
cache.update("test", "blah");
assertEquals("blah", cache.read("test"));
cache.remove("test");
assertNull(cache.get("test"));
}
@Test
public void testDogpileCacheMiss() {
MockMemcached mockCache = new MockMemcached();
cache = new MemcachedCache("region", mockCache, emptyConfig);
Sha1KeyStrategy strategy = new Sha1KeyStrategy();
cache.setKeyStrategy(strategy);
cache.setDogpilePreventionEnabled(true);
cache.setCacheTimeSeconds(1);
cache.setDogpilePreventionExpirationFactor(2);
String key = strategy.toKey("region", 0, "test");
assertNull(cache.get("test"));
assertEquals(MemcachedCache.DOGPILE_TOKEN, mockCache.get(key + ".dogpileTokenKey"));
cache.put("test", "value");
assertEquals("value", mockCache.get(key));
}
@Test
public void testDogpileCacheHit() {
MockMemcached mockCache = new MockMemcached();
cache = new MemcachedCache("region", mockCache, emptyConfig); | // Path: src/main/java/com/mc/hibernate/memcached/keystrategy/KeyStrategy.java
// public interface KeyStrategy {
//
// String toKey(String regionName, long clearIndex, Object key);
// }
//
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java
// public class Sha1KeyStrategy extends DigestKeyStrategy {
// protected String digest(String key) {
// return StringUtils.sha1Hex(key);
// }
// }
//
// Path: src/test/java/com/mc/hibernate/memcached/mock/MockMemcached.java
// public class MockMemcached implements Memcache {
//
// private Map<String, Object> cache = new HashMap<>();
//
// public Object get(String key) {
// return cache.get(key);
// }
//
// public void set(String key, int cacheTimeSeconds, Object o) {
// cache.put(key, o);
// }
//
// public void delete(String key) {
// cache.remove(key);
// }
//
// public void incr(String key, int factor, int startingValue) {
// String counter = (String) cache.get(key);
// if (counter != null) {
// cache.put(key, Long.parseLong(counter) + 1);
// } else {
// cache.put(key, String.valueOf(startingValue));
// }
// }
//
// public void shutdown() {
//
// }
//
// public Map<String, Object> getMulti(String... keys) {
// Map<String, Object> result = new HashMap<>();
// for (String key : keys) {
// result.put(key, cache.get(key));
// }
// return result;
// }
//
// }
// Path: src/test/java/com/mc/hibernate/memcached/MemcachedCacheTest.java
import com.mc.hibernate.memcached.keystrategy.KeyStrategy;
import com.mc.hibernate.memcached.keystrategy.Sha1KeyStrategy;
import com.mc.hibernate.memcached.mock.MockMemcached;
import org.junit.Test;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
cache.update("test", "blah");
assertEquals("blah", cache.read("test"));
cache.remove("test");
assertNull(cache.get("test"));
}
@Test
public void testDogpileCacheMiss() {
MockMemcached mockCache = new MockMemcached();
cache = new MemcachedCache("region", mockCache, emptyConfig);
Sha1KeyStrategy strategy = new Sha1KeyStrategy();
cache.setKeyStrategy(strategy);
cache.setDogpilePreventionEnabled(true);
cache.setCacheTimeSeconds(1);
cache.setDogpilePreventionExpirationFactor(2);
String key = strategy.toKey("region", 0, "test");
assertNull(cache.get("test"));
assertEquals(MemcachedCache.DOGPILE_TOKEN, mockCache.get(key + ".dogpileTokenKey"));
cache.put("test", "value");
assertEquals("value", mockCache.get(key));
}
@Test
public void testDogpileCacheHit() {
MockMemcached mockCache = new MockMemcached();
cache = new MemcachedCache("region", mockCache, emptyConfig); | KeyStrategy strategy = new Sha1KeyStrategy(); |
mihaicostin/hibernate-l2-memcached | src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java | // Path: src/main/java/com/mc/hibernate/memcached/utils/StringUtils.java
// public class StringUtils {
//
// private static final char[] DIGITS = {
// '0', '1', '2', '3', '4', '5', '6', '7',
// '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
// };
//
// public static String join(Object[] array, String separator) {
// if (array == null) {
// return null;
// }
// int arraySize = array.length;
// StringBuilder buffer = new StringBuilder();
//
// for (int i = 0; i < arraySize; i++) {
// if (i > 0) {
// buffer.append(separator);
// }
// if (array[i] != null) {
// buffer.append(array[i]);
// }
// }
// return buffer.toString();
// }
//
// public static String md5Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("MD5", data);
//
// return toHexString(bytes);
// }
//
// public static String sha1Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("SHA1", data);
//
// return toHexString(bytes);
// }
//
// private static String toHexString(byte[] bytes) {
// int l = bytes.length;
//
// char[] out = new char[l << 1];
//
// for (int i = 0, j = 0; i < l; i++) {
// out[j++] = DIGITS[(0xF0 & bytes[i]) >>> 4];
// out[j++] = DIGITS[0x0F & bytes[i]];
// }
//
// return new String(out);
// }
//
// private static byte[] digest(String algorithm, String data) {
// MessageDigest digest;
// try {
// digest = MessageDigest.getInstance(algorithm);
// } catch (NoSuchAlgorithmException e) {
// throw new RuntimeException(e);
// }
//
// return digest.digest(data.getBytes());
// }
// }
| import com.mc.hibernate.memcached.utils.StringUtils; | /* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached.keystrategy;
public class Sha1KeyStrategy extends DigestKeyStrategy {
protected String digest(String key) { | // Path: src/main/java/com/mc/hibernate/memcached/utils/StringUtils.java
// public class StringUtils {
//
// private static final char[] DIGITS = {
// '0', '1', '2', '3', '4', '5', '6', '7',
// '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
// };
//
// public static String join(Object[] array, String separator) {
// if (array == null) {
// return null;
// }
// int arraySize = array.length;
// StringBuilder buffer = new StringBuilder();
//
// for (int i = 0; i < arraySize; i++) {
// if (i > 0) {
// buffer.append(separator);
// }
// if (array[i] != null) {
// buffer.append(array[i]);
// }
// }
// return buffer.toString();
// }
//
// public static String md5Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("MD5", data);
//
// return toHexString(bytes);
// }
//
// public static String sha1Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("SHA1", data);
//
// return toHexString(bytes);
// }
//
// private static String toHexString(byte[] bytes) {
// int l = bytes.length;
//
// char[] out = new char[l << 1];
//
// for (int i = 0, j = 0; i < l; i++) {
// out[j++] = DIGITS[(0xF0 & bytes[i]) >>> 4];
// out[j++] = DIGITS[0x0F & bytes[i]];
// }
//
// return new String(out);
// }
//
// private static byte[] digest(String algorithm, String data) {
// MessageDigest digest;
// try {
// digest = MessageDigest.getInstance(algorithm);
// } catch (NoSuchAlgorithmException e) {
// throw new RuntimeException(e);
// }
//
// return digest.digest(data.getBytes());
// }
// }
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Sha1KeyStrategy.java
import com.mc.hibernate.memcached.utils.StringUtils;
/* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached.keystrategy;
public class Sha1KeyStrategy extends DigestKeyStrategy {
protected String digest(String key) { | return StringUtils.sha1Hex(key); |
mihaicostin/hibernate-l2-memcached | src/main/java/com/mc/hibernate/memcached/keystrategy/Md5KeyStrategy.java | // Path: src/main/java/com/mc/hibernate/memcached/utils/StringUtils.java
// public class StringUtils {
//
// private static final char[] DIGITS = {
// '0', '1', '2', '3', '4', '5', '6', '7',
// '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
// };
//
// public static String join(Object[] array, String separator) {
// if (array == null) {
// return null;
// }
// int arraySize = array.length;
// StringBuilder buffer = new StringBuilder();
//
// for (int i = 0; i < arraySize; i++) {
// if (i > 0) {
// buffer.append(separator);
// }
// if (array[i] != null) {
// buffer.append(array[i]);
// }
// }
// return buffer.toString();
// }
//
// public static String md5Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("MD5", data);
//
// return toHexString(bytes);
// }
//
// public static String sha1Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("SHA1", data);
//
// return toHexString(bytes);
// }
//
// private static String toHexString(byte[] bytes) {
// int l = bytes.length;
//
// char[] out = new char[l << 1];
//
// for (int i = 0, j = 0; i < l; i++) {
// out[j++] = DIGITS[(0xF0 & bytes[i]) >>> 4];
// out[j++] = DIGITS[0x0F & bytes[i]];
// }
//
// return new String(out);
// }
//
// private static byte[] digest(String algorithm, String data) {
// MessageDigest digest;
// try {
// digest = MessageDigest.getInstance(algorithm);
// } catch (NoSuchAlgorithmException e) {
// throw new RuntimeException(e);
// }
//
// return digest.digest(data.getBytes());
// }
// }
| import com.mc.hibernate.memcached.utils.StringUtils; | /* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached.keystrategy;
public class Md5KeyStrategy extends DigestKeyStrategy {
protected String digest(String key) { | // Path: src/main/java/com/mc/hibernate/memcached/utils/StringUtils.java
// public class StringUtils {
//
// private static final char[] DIGITS = {
// '0', '1', '2', '3', '4', '5', '6', '7',
// '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
// };
//
// public static String join(Object[] array, String separator) {
// if (array == null) {
// return null;
// }
// int arraySize = array.length;
// StringBuilder buffer = new StringBuilder();
//
// for (int i = 0; i < arraySize; i++) {
// if (i > 0) {
// buffer.append(separator);
// }
// if (array[i] != null) {
// buffer.append(array[i]);
// }
// }
// return buffer.toString();
// }
//
// public static String md5Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("MD5", data);
//
// return toHexString(bytes);
// }
//
// public static String sha1Hex(String data) {
// if (data == null) {
// throw new IllegalArgumentException("data must not be null");
// }
//
// byte[] bytes = digest("SHA1", data);
//
// return toHexString(bytes);
// }
//
// private static String toHexString(byte[] bytes) {
// int l = bytes.length;
//
// char[] out = new char[l << 1];
//
// for (int i = 0, j = 0; i < l; i++) {
// out[j++] = DIGITS[(0xF0 & bytes[i]) >>> 4];
// out[j++] = DIGITS[0x0F & bytes[i]];
// }
//
// return new String(out);
// }
//
// private static byte[] digest(String algorithm, String data) {
// MessageDigest digest;
// try {
// digest = MessageDigest.getInstance(algorithm);
// } catch (NoSuchAlgorithmException e) {
// throw new RuntimeException(e);
// }
//
// return digest.digest(data.getBytes());
// }
// }
// Path: src/main/java/com/mc/hibernate/memcached/keystrategy/Md5KeyStrategy.java
import com.mc.hibernate.memcached.utils.StringUtils;
/* Copyright 2015, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mc.hibernate.memcached.keystrategy;
public class Md5KeyStrategy extends DigestKeyStrategy {
protected String digest(String key) { | return StringUtils.md5Hex(key); |
mihaicostin/hibernate-l2-memcached | src/test/java/com/mc/hibernate/memcached/LoggingMemcacheExceptionHandlerTest.java | // Path: src/test/java/com/mc/hibernate/memcached/mock/MockAppender.java
// public class MockAppender implements Appender {
//
// private String expectedMessage;
// private Exception expectedError;
// private boolean appenderCalled = false;
//
// public MockAppender(String expectedMessage, Exception expectedError) {
// this.expectedMessage = expectedMessage;
// this.expectedError = expectedError;
// }
//
// public void addFilter(Filter newFilter) {
// throw new UnsupportedOperationException();
// }
//
// public Filter getFilter() {
// throw new UnsupportedOperationException();
// }
//
// public void clearFilters() {
// throw new UnsupportedOperationException();
// }
//
// public void close() {
// }
//
// public void doAppend(LoggingEvent event) {
// Assert.assertEquals(expectedMessage, event.getMessage());
// Assert.assertEquals(expectedError, event.getThrowableInformation().getThrowable());
// appenderCalled = true;
// }
//
// public String getName() {
// throw new UnsupportedOperationException();
// }
//
// public void setErrorHandler(ErrorHandler errorHandler) {
// throw new UnsupportedOperationException();
// }
//
// public ErrorHandler getErrorHandler() {
// throw new UnsupportedOperationException();
// }
//
// public void setLayout(Layout layout) {
// throw new UnsupportedOperationException();
// }
//
// public Layout getLayout() {
// throw new UnsupportedOperationException();
// }
//
// public void setName(String name) {
// throw new UnsupportedOperationException();
// }
//
// public boolean requiresLayout() {
// throw new UnsupportedOperationException();
// }
//
// public boolean isAppenderCalled() {
// return appenderCalled;
// }
// }
| import com.mc.hibernate.memcached.mock.MockAppender;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue; | package com.mc.hibernate.memcached;
public class LoggingMemcacheExceptionHandlerTest extends BaseTest {
private LoggingMemcacheExceptionHandler handler = new LoggingMemcacheExceptionHandler();
private Logger logger = Logger.getLogger(LoggingMemcacheExceptionHandler.class);
@Before
public void setUp() {
logger.removeAllAppenders();
}
@Test
public void testDelete() {
Exception exception = new Exception("blah"); | // Path: src/test/java/com/mc/hibernate/memcached/mock/MockAppender.java
// public class MockAppender implements Appender {
//
// private String expectedMessage;
// private Exception expectedError;
// private boolean appenderCalled = false;
//
// public MockAppender(String expectedMessage, Exception expectedError) {
// this.expectedMessage = expectedMessage;
// this.expectedError = expectedError;
// }
//
// public void addFilter(Filter newFilter) {
// throw new UnsupportedOperationException();
// }
//
// public Filter getFilter() {
// throw new UnsupportedOperationException();
// }
//
// public void clearFilters() {
// throw new UnsupportedOperationException();
// }
//
// public void close() {
// }
//
// public void doAppend(LoggingEvent event) {
// Assert.assertEquals(expectedMessage, event.getMessage());
// Assert.assertEquals(expectedError, event.getThrowableInformation().getThrowable());
// appenderCalled = true;
// }
//
// public String getName() {
// throw new UnsupportedOperationException();
// }
//
// public void setErrorHandler(ErrorHandler errorHandler) {
// throw new UnsupportedOperationException();
// }
//
// public ErrorHandler getErrorHandler() {
// throw new UnsupportedOperationException();
// }
//
// public void setLayout(Layout layout) {
// throw new UnsupportedOperationException();
// }
//
// public Layout getLayout() {
// throw new UnsupportedOperationException();
// }
//
// public void setName(String name) {
// throw new UnsupportedOperationException();
// }
//
// public boolean requiresLayout() {
// throw new UnsupportedOperationException();
// }
//
// public boolean isAppenderCalled() {
// return appenderCalled;
// }
// }
// Path: src/test/java/com/mc/hibernate/memcached/LoggingMemcacheExceptionHandlerTest.java
import com.mc.hibernate.memcached.mock.MockAppender;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
package com.mc.hibernate.memcached;
public class LoggingMemcacheExceptionHandlerTest extends BaseTest {
private LoggingMemcacheExceptionHandler handler = new LoggingMemcacheExceptionHandler();
private Logger logger = Logger.getLogger(LoggingMemcacheExceptionHandler.class);
@Before
public void setUp() {
logger.removeAllAppenders();
}
@Test
public void testDelete() {
Exception exception = new Exception("blah"); | MockAppender appender = new MockAppender("Cache 'delete' failed for key [blah]", exception); |
xda/XDA-One | android/src/main/java/com/xda/one/api/model/response/ResponseMention.java | // Path: android/src/main/java/com/xda/one/api/model/interfaces/Mention.java
// public interface Mention extends Parcelable {
//
// public String getPageText();
//
// public String getDateLine();
//
// public String getPostId();
//
// public String getType();
//
// String getUserId();
//
// public String getUserName();
//
// public String getMentionedUserId();
//
// public String getMentionedUsername();
//
// public String getMentionedUserGroupId();
//
// public String getMentionedInfractionGroupId();
//
// public UnifiedThread getThread();
//
// String getAvatarUrl();
// }
//
// Path: android/src/main/java/com/xda/one/api/model/interfaces/UnifiedThread.java
// public interface UnifiedThread extends Parcelable {
//
// public String getThreadId();
//
// public boolean isAttach();
//
// public boolean hasAttachment();
//
// public int getViews();
//
// public long getLastPost();
//
// public String getTitle();
//
// public String getFirstPostContent();
//
// public String getPostUsername();
//
// public boolean isSticky();
//
// public int getTotalPosts();
//
// public int getLastPostId();
//
// public String getLastPoster();
//
// public int getFirstPostId();
//
// public String getThreadSlug();
//
// String getForumTitle();
//
// public int getForumId();
//
// public int getReplyCount();
//
// public boolean isSubscribed();
//
// public String getAvatarUrl();
//
// public boolean isUnread();
//
// boolean isOpen();
//
// public String getWebUri();
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.xda.one.api.model.interfaces.Mention;
import com.xda.one.api.model.interfaces.UnifiedThread;
import android.os.Parcel; |
@JsonProperty("mentionedusername")
private String mMentionedUsername;
@JsonProperty("mentionedusergroupid")
private String mMentionedUserGroupId;
@JsonProperty("mentionedinfractiongroupid")
private String mMentionedInfractionGroupId;
@JsonProperty("thread")
private ResponseUnifiedThread mThread;
public ResponseMention() {
mResponseAvatar = new ResponseAvatar();
}
public ResponseMention(Parcel in) {
mResponseAvatar = new ResponseAvatar(in);
mPageText = in.readString();
mDateLine = in.readString();
mPostId = in.readString();
mType = in.readString();
mUserId = in.readString();
mUserName = in.readString();
mMentionedUserId = in.readString();
mMentionedUsername = in.readString();
mMentionedUserGroupId = in.readString();
mMentionedInfractionGroupId = in.readString(); | // Path: android/src/main/java/com/xda/one/api/model/interfaces/Mention.java
// public interface Mention extends Parcelable {
//
// public String getPageText();
//
// public String getDateLine();
//
// public String getPostId();
//
// public String getType();
//
// String getUserId();
//
// public String getUserName();
//
// public String getMentionedUserId();
//
// public String getMentionedUsername();
//
// public String getMentionedUserGroupId();
//
// public String getMentionedInfractionGroupId();
//
// public UnifiedThread getThread();
//
// String getAvatarUrl();
// }
//
// Path: android/src/main/java/com/xda/one/api/model/interfaces/UnifiedThread.java
// public interface UnifiedThread extends Parcelable {
//
// public String getThreadId();
//
// public boolean isAttach();
//
// public boolean hasAttachment();
//
// public int getViews();
//
// public long getLastPost();
//
// public String getTitle();
//
// public String getFirstPostContent();
//
// public String getPostUsername();
//
// public boolean isSticky();
//
// public int getTotalPosts();
//
// public int getLastPostId();
//
// public String getLastPoster();
//
// public int getFirstPostId();
//
// public String getThreadSlug();
//
// String getForumTitle();
//
// public int getForumId();
//
// public int getReplyCount();
//
// public boolean isSubscribed();
//
// public String getAvatarUrl();
//
// public boolean isUnread();
//
// boolean isOpen();
//
// public String getWebUri();
// }
// Path: android/src/main/java/com/xda/one/api/model/response/ResponseMention.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.xda.one.api.model.interfaces.Mention;
import com.xda.one.api.model.interfaces.UnifiedThread;
import android.os.Parcel;
@JsonProperty("mentionedusername")
private String mMentionedUsername;
@JsonProperty("mentionedusergroupid")
private String mMentionedUserGroupId;
@JsonProperty("mentionedinfractiongroupid")
private String mMentionedInfractionGroupId;
@JsonProperty("thread")
private ResponseUnifiedThread mThread;
public ResponseMention() {
mResponseAvatar = new ResponseAvatar();
}
public ResponseMention(Parcel in) {
mResponseAvatar = new ResponseAvatar(in);
mPageText = in.readString();
mDateLine = in.readString();
mPostId = in.readString();
mType = in.readString();
mUserId = in.readString();
mUserName = in.readString();
mMentionedUserId = in.readString();
mMentionedUsername = in.readString();
mMentionedUserGroupId = in.readString();
mMentionedInfractionGroupId = in.readString(); | mThread = in.readParcelable(UnifiedThread.class.getClassLoader()); |
xda/XDA-One | android/src/main/java/com/xda/one/api/inteface/UserClient.java | // Path: android/src/main/java/com/xda/one/api/misc/Consumer.java
// public interface Consumer<T> {
//
// public void run(T data);
// }
//
// Path: android/src/main/java/com/xda/one/api/misc/Result.java
// public class Result {
//
// private static final String ERROR = "error";
//
// private static final String MESSAGE = "message";
//
// private boolean mSuccess;
//
// private String mMessage;
//
// public Result(final boolean success) {
// mSuccess = success;
// }
//
// public Result(final String message) {
// mMessage = message;
// }
//
// public static Result parseResultFromResponse(final Response response) {
// InputStream inputStream = null;
// try {
// inputStream = response.getBody().in();
// final String output = IOUtils.toString(inputStream);
// return Result.parseResultFromString(output);
// } catch (IOException | NullPointerException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static Result parseResultFromString(final String line) {
// if (line == null) {
// return null;
// }
//
// final Result result;
// try {
// final JsonNode error = OBJECT_MAPPER.readTree(line).get(ERROR);
//
// if (error == null) {
// result = new Result(true);
// } else {
// result = new Result(error.get(MESSAGE).asText());
// }
// return result;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean isSuccess(Result result) {
// return result != null && result.isSuccess();
// }
//
// public boolean isSuccess() {
// return mSuccess;
// }
//
// public String getMessage() {
// return mMessage;
// }
// }
//
// Path: android/src/main/java/com/xda/one/api/model/response/ResponseUserProfile.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class ResponseUserProfile {
//
// private final ResponseAvatar mResponseAvatar = new ResponseAvatar();
//
// @JsonProperty("userid")
// private String mUserId;
//
// @JsonProperty("signature")
// private String mSignature;
//
// @JsonProperty("username")
// private String mUserName;
//
// @JsonProperty("usertitle")
// private String mUserTitle;
//
// @JsonProperty("posts")
// private int mPosts;
//
// @JsonProperty("post_thanks_thanked_posts")
// private int mThankedPosts;
//
// @JsonProperty("post_thanks_thanked_times")
// private int mThankedTimes;
//
// @JsonProperty("devices")
// private List<ResponseUserProfileDevice> mDevices;
//
// @JsonProperty("email")
// private String mEmail;
//
// @JsonProperty("notifications")
// private ResponseUserProfileNotificationContainer mNotifications;
//
// private CharSequence mParsedSignature;
//
// public CharSequence getParsedSignature() {
// return mParsedSignature;
// }
//
// public void setParsedSignature(final CharSequence parsedSignature) {
// mParsedSignature = parsedSignature;
// }
//
// public String getUserId() {
// return mUserId;
// }
//
// public String getSignature() {
// return mSignature;
// }
//
// public String getUserName() {
// return mUserName;
// }
//
// public String getUserTitle() {
// return mUserTitle;
// }
//
// public int getPosts() {
// return mPosts;
// }
//
// public int getThankedPosts() {
// return mThankedPosts;
// }
//
// public int getThankedTimes() {
// return mThankedTimes;
// }
//
// public List<ResponseUserProfileDevice> getDevices() {
// return mDevices;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public ResponseUserProfileNotificationContainer getNotifications() {
// return mNotifications;
// }
//
// // Delegate methods
// public String getAvatarUrl() {
// return mResponseAvatar.getAvatarUrl();
// }
//
// @JsonProperty(value = "avatar_url")
// public void setAvatarUrl(final String avatarUrl) {
// mResponseAvatar.setAvatarUrl(avatarUrl);
// }
// }
| import com.xda.one.api.misc.Consumer;
import com.xda.one.api.misc.EventBus;
import com.xda.one.api.misc.Result;
import com.xda.one.api.model.interfaces.container.MentionContainer;
import com.xda.one.api.model.interfaces.container.QuoteContainer;
import com.xda.one.api.model.response.ResponseUserProfile;
import retrofit.client.Response; | package com.xda.one.api.inteface;
public interface UserClient {
public EventBus getBus();
public void login(final String username, final String password);
void register(final String email, final String username, final String password, | // Path: android/src/main/java/com/xda/one/api/misc/Consumer.java
// public interface Consumer<T> {
//
// public void run(T data);
// }
//
// Path: android/src/main/java/com/xda/one/api/misc/Result.java
// public class Result {
//
// private static final String ERROR = "error";
//
// private static final String MESSAGE = "message";
//
// private boolean mSuccess;
//
// private String mMessage;
//
// public Result(final boolean success) {
// mSuccess = success;
// }
//
// public Result(final String message) {
// mMessage = message;
// }
//
// public static Result parseResultFromResponse(final Response response) {
// InputStream inputStream = null;
// try {
// inputStream = response.getBody().in();
// final String output = IOUtils.toString(inputStream);
// return Result.parseResultFromString(output);
// } catch (IOException | NullPointerException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static Result parseResultFromString(final String line) {
// if (line == null) {
// return null;
// }
//
// final Result result;
// try {
// final JsonNode error = OBJECT_MAPPER.readTree(line).get(ERROR);
//
// if (error == null) {
// result = new Result(true);
// } else {
// result = new Result(error.get(MESSAGE).asText());
// }
// return result;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean isSuccess(Result result) {
// return result != null && result.isSuccess();
// }
//
// public boolean isSuccess() {
// return mSuccess;
// }
//
// public String getMessage() {
// return mMessage;
// }
// }
//
// Path: android/src/main/java/com/xda/one/api/model/response/ResponseUserProfile.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class ResponseUserProfile {
//
// private final ResponseAvatar mResponseAvatar = new ResponseAvatar();
//
// @JsonProperty("userid")
// private String mUserId;
//
// @JsonProperty("signature")
// private String mSignature;
//
// @JsonProperty("username")
// private String mUserName;
//
// @JsonProperty("usertitle")
// private String mUserTitle;
//
// @JsonProperty("posts")
// private int mPosts;
//
// @JsonProperty("post_thanks_thanked_posts")
// private int mThankedPosts;
//
// @JsonProperty("post_thanks_thanked_times")
// private int mThankedTimes;
//
// @JsonProperty("devices")
// private List<ResponseUserProfileDevice> mDevices;
//
// @JsonProperty("email")
// private String mEmail;
//
// @JsonProperty("notifications")
// private ResponseUserProfileNotificationContainer mNotifications;
//
// private CharSequence mParsedSignature;
//
// public CharSequence getParsedSignature() {
// return mParsedSignature;
// }
//
// public void setParsedSignature(final CharSequence parsedSignature) {
// mParsedSignature = parsedSignature;
// }
//
// public String getUserId() {
// return mUserId;
// }
//
// public String getSignature() {
// return mSignature;
// }
//
// public String getUserName() {
// return mUserName;
// }
//
// public String getUserTitle() {
// return mUserTitle;
// }
//
// public int getPosts() {
// return mPosts;
// }
//
// public int getThankedPosts() {
// return mThankedPosts;
// }
//
// public int getThankedTimes() {
// return mThankedTimes;
// }
//
// public List<ResponseUserProfileDevice> getDevices() {
// return mDevices;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public ResponseUserProfileNotificationContainer getNotifications() {
// return mNotifications;
// }
//
// // Delegate methods
// public String getAvatarUrl() {
// return mResponseAvatar.getAvatarUrl();
// }
//
// @JsonProperty(value = "avatar_url")
// public void setAvatarUrl(final String avatarUrl) {
// mResponseAvatar.setAvatarUrl(avatarUrl);
// }
// }
// Path: android/src/main/java/com/xda/one/api/inteface/UserClient.java
import com.xda.one.api.misc.Consumer;
import com.xda.one.api.misc.EventBus;
import com.xda.one.api.misc.Result;
import com.xda.one.api.model.interfaces.container.MentionContainer;
import com.xda.one.api.model.interfaces.container.QuoteContainer;
import com.xda.one.api.model.response.ResponseUserProfile;
import retrofit.client.Response;
package com.xda.one.api.inteface;
public interface UserClient {
public EventBus getBus();
public void login(final String username, final String password);
void register(final String email, final String username, final String password, | final String challenge, final String response, final Consumer<Response> success, |
xda/XDA-One | android/src/main/java/com/xda/one/api/inteface/UserClient.java | // Path: android/src/main/java/com/xda/one/api/misc/Consumer.java
// public interface Consumer<T> {
//
// public void run(T data);
// }
//
// Path: android/src/main/java/com/xda/one/api/misc/Result.java
// public class Result {
//
// private static final String ERROR = "error";
//
// private static final String MESSAGE = "message";
//
// private boolean mSuccess;
//
// private String mMessage;
//
// public Result(final boolean success) {
// mSuccess = success;
// }
//
// public Result(final String message) {
// mMessage = message;
// }
//
// public static Result parseResultFromResponse(final Response response) {
// InputStream inputStream = null;
// try {
// inputStream = response.getBody().in();
// final String output = IOUtils.toString(inputStream);
// return Result.parseResultFromString(output);
// } catch (IOException | NullPointerException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static Result parseResultFromString(final String line) {
// if (line == null) {
// return null;
// }
//
// final Result result;
// try {
// final JsonNode error = OBJECT_MAPPER.readTree(line).get(ERROR);
//
// if (error == null) {
// result = new Result(true);
// } else {
// result = new Result(error.get(MESSAGE).asText());
// }
// return result;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean isSuccess(Result result) {
// return result != null && result.isSuccess();
// }
//
// public boolean isSuccess() {
// return mSuccess;
// }
//
// public String getMessage() {
// return mMessage;
// }
// }
//
// Path: android/src/main/java/com/xda/one/api/model/response/ResponseUserProfile.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class ResponseUserProfile {
//
// private final ResponseAvatar mResponseAvatar = new ResponseAvatar();
//
// @JsonProperty("userid")
// private String mUserId;
//
// @JsonProperty("signature")
// private String mSignature;
//
// @JsonProperty("username")
// private String mUserName;
//
// @JsonProperty("usertitle")
// private String mUserTitle;
//
// @JsonProperty("posts")
// private int mPosts;
//
// @JsonProperty("post_thanks_thanked_posts")
// private int mThankedPosts;
//
// @JsonProperty("post_thanks_thanked_times")
// private int mThankedTimes;
//
// @JsonProperty("devices")
// private List<ResponseUserProfileDevice> mDevices;
//
// @JsonProperty("email")
// private String mEmail;
//
// @JsonProperty("notifications")
// private ResponseUserProfileNotificationContainer mNotifications;
//
// private CharSequence mParsedSignature;
//
// public CharSequence getParsedSignature() {
// return mParsedSignature;
// }
//
// public void setParsedSignature(final CharSequence parsedSignature) {
// mParsedSignature = parsedSignature;
// }
//
// public String getUserId() {
// return mUserId;
// }
//
// public String getSignature() {
// return mSignature;
// }
//
// public String getUserName() {
// return mUserName;
// }
//
// public String getUserTitle() {
// return mUserTitle;
// }
//
// public int getPosts() {
// return mPosts;
// }
//
// public int getThankedPosts() {
// return mThankedPosts;
// }
//
// public int getThankedTimes() {
// return mThankedTimes;
// }
//
// public List<ResponseUserProfileDevice> getDevices() {
// return mDevices;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public ResponseUserProfileNotificationContainer getNotifications() {
// return mNotifications;
// }
//
// // Delegate methods
// public String getAvatarUrl() {
// return mResponseAvatar.getAvatarUrl();
// }
//
// @JsonProperty(value = "avatar_url")
// public void setAvatarUrl(final String avatarUrl) {
// mResponseAvatar.setAvatarUrl(avatarUrl);
// }
// }
| import com.xda.one.api.misc.Consumer;
import com.xda.one.api.misc.EventBus;
import com.xda.one.api.misc.Result;
import com.xda.one.api.model.interfaces.container.MentionContainer;
import com.xda.one.api.model.interfaces.container.QuoteContainer;
import com.xda.one.api.model.response.ResponseUserProfile;
import retrofit.client.Response; | package com.xda.one.api.inteface;
public interface UserClient {
public EventBus getBus();
public void login(final String username, final String password);
void register(final String email, final String username, final String password,
final String challenge, final String response, final Consumer<Response> success, | // Path: android/src/main/java/com/xda/one/api/misc/Consumer.java
// public interface Consumer<T> {
//
// public void run(T data);
// }
//
// Path: android/src/main/java/com/xda/one/api/misc/Result.java
// public class Result {
//
// private static final String ERROR = "error";
//
// private static final String MESSAGE = "message";
//
// private boolean mSuccess;
//
// private String mMessage;
//
// public Result(final boolean success) {
// mSuccess = success;
// }
//
// public Result(final String message) {
// mMessage = message;
// }
//
// public static Result parseResultFromResponse(final Response response) {
// InputStream inputStream = null;
// try {
// inputStream = response.getBody().in();
// final String output = IOUtils.toString(inputStream);
// return Result.parseResultFromString(output);
// } catch (IOException | NullPointerException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static Result parseResultFromString(final String line) {
// if (line == null) {
// return null;
// }
//
// final Result result;
// try {
// final JsonNode error = OBJECT_MAPPER.readTree(line).get(ERROR);
//
// if (error == null) {
// result = new Result(true);
// } else {
// result = new Result(error.get(MESSAGE).asText());
// }
// return result;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean isSuccess(Result result) {
// return result != null && result.isSuccess();
// }
//
// public boolean isSuccess() {
// return mSuccess;
// }
//
// public String getMessage() {
// return mMessage;
// }
// }
//
// Path: android/src/main/java/com/xda/one/api/model/response/ResponseUserProfile.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class ResponseUserProfile {
//
// private final ResponseAvatar mResponseAvatar = new ResponseAvatar();
//
// @JsonProperty("userid")
// private String mUserId;
//
// @JsonProperty("signature")
// private String mSignature;
//
// @JsonProperty("username")
// private String mUserName;
//
// @JsonProperty("usertitle")
// private String mUserTitle;
//
// @JsonProperty("posts")
// private int mPosts;
//
// @JsonProperty("post_thanks_thanked_posts")
// private int mThankedPosts;
//
// @JsonProperty("post_thanks_thanked_times")
// private int mThankedTimes;
//
// @JsonProperty("devices")
// private List<ResponseUserProfileDevice> mDevices;
//
// @JsonProperty("email")
// private String mEmail;
//
// @JsonProperty("notifications")
// private ResponseUserProfileNotificationContainer mNotifications;
//
// private CharSequence mParsedSignature;
//
// public CharSequence getParsedSignature() {
// return mParsedSignature;
// }
//
// public void setParsedSignature(final CharSequence parsedSignature) {
// mParsedSignature = parsedSignature;
// }
//
// public String getUserId() {
// return mUserId;
// }
//
// public String getSignature() {
// return mSignature;
// }
//
// public String getUserName() {
// return mUserName;
// }
//
// public String getUserTitle() {
// return mUserTitle;
// }
//
// public int getPosts() {
// return mPosts;
// }
//
// public int getThankedPosts() {
// return mThankedPosts;
// }
//
// public int getThankedTimes() {
// return mThankedTimes;
// }
//
// public List<ResponseUserProfileDevice> getDevices() {
// return mDevices;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public ResponseUserProfileNotificationContainer getNotifications() {
// return mNotifications;
// }
//
// // Delegate methods
// public String getAvatarUrl() {
// return mResponseAvatar.getAvatarUrl();
// }
//
// @JsonProperty(value = "avatar_url")
// public void setAvatarUrl(final String avatarUrl) {
// mResponseAvatar.setAvatarUrl(avatarUrl);
// }
// }
// Path: android/src/main/java/com/xda/one/api/inteface/UserClient.java
import com.xda.one.api.misc.Consumer;
import com.xda.one.api.misc.EventBus;
import com.xda.one.api.misc.Result;
import com.xda.one.api.model.interfaces.container.MentionContainer;
import com.xda.one.api.model.interfaces.container.QuoteContainer;
import com.xda.one.api.model.response.ResponseUserProfile;
import retrofit.client.Response;
package com.xda.one.api.inteface;
public interface UserClient {
public EventBus getBus();
public void login(final String username, final String password);
void register(final String email, final String username, final String password,
final String challenge, final String response, final Consumer<Response> success, | final Consumer<Result> failure); |
xda/XDA-One | android/src/main/java/com/xda/one/api/inteface/UserClient.java | // Path: android/src/main/java/com/xda/one/api/misc/Consumer.java
// public interface Consumer<T> {
//
// public void run(T data);
// }
//
// Path: android/src/main/java/com/xda/one/api/misc/Result.java
// public class Result {
//
// private static final String ERROR = "error";
//
// private static final String MESSAGE = "message";
//
// private boolean mSuccess;
//
// private String mMessage;
//
// public Result(final boolean success) {
// mSuccess = success;
// }
//
// public Result(final String message) {
// mMessage = message;
// }
//
// public static Result parseResultFromResponse(final Response response) {
// InputStream inputStream = null;
// try {
// inputStream = response.getBody().in();
// final String output = IOUtils.toString(inputStream);
// return Result.parseResultFromString(output);
// } catch (IOException | NullPointerException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static Result parseResultFromString(final String line) {
// if (line == null) {
// return null;
// }
//
// final Result result;
// try {
// final JsonNode error = OBJECT_MAPPER.readTree(line).get(ERROR);
//
// if (error == null) {
// result = new Result(true);
// } else {
// result = new Result(error.get(MESSAGE).asText());
// }
// return result;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean isSuccess(Result result) {
// return result != null && result.isSuccess();
// }
//
// public boolean isSuccess() {
// return mSuccess;
// }
//
// public String getMessage() {
// return mMessage;
// }
// }
//
// Path: android/src/main/java/com/xda/one/api/model/response/ResponseUserProfile.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class ResponseUserProfile {
//
// private final ResponseAvatar mResponseAvatar = new ResponseAvatar();
//
// @JsonProperty("userid")
// private String mUserId;
//
// @JsonProperty("signature")
// private String mSignature;
//
// @JsonProperty("username")
// private String mUserName;
//
// @JsonProperty("usertitle")
// private String mUserTitle;
//
// @JsonProperty("posts")
// private int mPosts;
//
// @JsonProperty("post_thanks_thanked_posts")
// private int mThankedPosts;
//
// @JsonProperty("post_thanks_thanked_times")
// private int mThankedTimes;
//
// @JsonProperty("devices")
// private List<ResponseUserProfileDevice> mDevices;
//
// @JsonProperty("email")
// private String mEmail;
//
// @JsonProperty("notifications")
// private ResponseUserProfileNotificationContainer mNotifications;
//
// private CharSequence mParsedSignature;
//
// public CharSequence getParsedSignature() {
// return mParsedSignature;
// }
//
// public void setParsedSignature(final CharSequence parsedSignature) {
// mParsedSignature = parsedSignature;
// }
//
// public String getUserId() {
// return mUserId;
// }
//
// public String getSignature() {
// return mSignature;
// }
//
// public String getUserName() {
// return mUserName;
// }
//
// public String getUserTitle() {
// return mUserTitle;
// }
//
// public int getPosts() {
// return mPosts;
// }
//
// public int getThankedPosts() {
// return mThankedPosts;
// }
//
// public int getThankedTimes() {
// return mThankedTimes;
// }
//
// public List<ResponseUserProfileDevice> getDevices() {
// return mDevices;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public ResponseUserProfileNotificationContainer getNotifications() {
// return mNotifications;
// }
//
// // Delegate methods
// public String getAvatarUrl() {
// return mResponseAvatar.getAvatarUrl();
// }
//
// @JsonProperty(value = "avatar_url")
// public void setAvatarUrl(final String avatarUrl) {
// mResponseAvatar.setAvatarUrl(avatarUrl);
// }
// }
| import com.xda.one.api.misc.Consumer;
import com.xda.one.api.misc.EventBus;
import com.xda.one.api.misc.Result;
import com.xda.one.api.model.interfaces.container.MentionContainer;
import com.xda.one.api.model.interfaces.container.QuoteContainer;
import com.xda.one.api.model.response.ResponseUserProfile;
import retrofit.client.Response; | package com.xda.one.api.inteface;
public interface UserClient {
public EventBus getBus();
public void login(final String username, final String password);
void register(final String email, final String username, final String password,
final String challenge, final String response, final Consumer<Response> success,
final Consumer<Result> failure);
public MentionContainer getMentions(final int page);
public QuoteContainer getQuotes(final int page);
| // Path: android/src/main/java/com/xda/one/api/misc/Consumer.java
// public interface Consumer<T> {
//
// public void run(T data);
// }
//
// Path: android/src/main/java/com/xda/one/api/misc/Result.java
// public class Result {
//
// private static final String ERROR = "error";
//
// private static final String MESSAGE = "message";
//
// private boolean mSuccess;
//
// private String mMessage;
//
// public Result(final boolean success) {
// mSuccess = success;
// }
//
// public Result(final String message) {
// mMessage = message;
// }
//
// public static Result parseResultFromResponse(final Response response) {
// InputStream inputStream = null;
// try {
// inputStream = response.getBody().in();
// final String output = IOUtils.toString(inputStream);
// return Result.parseResultFromString(output);
// } catch (IOException | NullPointerException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static Result parseResultFromString(final String line) {
// if (line == null) {
// return null;
// }
//
// final Result result;
// try {
// final JsonNode error = OBJECT_MAPPER.readTree(line).get(ERROR);
//
// if (error == null) {
// result = new Result(true);
// } else {
// result = new Result(error.get(MESSAGE).asText());
// }
// return result;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean isSuccess(Result result) {
// return result != null && result.isSuccess();
// }
//
// public boolean isSuccess() {
// return mSuccess;
// }
//
// public String getMessage() {
// return mMessage;
// }
// }
//
// Path: android/src/main/java/com/xda/one/api/model/response/ResponseUserProfile.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class ResponseUserProfile {
//
// private final ResponseAvatar mResponseAvatar = new ResponseAvatar();
//
// @JsonProperty("userid")
// private String mUserId;
//
// @JsonProperty("signature")
// private String mSignature;
//
// @JsonProperty("username")
// private String mUserName;
//
// @JsonProperty("usertitle")
// private String mUserTitle;
//
// @JsonProperty("posts")
// private int mPosts;
//
// @JsonProperty("post_thanks_thanked_posts")
// private int mThankedPosts;
//
// @JsonProperty("post_thanks_thanked_times")
// private int mThankedTimes;
//
// @JsonProperty("devices")
// private List<ResponseUserProfileDevice> mDevices;
//
// @JsonProperty("email")
// private String mEmail;
//
// @JsonProperty("notifications")
// private ResponseUserProfileNotificationContainer mNotifications;
//
// private CharSequence mParsedSignature;
//
// public CharSequence getParsedSignature() {
// return mParsedSignature;
// }
//
// public void setParsedSignature(final CharSequence parsedSignature) {
// mParsedSignature = parsedSignature;
// }
//
// public String getUserId() {
// return mUserId;
// }
//
// public String getSignature() {
// return mSignature;
// }
//
// public String getUserName() {
// return mUserName;
// }
//
// public String getUserTitle() {
// return mUserTitle;
// }
//
// public int getPosts() {
// return mPosts;
// }
//
// public int getThankedPosts() {
// return mThankedPosts;
// }
//
// public int getThankedTimes() {
// return mThankedTimes;
// }
//
// public List<ResponseUserProfileDevice> getDevices() {
// return mDevices;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public ResponseUserProfileNotificationContainer getNotifications() {
// return mNotifications;
// }
//
// // Delegate methods
// public String getAvatarUrl() {
// return mResponseAvatar.getAvatarUrl();
// }
//
// @JsonProperty(value = "avatar_url")
// public void setAvatarUrl(final String avatarUrl) {
// mResponseAvatar.setAvatarUrl(avatarUrl);
// }
// }
// Path: android/src/main/java/com/xda/one/api/inteface/UserClient.java
import com.xda.one.api.misc.Consumer;
import com.xda.one.api.misc.EventBus;
import com.xda.one.api.misc.Result;
import com.xda.one.api.model.interfaces.container.MentionContainer;
import com.xda.one.api.model.interfaces.container.QuoteContainer;
import com.xda.one.api.model.response.ResponseUserProfile;
import retrofit.client.Response;
package com.xda.one.api.inteface;
public interface UserClient {
public EventBus getBus();
public void login(final String username, final String password);
void register(final String email, final String username, final String password,
final String challenge, final String response, final Consumer<Response> success,
final Consumer<Result> failure);
public MentionContainer getMentions(final int page);
public QuoteContainer getQuotes(final int page);
| public ResponseUserProfile getUserProfile(); |
xda/XDA-One | android/src/main/java/com/xda/one/ui/MentionFragment.java | // Path: android/src/main/java/com/xda/one/ui/listener/InfiniteRecyclerLoadHelper.java
// public class InfiniteRecyclerLoadHelper extends RecyclerView.OnScrollListener
// implements RecyclerEndHelper.Callback {
//
// private final Callback mCallback;
//
// private final RecyclerEndHelper mRecyclerEndHelper;
//
// private final RecyclerView.OnScrollListener mScrollListener;
//
// // Pagination stuff
// private int mTotalPages;
//
// private int mLoadedPage = 1;
//
// private boolean mLoading = false;
//
// public InfiniteRecyclerLoadHelper(final RecyclerView recyclerView, final Callback callback,
// final int totalPages, final RecyclerView.OnScrollListener scrollListener) {
// mRecyclerEndHelper = new RecyclerEndHelper(recyclerView, this);
// mCallback = callback;
// mTotalPages = totalPages;
//
// mScrollListener = scrollListener;
// recyclerView.setOnScrollListener(this);
// }
//
// @Override
// public void onListEndReached() {
// if (mLoadedPage < mTotalPages && !mLoading) {
// mLoading = true;
// mCallback.loadMoreData(++mLoadedPage);
// }
// }
//
// /**
// * This method should be called when the loading is finished
// */
// public void onLoadFinished() {
// mLoading = false;
// }
//
// public boolean hasMoreData() {
// return mLoadedPage < mTotalPages;
// }
//
// @Override
// public void onScrollStateChanged(final RecyclerView recyclerView, final int newState) {
// if (mScrollListener != null) {
// mScrollListener.onScrollStateChanged(recyclerView, newState);
// }
// mRecyclerEndHelper.onScrollStateChanged(recyclerView, newState);
// }
//
// @Override
// public void onScrolled(final RecyclerView recyclerView, final int dx, final int dy) {
// if (mScrollListener != null) {
// mScrollListener.onScrolled(recyclerView, dx, dy);
// }
// mRecyclerEndHelper.onScrolled(recyclerView, dx, dy);
// }
//
// public void updateRecyclerView(RecyclerView recyclerView) {
// mRecyclerEndHelper.updateRecyclerView(recyclerView);
// }
//
// public boolean isLoading() {
// return mLoading;
// }
//
// public interface Callback {
//
// public void loadMoreData(final int page);
// }
// }
//
// Path: android/src/main/java/com/xda/one/util/Utils.java
// public class Utils {
//
// public static String handleRetrofitErrorQuietly(final RetrofitError error) {
// error.printStackTrace();
//
// InputStream inputStream = null;
// try {
// if (error.isNetworkError()) {
// Log.e("XDA-ONE", "Network error happened.");
// } else {
// final TypedInput body = error.getResponse().getBody();
// if (body == null) {
// Log.e("XDA-ONE", "Unable to retrieve body");
// return null;
// }
// inputStream = body.in();
//
// final String result = IOUtils.toString(inputStream);
// Log.e("XDA-ONE", result);
// return result;
// }
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static <T> int getCollectionSize(final Collection<T> collection) {
// return collection == null ? 0 : collection.size();
// }
//
// public static boolean isCollectionEmpty(final Collection collection) {
// return collection == null || collection.isEmpty();
// }
//
// public static CharSequence getRelativeDate(final Context context, final long dateline) {
// return DateUtils.getRelativeDateTimeString(context, dateline,
// DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS,
// DateUtils.FORMAT_NUMERIC_DATE);
// }
// }
| import com.xda.one.R;
import com.xda.one.api.inteface.PostClient;
import com.xda.one.api.model.response.container.ResponsePostContainer;
import com.xda.one.api.retrofit.RetrofitPostClient;
import com.xda.one.loader.MentionLoader;
import com.xda.one.model.augmented.AugmentedMention;
import com.xda.one.model.augmented.container.AugmentedMentionContainer;
import com.xda.one.ui.helper.CancellableCallbackHelper;
import com.xda.one.ui.listener.AvatarClickListener;
import com.xda.one.ui.listener.InfiniteRecyclerLoadHelper;
import com.xda.one.util.FragmentUtils;
import com.xda.one.util.UIUtils;
import com.xda.one.util.Utils;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List; |
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new MentionAdapter(getActivity(), new MentionClickListener(),
new AvatarClickListener(getActivity()));
}
@Override
public void onViewCreated(final View view, @Nullable final Bundle state) {
super.onViewCreated(view, state);
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
UIUtils.updateEmptyViewState(getView(), mRecyclerView, mAdapter.isEmpty());
reloadTheFirstPage();
}
});
mRecyclerView.setAdapter(mAdapter);
if (!mAdapter.isEmpty()) {
return;
}
if (state == null) {
loadTheFirstPage();
} else {
final List<AugmentedMention> mentions = state
.getParcelableArrayList(SAVED_ADAPTER_STATE); | // Path: android/src/main/java/com/xda/one/ui/listener/InfiniteRecyclerLoadHelper.java
// public class InfiniteRecyclerLoadHelper extends RecyclerView.OnScrollListener
// implements RecyclerEndHelper.Callback {
//
// private final Callback mCallback;
//
// private final RecyclerEndHelper mRecyclerEndHelper;
//
// private final RecyclerView.OnScrollListener mScrollListener;
//
// // Pagination stuff
// private int mTotalPages;
//
// private int mLoadedPage = 1;
//
// private boolean mLoading = false;
//
// public InfiniteRecyclerLoadHelper(final RecyclerView recyclerView, final Callback callback,
// final int totalPages, final RecyclerView.OnScrollListener scrollListener) {
// mRecyclerEndHelper = new RecyclerEndHelper(recyclerView, this);
// mCallback = callback;
// mTotalPages = totalPages;
//
// mScrollListener = scrollListener;
// recyclerView.setOnScrollListener(this);
// }
//
// @Override
// public void onListEndReached() {
// if (mLoadedPage < mTotalPages && !mLoading) {
// mLoading = true;
// mCallback.loadMoreData(++mLoadedPage);
// }
// }
//
// /**
// * This method should be called when the loading is finished
// */
// public void onLoadFinished() {
// mLoading = false;
// }
//
// public boolean hasMoreData() {
// return mLoadedPage < mTotalPages;
// }
//
// @Override
// public void onScrollStateChanged(final RecyclerView recyclerView, final int newState) {
// if (mScrollListener != null) {
// mScrollListener.onScrollStateChanged(recyclerView, newState);
// }
// mRecyclerEndHelper.onScrollStateChanged(recyclerView, newState);
// }
//
// @Override
// public void onScrolled(final RecyclerView recyclerView, final int dx, final int dy) {
// if (mScrollListener != null) {
// mScrollListener.onScrolled(recyclerView, dx, dy);
// }
// mRecyclerEndHelper.onScrolled(recyclerView, dx, dy);
// }
//
// public void updateRecyclerView(RecyclerView recyclerView) {
// mRecyclerEndHelper.updateRecyclerView(recyclerView);
// }
//
// public boolean isLoading() {
// return mLoading;
// }
//
// public interface Callback {
//
// public void loadMoreData(final int page);
// }
// }
//
// Path: android/src/main/java/com/xda/one/util/Utils.java
// public class Utils {
//
// public static String handleRetrofitErrorQuietly(final RetrofitError error) {
// error.printStackTrace();
//
// InputStream inputStream = null;
// try {
// if (error.isNetworkError()) {
// Log.e("XDA-ONE", "Network error happened.");
// } else {
// final TypedInput body = error.getResponse().getBody();
// if (body == null) {
// Log.e("XDA-ONE", "Unable to retrieve body");
// return null;
// }
// inputStream = body.in();
//
// final String result = IOUtils.toString(inputStream);
// Log.e("XDA-ONE", result);
// return result;
// }
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static <T> int getCollectionSize(final Collection<T> collection) {
// return collection == null ? 0 : collection.size();
// }
//
// public static boolean isCollectionEmpty(final Collection collection) {
// return collection == null || collection.isEmpty();
// }
//
// public static CharSequence getRelativeDate(final Context context, final long dateline) {
// return DateUtils.getRelativeDateTimeString(context, dateline,
// DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS,
// DateUtils.FORMAT_NUMERIC_DATE);
// }
// }
// Path: android/src/main/java/com/xda/one/ui/MentionFragment.java
import com.xda.one.R;
import com.xda.one.api.inteface.PostClient;
import com.xda.one.api.model.response.container.ResponsePostContainer;
import com.xda.one.api.retrofit.RetrofitPostClient;
import com.xda.one.loader.MentionLoader;
import com.xda.one.model.augmented.AugmentedMention;
import com.xda.one.model.augmented.container.AugmentedMentionContainer;
import com.xda.one.ui.helper.CancellableCallbackHelper;
import com.xda.one.ui.listener.AvatarClickListener;
import com.xda.one.ui.listener.InfiniteRecyclerLoadHelper;
import com.xda.one.util.FragmentUtils;
import com.xda.one.util.UIUtils;
import com.xda.one.util.Utils;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new MentionAdapter(getActivity(), new MentionClickListener(),
new AvatarClickListener(getActivity()));
}
@Override
public void onViewCreated(final View view, @Nullable final Bundle state) {
super.onViewCreated(view, state);
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
UIUtils.updateEmptyViewState(getView(), mRecyclerView, mAdapter.isEmpty());
reloadTheFirstPage();
}
});
mRecyclerView.setAdapter(mAdapter);
if (!mAdapter.isEmpty()) {
return;
}
if (state == null) {
loadTheFirstPage();
} else {
final List<AugmentedMention> mentions = state
.getParcelableArrayList(SAVED_ADAPTER_STATE); | if (Utils.isCollectionEmpty(mentions)) { |
xda/XDA-One | android/src/main/java/com/xda/one/ui/MentionFragment.java | // Path: android/src/main/java/com/xda/one/ui/listener/InfiniteRecyclerLoadHelper.java
// public class InfiniteRecyclerLoadHelper extends RecyclerView.OnScrollListener
// implements RecyclerEndHelper.Callback {
//
// private final Callback mCallback;
//
// private final RecyclerEndHelper mRecyclerEndHelper;
//
// private final RecyclerView.OnScrollListener mScrollListener;
//
// // Pagination stuff
// private int mTotalPages;
//
// private int mLoadedPage = 1;
//
// private boolean mLoading = false;
//
// public InfiniteRecyclerLoadHelper(final RecyclerView recyclerView, final Callback callback,
// final int totalPages, final RecyclerView.OnScrollListener scrollListener) {
// mRecyclerEndHelper = new RecyclerEndHelper(recyclerView, this);
// mCallback = callback;
// mTotalPages = totalPages;
//
// mScrollListener = scrollListener;
// recyclerView.setOnScrollListener(this);
// }
//
// @Override
// public void onListEndReached() {
// if (mLoadedPage < mTotalPages && !mLoading) {
// mLoading = true;
// mCallback.loadMoreData(++mLoadedPage);
// }
// }
//
// /**
// * This method should be called when the loading is finished
// */
// public void onLoadFinished() {
// mLoading = false;
// }
//
// public boolean hasMoreData() {
// return mLoadedPage < mTotalPages;
// }
//
// @Override
// public void onScrollStateChanged(final RecyclerView recyclerView, final int newState) {
// if (mScrollListener != null) {
// mScrollListener.onScrollStateChanged(recyclerView, newState);
// }
// mRecyclerEndHelper.onScrollStateChanged(recyclerView, newState);
// }
//
// @Override
// public void onScrolled(final RecyclerView recyclerView, final int dx, final int dy) {
// if (mScrollListener != null) {
// mScrollListener.onScrolled(recyclerView, dx, dy);
// }
// mRecyclerEndHelper.onScrolled(recyclerView, dx, dy);
// }
//
// public void updateRecyclerView(RecyclerView recyclerView) {
// mRecyclerEndHelper.updateRecyclerView(recyclerView);
// }
//
// public boolean isLoading() {
// return mLoading;
// }
//
// public interface Callback {
//
// public void loadMoreData(final int page);
// }
// }
//
// Path: android/src/main/java/com/xda/one/util/Utils.java
// public class Utils {
//
// public static String handleRetrofitErrorQuietly(final RetrofitError error) {
// error.printStackTrace();
//
// InputStream inputStream = null;
// try {
// if (error.isNetworkError()) {
// Log.e("XDA-ONE", "Network error happened.");
// } else {
// final TypedInput body = error.getResponse().getBody();
// if (body == null) {
// Log.e("XDA-ONE", "Unable to retrieve body");
// return null;
// }
// inputStream = body.in();
//
// final String result = IOUtils.toString(inputStream);
// Log.e("XDA-ONE", result);
// return result;
// }
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static <T> int getCollectionSize(final Collection<T> collection) {
// return collection == null ? 0 : collection.size();
// }
//
// public static boolean isCollectionEmpty(final Collection collection) {
// return collection == null || collection.isEmpty();
// }
//
// public static CharSequence getRelativeDate(final Context context, final long dateline) {
// return DateUtils.getRelativeDateTimeString(context, dateline,
// DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS,
// DateUtils.FORMAT_NUMERIC_DATE);
// }
// }
| import com.xda.one.R;
import com.xda.one.api.inteface.PostClient;
import com.xda.one.api.model.response.container.ResponsePostContainer;
import com.xda.one.api.retrofit.RetrofitPostClient;
import com.xda.one.loader.MentionLoader;
import com.xda.one.model.augmented.AugmentedMention;
import com.xda.one.model.augmented.container.AugmentedMentionContainer;
import com.xda.one.ui.helper.CancellableCallbackHelper;
import com.xda.one.ui.listener.AvatarClickListener;
import com.xda.one.ui.listener.InfiniteRecyclerLoadHelper;
import com.xda.one.util.FragmentUtils;
import com.xda.one.util.UIUtils;
import com.xda.one.util.Utils;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List; | mAdapter = new MentionAdapter(getActivity(), new MentionClickListener(),
new AvatarClickListener(getActivity()));
}
@Override
public void onViewCreated(final View view, @Nullable final Bundle state) {
super.onViewCreated(view, state);
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
UIUtils.updateEmptyViewState(getView(), mRecyclerView, mAdapter.isEmpty());
reloadTheFirstPage();
}
});
mRecyclerView.setAdapter(mAdapter);
if (!mAdapter.isEmpty()) {
return;
}
if (state == null) {
loadTheFirstPage();
} else {
final List<AugmentedMention> mentions = state
.getParcelableArrayList(SAVED_ADAPTER_STATE);
if (Utils.isCollectionEmpty(mentions)) {
loadTheFirstPage();
} else {
// This should give a non-zero integer
mTotalPages = state.getInt(PAGES_SAVED_STATE); | // Path: android/src/main/java/com/xda/one/ui/listener/InfiniteRecyclerLoadHelper.java
// public class InfiniteRecyclerLoadHelper extends RecyclerView.OnScrollListener
// implements RecyclerEndHelper.Callback {
//
// private final Callback mCallback;
//
// private final RecyclerEndHelper mRecyclerEndHelper;
//
// private final RecyclerView.OnScrollListener mScrollListener;
//
// // Pagination stuff
// private int mTotalPages;
//
// private int mLoadedPage = 1;
//
// private boolean mLoading = false;
//
// public InfiniteRecyclerLoadHelper(final RecyclerView recyclerView, final Callback callback,
// final int totalPages, final RecyclerView.OnScrollListener scrollListener) {
// mRecyclerEndHelper = new RecyclerEndHelper(recyclerView, this);
// mCallback = callback;
// mTotalPages = totalPages;
//
// mScrollListener = scrollListener;
// recyclerView.setOnScrollListener(this);
// }
//
// @Override
// public void onListEndReached() {
// if (mLoadedPage < mTotalPages && !mLoading) {
// mLoading = true;
// mCallback.loadMoreData(++mLoadedPage);
// }
// }
//
// /**
// * This method should be called when the loading is finished
// */
// public void onLoadFinished() {
// mLoading = false;
// }
//
// public boolean hasMoreData() {
// return mLoadedPage < mTotalPages;
// }
//
// @Override
// public void onScrollStateChanged(final RecyclerView recyclerView, final int newState) {
// if (mScrollListener != null) {
// mScrollListener.onScrollStateChanged(recyclerView, newState);
// }
// mRecyclerEndHelper.onScrollStateChanged(recyclerView, newState);
// }
//
// @Override
// public void onScrolled(final RecyclerView recyclerView, final int dx, final int dy) {
// if (mScrollListener != null) {
// mScrollListener.onScrolled(recyclerView, dx, dy);
// }
// mRecyclerEndHelper.onScrolled(recyclerView, dx, dy);
// }
//
// public void updateRecyclerView(RecyclerView recyclerView) {
// mRecyclerEndHelper.updateRecyclerView(recyclerView);
// }
//
// public boolean isLoading() {
// return mLoading;
// }
//
// public interface Callback {
//
// public void loadMoreData(final int page);
// }
// }
//
// Path: android/src/main/java/com/xda/one/util/Utils.java
// public class Utils {
//
// public static String handleRetrofitErrorQuietly(final RetrofitError error) {
// error.printStackTrace();
//
// InputStream inputStream = null;
// try {
// if (error.isNetworkError()) {
// Log.e("XDA-ONE", "Network error happened.");
// } else {
// final TypedInput body = error.getResponse().getBody();
// if (body == null) {
// Log.e("XDA-ONE", "Unable to retrieve body");
// return null;
// }
// inputStream = body.in();
//
// final String result = IOUtils.toString(inputStream);
// Log.e("XDA-ONE", result);
// return result;
// }
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static <T> int getCollectionSize(final Collection<T> collection) {
// return collection == null ? 0 : collection.size();
// }
//
// public static boolean isCollectionEmpty(final Collection collection) {
// return collection == null || collection.isEmpty();
// }
//
// public static CharSequence getRelativeDate(final Context context, final long dateline) {
// return DateUtils.getRelativeDateTimeString(context, dateline,
// DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS,
// DateUtils.FORMAT_NUMERIC_DATE);
// }
// }
// Path: android/src/main/java/com/xda/one/ui/MentionFragment.java
import com.xda.one.R;
import com.xda.one.api.inteface.PostClient;
import com.xda.one.api.model.response.container.ResponsePostContainer;
import com.xda.one.api.retrofit.RetrofitPostClient;
import com.xda.one.loader.MentionLoader;
import com.xda.one.model.augmented.AugmentedMention;
import com.xda.one.model.augmented.container.AugmentedMentionContainer;
import com.xda.one.ui.helper.CancellableCallbackHelper;
import com.xda.one.ui.listener.AvatarClickListener;
import com.xda.one.ui.listener.InfiniteRecyclerLoadHelper;
import com.xda.one.util.FragmentUtils;
import com.xda.one.util.UIUtils;
import com.xda.one.util.Utils;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
mAdapter = new MentionAdapter(getActivity(), new MentionClickListener(),
new AvatarClickListener(getActivity()));
}
@Override
public void onViewCreated(final View view, @Nullable final Bundle state) {
super.onViewCreated(view, state);
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
UIUtils.updateEmptyViewState(getView(), mRecyclerView, mAdapter.isEmpty());
reloadTheFirstPage();
}
});
mRecyclerView.setAdapter(mAdapter);
if (!mAdapter.isEmpty()) {
return;
}
if (state == null) {
loadTheFirstPage();
} else {
final List<AugmentedMention> mentions = state
.getParcelableArrayList(SAVED_ADAPTER_STATE);
if (Utils.isCollectionEmpty(mentions)) {
loadTheFirstPage();
} else {
// This should give a non-zero integer
mTotalPages = state.getInt(PAGES_SAVED_STATE); | mInfiniteScrollListener = new InfiniteRecyclerLoadHelper(mRecyclerView, |
xda/XDA-One | android/src/main/java/com/xda/one/api/inteface/ThreadClient.java | // Path: android/src/main/java/com/xda/one/api/misc/Consumer.java
// public interface Consumer<T> {
//
// public void run(T data);
// }
//
// Path: android/src/main/java/com/xda/one/api/misc/Result.java
// public class Result {
//
// private static final String ERROR = "error";
//
// private static final String MESSAGE = "message";
//
// private boolean mSuccess;
//
// private String mMessage;
//
// public Result(final boolean success) {
// mSuccess = success;
// }
//
// public Result(final String message) {
// mMessage = message;
// }
//
// public static Result parseResultFromResponse(final Response response) {
// InputStream inputStream = null;
// try {
// inputStream = response.getBody().in();
// final String output = IOUtils.toString(inputStream);
// return Result.parseResultFromString(output);
// } catch (IOException | NullPointerException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static Result parseResultFromString(final String line) {
// if (line == null) {
// return null;
// }
//
// final Result result;
// try {
// final JsonNode error = OBJECT_MAPPER.readTree(line).get(ERROR);
//
// if (error == null) {
// result = new Result(true);
// } else {
// result = new Result(error.get(MESSAGE).asText());
// }
// return result;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean isSuccess(Result result) {
// return result != null && result.isSuccess();
// }
//
// public boolean isSuccess() {
// return mSuccess;
// }
//
// public String getMessage() {
// return mMessage;
// }
// }
//
// Path: android/src/main/java/com/xda/one/api/model/interfaces/UnifiedThread.java
// public interface UnifiedThread extends Parcelable {
//
// public String getThreadId();
//
// public boolean isAttach();
//
// public boolean hasAttachment();
//
// public int getViews();
//
// public long getLastPost();
//
// public String getTitle();
//
// public String getFirstPostContent();
//
// public String getPostUsername();
//
// public boolean isSticky();
//
// public int getTotalPosts();
//
// public int getLastPostId();
//
// public String getLastPoster();
//
// public int getFirstPostId();
//
// public String getThreadSlug();
//
// String getForumTitle();
//
// public int getForumId();
//
// public int getReplyCount();
//
// public boolean isSubscribed();
//
// public String getAvatarUrl();
//
// public boolean isUnread();
//
// boolean isOpen();
//
// public String getWebUri();
// }
| import com.xda.one.api.misc.Consumer;
import com.xda.one.api.misc.EventBus;
import com.xda.one.api.misc.Result;
import com.xda.one.api.model.interfaces.UnifiedThread;
import com.xda.one.api.model.response.container.ResponseUnifiedThreadContainer; | package com.xda.one.api.inteface;
public interface ThreadClient {
public EventBus getBus();
public ResponseUnifiedThreadContainer getThreads(final int forumId, final int page);
public ResponseUnifiedThreadContainer getParticipatedThreads(final int page);
public ResponseUnifiedThreadContainer getSubscribedThreads(final int page);
public void createThread(final int forumId, final String title, final String message, | // Path: android/src/main/java/com/xda/one/api/misc/Consumer.java
// public interface Consumer<T> {
//
// public void run(T data);
// }
//
// Path: android/src/main/java/com/xda/one/api/misc/Result.java
// public class Result {
//
// private static final String ERROR = "error";
//
// private static final String MESSAGE = "message";
//
// private boolean mSuccess;
//
// private String mMessage;
//
// public Result(final boolean success) {
// mSuccess = success;
// }
//
// public Result(final String message) {
// mMessage = message;
// }
//
// public static Result parseResultFromResponse(final Response response) {
// InputStream inputStream = null;
// try {
// inputStream = response.getBody().in();
// final String output = IOUtils.toString(inputStream);
// return Result.parseResultFromString(output);
// } catch (IOException | NullPointerException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static Result parseResultFromString(final String line) {
// if (line == null) {
// return null;
// }
//
// final Result result;
// try {
// final JsonNode error = OBJECT_MAPPER.readTree(line).get(ERROR);
//
// if (error == null) {
// result = new Result(true);
// } else {
// result = new Result(error.get(MESSAGE).asText());
// }
// return result;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean isSuccess(Result result) {
// return result != null && result.isSuccess();
// }
//
// public boolean isSuccess() {
// return mSuccess;
// }
//
// public String getMessage() {
// return mMessage;
// }
// }
//
// Path: android/src/main/java/com/xda/one/api/model/interfaces/UnifiedThread.java
// public interface UnifiedThread extends Parcelable {
//
// public String getThreadId();
//
// public boolean isAttach();
//
// public boolean hasAttachment();
//
// public int getViews();
//
// public long getLastPost();
//
// public String getTitle();
//
// public String getFirstPostContent();
//
// public String getPostUsername();
//
// public boolean isSticky();
//
// public int getTotalPosts();
//
// public int getLastPostId();
//
// public String getLastPoster();
//
// public int getFirstPostId();
//
// public String getThreadSlug();
//
// String getForumTitle();
//
// public int getForumId();
//
// public int getReplyCount();
//
// public boolean isSubscribed();
//
// public String getAvatarUrl();
//
// public boolean isUnread();
//
// boolean isOpen();
//
// public String getWebUri();
// }
// Path: android/src/main/java/com/xda/one/api/inteface/ThreadClient.java
import com.xda.one.api.misc.Consumer;
import com.xda.one.api.misc.EventBus;
import com.xda.one.api.misc.Result;
import com.xda.one.api.model.interfaces.UnifiedThread;
import com.xda.one.api.model.response.container.ResponseUnifiedThreadContainer;
package com.xda.one.api.inteface;
public interface ThreadClient {
public EventBus getBus();
public ResponseUnifiedThreadContainer getThreads(final int forumId, final int page);
public ResponseUnifiedThreadContainer getParticipatedThreads(final int page);
public ResponseUnifiedThreadContainer getSubscribedThreads(final int page);
public void createThread(final int forumId, final String title, final String message, | final Consumer<Result> runnable); |
xda/XDA-One | android/src/main/java/com/xda/one/api/inteface/ThreadClient.java | // Path: android/src/main/java/com/xda/one/api/misc/Consumer.java
// public interface Consumer<T> {
//
// public void run(T data);
// }
//
// Path: android/src/main/java/com/xda/one/api/misc/Result.java
// public class Result {
//
// private static final String ERROR = "error";
//
// private static final String MESSAGE = "message";
//
// private boolean mSuccess;
//
// private String mMessage;
//
// public Result(final boolean success) {
// mSuccess = success;
// }
//
// public Result(final String message) {
// mMessage = message;
// }
//
// public static Result parseResultFromResponse(final Response response) {
// InputStream inputStream = null;
// try {
// inputStream = response.getBody().in();
// final String output = IOUtils.toString(inputStream);
// return Result.parseResultFromString(output);
// } catch (IOException | NullPointerException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static Result parseResultFromString(final String line) {
// if (line == null) {
// return null;
// }
//
// final Result result;
// try {
// final JsonNode error = OBJECT_MAPPER.readTree(line).get(ERROR);
//
// if (error == null) {
// result = new Result(true);
// } else {
// result = new Result(error.get(MESSAGE).asText());
// }
// return result;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean isSuccess(Result result) {
// return result != null && result.isSuccess();
// }
//
// public boolean isSuccess() {
// return mSuccess;
// }
//
// public String getMessage() {
// return mMessage;
// }
// }
//
// Path: android/src/main/java/com/xda/one/api/model/interfaces/UnifiedThread.java
// public interface UnifiedThread extends Parcelable {
//
// public String getThreadId();
//
// public boolean isAttach();
//
// public boolean hasAttachment();
//
// public int getViews();
//
// public long getLastPost();
//
// public String getTitle();
//
// public String getFirstPostContent();
//
// public String getPostUsername();
//
// public boolean isSticky();
//
// public int getTotalPosts();
//
// public int getLastPostId();
//
// public String getLastPoster();
//
// public int getFirstPostId();
//
// public String getThreadSlug();
//
// String getForumTitle();
//
// public int getForumId();
//
// public int getReplyCount();
//
// public boolean isSubscribed();
//
// public String getAvatarUrl();
//
// public boolean isUnread();
//
// boolean isOpen();
//
// public String getWebUri();
// }
| import com.xda.one.api.misc.Consumer;
import com.xda.one.api.misc.EventBus;
import com.xda.one.api.misc.Result;
import com.xda.one.api.model.interfaces.UnifiedThread;
import com.xda.one.api.model.response.container.ResponseUnifiedThreadContainer; | package com.xda.one.api.inteface;
public interface ThreadClient {
public EventBus getBus();
public ResponseUnifiedThreadContainer getThreads(final int forumId, final int page);
public ResponseUnifiedThreadContainer getParticipatedThreads(final int page);
public ResponseUnifiedThreadContainer getSubscribedThreads(final int page);
public void createThread(final int forumId, final String title, final String message, | // Path: android/src/main/java/com/xda/one/api/misc/Consumer.java
// public interface Consumer<T> {
//
// public void run(T data);
// }
//
// Path: android/src/main/java/com/xda/one/api/misc/Result.java
// public class Result {
//
// private static final String ERROR = "error";
//
// private static final String MESSAGE = "message";
//
// private boolean mSuccess;
//
// private String mMessage;
//
// public Result(final boolean success) {
// mSuccess = success;
// }
//
// public Result(final String message) {
// mMessage = message;
// }
//
// public static Result parseResultFromResponse(final Response response) {
// InputStream inputStream = null;
// try {
// inputStream = response.getBody().in();
// final String output = IOUtils.toString(inputStream);
// return Result.parseResultFromString(output);
// } catch (IOException | NullPointerException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static Result parseResultFromString(final String line) {
// if (line == null) {
// return null;
// }
//
// final Result result;
// try {
// final JsonNode error = OBJECT_MAPPER.readTree(line).get(ERROR);
//
// if (error == null) {
// result = new Result(true);
// } else {
// result = new Result(error.get(MESSAGE).asText());
// }
// return result;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean isSuccess(Result result) {
// return result != null && result.isSuccess();
// }
//
// public boolean isSuccess() {
// return mSuccess;
// }
//
// public String getMessage() {
// return mMessage;
// }
// }
//
// Path: android/src/main/java/com/xda/one/api/model/interfaces/UnifiedThread.java
// public interface UnifiedThread extends Parcelable {
//
// public String getThreadId();
//
// public boolean isAttach();
//
// public boolean hasAttachment();
//
// public int getViews();
//
// public long getLastPost();
//
// public String getTitle();
//
// public String getFirstPostContent();
//
// public String getPostUsername();
//
// public boolean isSticky();
//
// public int getTotalPosts();
//
// public int getLastPostId();
//
// public String getLastPoster();
//
// public int getFirstPostId();
//
// public String getThreadSlug();
//
// String getForumTitle();
//
// public int getForumId();
//
// public int getReplyCount();
//
// public boolean isSubscribed();
//
// public String getAvatarUrl();
//
// public boolean isUnread();
//
// boolean isOpen();
//
// public String getWebUri();
// }
// Path: android/src/main/java/com/xda/one/api/inteface/ThreadClient.java
import com.xda.one.api.misc.Consumer;
import com.xda.one.api.misc.EventBus;
import com.xda.one.api.misc.Result;
import com.xda.one.api.model.interfaces.UnifiedThread;
import com.xda.one.api.model.response.container.ResponseUnifiedThreadContainer;
package com.xda.one.api.inteface;
public interface ThreadClient {
public EventBus getBus();
public ResponseUnifiedThreadContainer getThreads(final int forumId, final int page);
public ResponseUnifiedThreadContainer getParticipatedThreads(final int page);
public ResponseUnifiedThreadContainer getSubscribedThreads(final int page);
public void createThread(final int forumId, final String title, final String message, | final Consumer<Result> runnable); |
xda/XDA-One | android/src/main/java/com/xda/one/api/inteface/ThreadClient.java | // Path: android/src/main/java/com/xda/one/api/misc/Consumer.java
// public interface Consumer<T> {
//
// public void run(T data);
// }
//
// Path: android/src/main/java/com/xda/one/api/misc/Result.java
// public class Result {
//
// private static final String ERROR = "error";
//
// private static final String MESSAGE = "message";
//
// private boolean mSuccess;
//
// private String mMessage;
//
// public Result(final boolean success) {
// mSuccess = success;
// }
//
// public Result(final String message) {
// mMessage = message;
// }
//
// public static Result parseResultFromResponse(final Response response) {
// InputStream inputStream = null;
// try {
// inputStream = response.getBody().in();
// final String output = IOUtils.toString(inputStream);
// return Result.parseResultFromString(output);
// } catch (IOException | NullPointerException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static Result parseResultFromString(final String line) {
// if (line == null) {
// return null;
// }
//
// final Result result;
// try {
// final JsonNode error = OBJECT_MAPPER.readTree(line).get(ERROR);
//
// if (error == null) {
// result = new Result(true);
// } else {
// result = new Result(error.get(MESSAGE).asText());
// }
// return result;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean isSuccess(Result result) {
// return result != null && result.isSuccess();
// }
//
// public boolean isSuccess() {
// return mSuccess;
// }
//
// public String getMessage() {
// return mMessage;
// }
// }
//
// Path: android/src/main/java/com/xda/one/api/model/interfaces/UnifiedThread.java
// public interface UnifiedThread extends Parcelable {
//
// public String getThreadId();
//
// public boolean isAttach();
//
// public boolean hasAttachment();
//
// public int getViews();
//
// public long getLastPost();
//
// public String getTitle();
//
// public String getFirstPostContent();
//
// public String getPostUsername();
//
// public boolean isSticky();
//
// public int getTotalPosts();
//
// public int getLastPostId();
//
// public String getLastPoster();
//
// public int getFirstPostId();
//
// public String getThreadSlug();
//
// String getForumTitle();
//
// public int getForumId();
//
// public int getReplyCount();
//
// public boolean isSubscribed();
//
// public String getAvatarUrl();
//
// public boolean isUnread();
//
// boolean isOpen();
//
// public String getWebUri();
// }
| import com.xda.one.api.misc.Consumer;
import com.xda.one.api.misc.EventBus;
import com.xda.one.api.misc.Result;
import com.xda.one.api.model.interfaces.UnifiedThread;
import com.xda.one.api.model.response.container.ResponseUnifiedThreadContainer; | package com.xda.one.api.inteface;
public interface ThreadClient {
public EventBus getBus();
public ResponseUnifiedThreadContainer getThreads(final int forumId, final int page);
public ResponseUnifiedThreadContainer getParticipatedThreads(final int page);
public ResponseUnifiedThreadContainer getSubscribedThreads(final int page);
public void createThread(final int forumId, final String title, final String message,
final Consumer<Result> runnable);
| // Path: android/src/main/java/com/xda/one/api/misc/Consumer.java
// public interface Consumer<T> {
//
// public void run(T data);
// }
//
// Path: android/src/main/java/com/xda/one/api/misc/Result.java
// public class Result {
//
// private static final String ERROR = "error";
//
// private static final String MESSAGE = "message";
//
// private boolean mSuccess;
//
// private String mMessage;
//
// public Result(final boolean success) {
// mSuccess = success;
// }
//
// public Result(final String message) {
// mMessage = message;
// }
//
// public static Result parseResultFromResponse(final Response response) {
// InputStream inputStream = null;
// try {
// inputStream = response.getBody().in();
// final String output = IOUtils.toString(inputStream);
// return Result.parseResultFromString(output);
// } catch (IOException | NullPointerException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static Result parseResultFromString(final String line) {
// if (line == null) {
// return null;
// }
//
// final Result result;
// try {
// final JsonNode error = OBJECT_MAPPER.readTree(line).get(ERROR);
//
// if (error == null) {
// result = new Result(true);
// } else {
// result = new Result(error.get(MESSAGE).asText());
// }
// return result;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean isSuccess(Result result) {
// return result != null && result.isSuccess();
// }
//
// public boolean isSuccess() {
// return mSuccess;
// }
//
// public String getMessage() {
// return mMessage;
// }
// }
//
// Path: android/src/main/java/com/xda/one/api/model/interfaces/UnifiedThread.java
// public interface UnifiedThread extends Parcelable {
//
// public String getThreadId();
//
// public boolean isAttach();
//
// public boolean hasAttachment();
//
// public int getViews();
//
// public long getLastPost();
//
// public String getTitle();
//
// public String getFirstPostContent();
//
// public String getPostUsername();
//
// public boolean isSticky();
//
// public int getTotalPosts();
//
// public int getLastPostId();
//
// public String getLastPoster();
//
// public int getFirstPostId();
//
// public String getThreadSlug();
//
// String getForumTitle();
//
// public int getForumId();
//
// public int getReplyCount();
//
// public boolean isSubscribed();
//
// public String getAvatarUrl();
//
// public boolean isUnread();
//
// boolean isOpen();
//
// public String getWebUri();
// }
// Path: android/src/main/java/com/xda/one/api/inteface/ThreadClient.java
import com.xda.one.api.misc.Consumer;
import com.xda.one.api.misc.EventBus;
import com.xda.one.api.misc.Result;
import com.xda.one.api.model.interfaces.UnifiedThread;
import com.xda.one.api.model.response.container.ResponseUnifiedThreadContainer;
package com.xda.one.api.inteface;
public interface ThreadClient {
public EventBus getBus();
public ResponseUnifiedThreadContainer getThreads(final int forumId, final int page);
public ResponseUnifiedThreadContainer getParticipatedThreads(final int page);
public ResponseUnifiedThreadContainer getSubscribedThreads(final int page);
public void createThread(final int forumId, final String title, final String message,
final Consumer<Result> runnable);
| public void subscribeAsync(final UnifiedThread normalDefaultUnifiedThread); |
xda/XDA-One | android/src/main/java/com/xda/one/ui/ViewMessageActivity.java | // Path: android/src/main/java/com/xda/one/model/augmented/AugmentedMessage.java
// public class AugmentedMessage implements Message {
//
// public static final Parcelable.Creator<AugmentedMessage> CREATOR
// = new Parcelable.Creator<AugmentedMessage>() {
// @Override
// public AugmentedMessage createFromParcel(final Parcel in) {
// return new AugmentedMessage(in);
// }
//
// @Override
// public AugmentedMessage[] newArray(final int size) {
// return new AugmentedMessage[size];
// }
// };
//
// private static final int MAX_LENGTH = 100;
//
// private final Message mMessage;
//
// private int mMessageRead;
//
// private String mSubMessage;
//
// private Spanned mMessageContent;
//
// private TextDataStructure mTextDataStructure;
//
// public AugmentedMessage(final Context context, final Message message) {
// mMessage = message;
//
// // Augmentation time
// mMessageRead = message.getMessageReadStatus();
//
// final CharSequence messageText = mMessage.getMessageContent();
// if (TextUtils.isEmpty(messageText)) {
// return;
// }
//
// final Spanned spanned = ContentParser.parseBBCode(context, messageText);
// setMessageContent(spanned);
//
// final String sub = StringUtils.trimCharSequence(spanned.toString(), MAX_LENGTH);
// mSubMessage = StringUtils.removeWhiteSpaces(sub);
// }
//
// private AugmentedMessage(final Parcel in) {
// mMessage = new ResponseMessage(in);
//
// mMessageRead = in.readInt();
//
// final Spanned spanned = Html.fromHtml(in.readString());
// setMessageContent(spanned);
//
// mSubMessage = in.readString();
// }
//
// @Override
// public int getPmId() {
// return mMessage.getPmId();
// }
//
// @Override
// public String getFromUserId() {
// return mMessage.getFromUserId();
// }
//
// @Override
// public String getFromUserName() {
// return mMessage.getFromUserName();
// }
//
// @Override
// public String getTitle() {
// return mMessage.getTitle();
// }
//
// @Override
// public long getDate() {
// return mMessage.getDate();
// }
//
// @Override
// public boolean isMessageUnread() {
// return mMessageRead == 0;
// }
//
// @Override
// public String getToUserArray() {
// return mMessage.getToUserArray();
// }
//
// @Override
// public boolean isShowSignature() {
// return mMessage.isShowSignature();
// }
//
// @Override
// public boolean isAllowSmilie() {
// return mMessage.isAllowSmilie();
// }
//
// @Override
// public int getMessageReadStatus() {
// return mMessageRead;
// }
//
// @Override
// public void setMessageReadStatus(int messageRead) {
// mMessageRead = messageRead;
// }
//
// @Override
// public String getAvatarUrl() {
// return mMessage.getAvatarUrl();
// }
//
// // Class specific stuff starts here
// @Override
// public Spanned getMessageContent() {
// return mMessageContent;
// }
//
// private void setMessageContent(final Spanned messageContent) {
// mMessageContent = messageContent;
//
// // While setting the message, also update the data structure
// mTextDataStructure = new TextDataStructure(messageContent);
// }
//
// @Override
// public String getSubMessage() {
// return mSubMessage;
// }
//
// @Override
// public TextDataStructure getTextDataStructure() {
// return mTextDataStructure;
// }
//
// private Message getMessage() {
// return mMessage;
// }
//
// // Parcelable starts here
// @Override
// public int describeContents() {
// return mMessage.describeContents();
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// mMessage.writeToParcel(dest, flags);
//
// dest.writeInt(mMessageRead);
// dest.writeString(Html.toHtml(mMessageContent));
// dest.writeString(mSubMessage);
// }
//
// // Equals and hashcode
// @Override
// public boolean equals(Object o) {
// if (!(o instanceof AugmentedMessage)) {
// return false;
// }
//
// final AugmentedMessage other = (AugmentedMessage) o;
// return getMessage().equals(other.getMessage());
// }
//
// @Override
// public int hashCode() {
// return mMessage.hashCode() + 41;
// }
// }
| import com.xda.one.R;
import com.xda.one.model.augmented.AugmentedMessage;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.WindowManager; | package com.xda.one.ui;
public class ViewMessageActivity extends BaseActivity {
private static final String MESSAGE_ARGUMENT = "message";
private ViewMessageFragment mMessageFragment;
private final String SCREEN_NAME = "ViewMessageActivity";
@Override
public void onCreate(final Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.frame_activity);
if (bundle == null) { | // Path: android/src/main/java/com/xda/one/model/augmented/AugmentedMessage.java
// public class AugmentedMessage implements Message {
//
// public static final Parcelable.Creator<AugmentedMessage> CREATOR
// = new Parcelable.Creator<AugmentedMessage>() {
// @Override
// public AugmentedMessage createFromParcel(final Parcel in) {
// return new AugmentedMessage(in);
// }
//
// @Override
// public AugmentedMessage[] newArray(final int size) {
// return new AugmentedMessage[size];
// }
// };
//
// private static final int MAX_LENGTH = 100;
//
// private final Message mMessage;
//
// private int mMessageRead;
//
// private String mSubMessage;
//
// private Spanned mMessageContent;
//
// private TextDataStructure mTextDataStructure;
//
// public AugmentedMessage(final Context context, final Message message) {
// mMessage = message;
//
// // Augmentation time
// mMessageRead = message.getMessageReadStatus();
//
// final CharSequence messageText = mMessage.getMessageContent();
// if (TextUtils.isEmpty(messageText)) {
// return;
// }
//
// final Spanned spanned = ContentParser.parseBBCode(context, messageText);
// setMessageContent(spanned);
//
// final String sub = StringUtils.trimCharSequence(spanned.toString(), MAX_LENGTH);
// mSubMessage = StringUtils.removeWhiteSpaces(sub);
// }
//
// private AugmentedMessage(final Parcel in) {
// mMessage = new ResponseMessage(in);
//
// mMessageRead = in.readInt();
//
// final Spanned spanned = Html.fromHtml(in.readString());
// setMessageContent(spanned);
//
// mSubMessage = in.readString();
// }
//
// @Override
// public int getPmId() {
// return mMessage.getPmId();
// }
//
// @Override
// public String getFromUserId() {
// return mMessage.getFromUserId();
// }
//
// @Override
// public String getFromUserName() {
// return mMessage.getFromUserName();
// }
//
// @Override
// public String getTitle() {
// return mMessage.getTitle();
// }
//
// @Override
// public long getDate() {
// return mMessage.getDate();
// }
//
// @Override
// public boolean isMessageUnread() {
// return mMessageRead == 0;
// }
//
// @Override
// public String getToUserArray() {
// return mMessage.getToUserArray();
// }
//
// @Override
// public boolean isShowSignature() {
// return mMessage.isShowSignature();
// }
//
// @Override
// public boolean isAllowSmilie() {
// return mMessage.isAllowSmilie();
// }
//
// @Override
// public int getMessageReadStatus() {
// return mMessageRead;
// }
//
// @Override
// public void setMessageReadStatus(int messageRead) {
// mMessageRead = messageRead;
// }
//
// @Override
// public String getAvatarUrl() {
// return mMessage.getAvatarUrl();
// }
//
// // Class specific stuff starts here
// @Override
// public Spanned getMessageContent() {
// return mMessageContent;
// }
//
// private void setMessageContent(final Spanned messageContent) {
// mMessageContent = messageContent;
//
// // While setting the message, also update the data structure
// mTextDataStructure = new TextDataStructure(messageContent);
// }
//
// @Override
// public String getSubMessage() {
// return mSubMessage;
// }
//
// @Override
// public TextDataStructure getTextDataStructure() {
// return mTextDataStructure;
// }
//
// private Message getMessage() {
// return mMessage;
// }
//
// // Parcelable starts here
// @Override
// public int describeContents() {
// return mMessage.describeContents();
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// mMessage.writeToParcel(dest, flags);
//
// dest.writeInt(mMessageRead);
// dest.writeString(Html.toHtml(mMessageContent));
// dest.writeString(mSubMessage);
// }
//
// // Equals and hashcode
// @Override
// public boolean equals(Object o) {
// if (!(o instanceof AugmentedMessage)) {
// return false;
// }
//
// final AugmentedMessage other = (AugmentedMessage) o;
// return getMessage().equals(other.getMessage());
// }
//
// @Override
// public int hashCode() {
// return mMessage.hashCode() + 41;
// }
// }
// Path: android/src/main/java/com/xda/one/ui/ViewMessageActivity.java
import com.xda.one.R;
import com.xda.one.model.augmented.AugmentedMessage;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.WindowManager;
package com.xda.one.ui;
public class ViewMessageActivity extends BaseActivity {
private static final String MESSAGE_ARGUMENT = "message";
private ViewMessageFragment mMessageFragment;
private final String SCREEN_NAME = "ViewMessageActivity";
@Override
public void onCreate(final Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.frame_activity);
if (bundle == null) { | final AugmentedMessage message = getIntent().getParcelableExtra(MESSAGE_ARGUMENT); |
xda/XDA-One | android/src/main/java/com/xda/one/auth/AuthForumLoaderCallbacks.java | // Path: android/src/main/java/com/xda/one/model/misc/ForumType.java
// public enum ForumType {
// TOP(R.string.forum_home_title),
// NEWEST(R.string.forum_home_title),
// GENERAL(R.string.forum_home_title),
// ALL(R.string.forum_home_title),
// CHILD(R.string.placeholder);
//
// private final int mStringTitleId;
//
// ForumType(int stringId) {
// mStringTitleId = stringId;
// }
//
// public int getStringTitleId() {
// return mStringTitleId;
// }
// }
//
// Path: android/src/main/java/com/xda/one/util/Utils.java
// public class Utils {
//
// public static String handleRetrofitErrorQuietly(final RetrofitError error) {
// error.printStackTrace();
//
// InputStream inputStream = null;
// try {
// if (error.isNetworkError()) {
// Log.e("XDA-ONE", "Network error happened.");
// } else {
// final TypedInput body = error.getResponse().getBody();
// if (body == null) {
// Log.e("XDA-ONE", "Unable to retrieve body");
// return null;
// }
// inputStream = body.in();
//
// final String result = IOUtils.toString(inputStream);
// Log.e("XDA-ONE", result);
// return result;
// }
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static <T> int getCollectionSize(final Collection<T> collection) {
// return collection == null ? 0 : collection.size();
// }
//
// public static boolean isCollectionEmpty(final Collection collection) {
// return collection == null || collection.isEmpty();
// }
//
// public static CharSequence getRelativeDate(final Context context, final long dateline) {
// return DateUtils.getRelativeDateTimeString(context, dateline,
// DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS,
// DateUtils.FORMAT_NUMERIC_DATE);
// }
// }
| import com.xda.one.api.model.response.ResponseForum;
import com.xda.one.loader.ForumLoader;
import com.xda.one.model.misc.ForumType;
import com.xda.one.util.Utils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.widget.Toast;
import java.util.List; | package com.xda.one.auth;
public class AuthForumLoaderCallbacks
implements LoaderManager.LoaderCallbacks<List<ResponseForum>> {
private final Activity mActivity;
private final XDAAccount mAccount;
private final ProgressDialog mProgressDialog;
public AuthForumLoaderCallbacks(final Activity activity, final XDAAccount account,
final ProgressDialog progressDialog) {
mActivity = activity;
mAccount = account;
mProgressDialog = progressDialog;
}
@Override
public Loader<List<ResponseForum>> onCreateLoader(final int id, final Bundle args) { | // Path: android/src/main/java/com/xda/one/model/misc/ForumType.java
// public enum ForumType {
// TOP(R.string.forum_home_title),
// NEWEST(R.string.forum_home_title),
// GENERAL(R.string.forum_home_title),
// ALL(R.string.forum_home_title),
// CHILD(R.string.placeholder);
//
// private final int mStringTitleId;
//
// ForumType(int stringId) {
// mStringTitleId = stringId;
// }
//
// public int getStringTitleId() {
// return mStringTitleId;
// }
// }
//
// Path: android/src/main/java/com/xda/one/util/Utils.java
// public class Utils {
//
// public static String handleRetrofitErrorQuietly(final RetrofitError error) {
// error.printStackTrace();
//
// InputStream inputStream = null;
// try {
// if (error.isNetworkError()) {
// Log.e("XDA-ONE", "Network error happened.");
// } else {
// final TypedInput body = error.getResponse().getBody();
// if (body == null) {
// Log.e("XDA-ONE", "Unable to retrieve body");
// return null;
// }
// inputStream = body.in();
//
// final String result = IOUtils.toString(inputStream);
// Log.e("XDA-ONE", result);
// return result;
// }
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static <T> int getCollectionSize(final Collection<T> collection) {
// return collection == null ? 0 : collection.size();
// }
//
// public static boolean isCollectionEmpty(final Collection collection) {
// return collection == null || collection.isEmpty();
// }
//
// public static CharSequence getRelativeDate(final Context context, final long dateline) {
// return DateUtils.getRelativeDateTimeString(context, dateline,
// DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS,
// DateUtils.FORMAT_NUMERIC_DATE);
// }
// }
// Path: android/src/main/java/com/xda/one/auth/AuthForumLoaderCallbacks.java
import com.xda.one.api.model.response.ResponseForum;
import com.xda.one.loader.ForumLoader;
import com.xda.one.model.misc.ForumType;
import com.xda.one.util.Utils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.widget.Toast;
import java.util.List;
package com.xda.one.auth;
public class AuthForumLoaderCallbacks
implements LoaderManager.LoaderCallbacks<List<ResponseForum>> {
private final Activity mActivity;
private final XDAAccount mAccount;
private final ProgressDialog mProgressDialog;
public AuthForumLoaderCallbacks(final Activity activity, final XDAAccount account,
final ProgressDialog progressDialog) {
mActivity = activity;
mAccount = account;
mProgressDialog = progressDialog;
}
@Override
public Loader<List<ResponseForum>> onCreateLoader(final int id, final Bundle args) { | return new ForumLoader(mActivity, ForumType.ALL, null, true); |
xda/XDA-One | android/src/main/java/com/xda/one/auth/AuthForumLoaderCallbacks.java | // Path: android/src/main/java/com/xda/one/model/misc/ForumType.java
// public enum ForumType {
// TOP(R.string.forum_home_title),
// NEWEST(R.string.forum_home_title),
// GENERAL(R.string.forum_home_title),
// ALL(R.string.forum_home_title),
// CHILD(R.string.placeholder);
//
// private final int mStringTitleId;
//
// ForumType(int stringId) {
// mStringTitleId = stringId;
// }
//
// public int getStringTitleId() {
// return mStringTitleId;
// }
// }
//
// Path: android/src/main/java/com/xda/one/util/Utils.java
// public class Utils {
//
// public static String handleRetrofitErrorQuietly(final RetrofitError error) {
// error.printStackTrace();
//
// InputStream inputStream = null;
// try {
// if (error.isNetworkError()) {
// Log.e("XDA-ONE", "Network error happened.");
// } else {
// final TypedInput body = error.getResponse().getBody();
// if (body == null) {
// Log.e("XDA-ONE", "Unable to retrieve body");
// return null;
// }
// inputStream = body.in();
//
// final String result = IOUtils.toString(inputStream);
// Log.e("XDA-ONE", result);
// return result;
// }
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static <T> int getCollectionSize(final Collection<T> collection) {
// return collection == null ? 0 : collection.size();
// }
//
// public static boolean isCollectionEmpty(final Collection collection) {
// return collection == null || collection.isEmpty();
// }
//
// public static CharSequence getRelativeDate(final Context context, final long dateline) {
// return DateUtils.getRelativeDateTimeString(context, dateline,
// DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS,
// DateUtils.FORMAT_NUMERIC_DATE);
// }
// }
| import com.xda.one.api.model.response.ResponseForum;
import com.xda.one.loader.ForumLoader;
import com.xda.one.model.misc.ForumType;
import com.xda.one.util.Utils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.widget.Toast;
import java.util.List; | package com.xda.one.auth;
public class AuthForumLoaderCallbacks
implements LoaderManager.LoaderCallbacks<List<ResponseForum>> {
private final Activity mActivity;
private final XDAAccount mAccount;
private final ProgressDialog mProgressDialog;
public AuthForumLoaderCallbacks(final Activity activity, final XDAAccount account,
final ProgressDialog progressDialog) {
mActivity = activity;
mAccount = account;
mProgressDialog = progressDialog;
}
@Override
public Loader<List<ResponseForum>> onCreateLoader(final int id, final Bundle args) {
return new ForumLoader(mActivity, ForumType.ALL, null, true);
}
@Override
public void onLoadFinished(final Loader<List<ResponseForum>> loader,
final List<ResponseForum> data) {
mProgressDialog.dismiss(); | // Path: android/src/main/java/com/xda/one/model/misc/ForumType.java
// public enum ForumType {
// TOP(R.string.forum_home_title),
// NEWEST(R.string.forum_home_title),
// GENERAL(R.string.forum_home_title),
// ALL(R.string.forum_home_title),
// CHILD(R.string.placeholder);
//
// private final int mStringTitleId;
//
// ForumType(int stringId) {
// mStringTitleId = stringId;
// }
//
// public int getStringTitleId() {
// return mStringTitleId;
// }
// }
//
// Path: android/src/main/java/com/xda/one/util/Utils.java
// public class Utils {
//
// public static String handleRetrofitErrorQuietly(final RetrofitError error) {
// error.printStackTrace();
//
// InputStream inputStream = null;
// try {
// if (error.isNetworkError()) {
// Log.e("XDA-ONE", "Network error happened.");
// } else {
// final TypedInput body = error.getResponse().getBody();
// if (body == null) {
// Log.e("XDA-ONE", "Unable to retrieve body");
// return null;
// }
// inputStream = body.in();
//
// final String result = IOUtils.toString(inputStream);
// Log.e("XDA-ONE", result);
// return result;
// }
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// IOUtils.closeQuietly(inputStream);
// }
// return null;
// }
//
// public static <T> int getCollectionSize(final Collection<T> collection) {
// return collection == null ? 0 : collection.size();
// }
//
// public static boolean isCollectionEmpty(final Collection collection) {
// return collection == null || collection.isEmpty();
// }
//
// public static CharSequence getRelativeDate(final Context context, final long dateline) {
// return DateUtils.getRelativeDateTimeString(context, dateline,
// DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS,
// DateUtils.FORMAT_NUMERIC_DATE);
// }
// }
// Path: android/src/main/java/com/xda/one/auth/AuthForumLoaderCallbacks.java
import com.xda.one.api.model.response.ResponseForum;
import com.xda.one.loader.ForumLoader;
import com.xda.one.model.misc.ForumType;
import com.xda.one.util.Utils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.widget.Toast;
import java.util.List;
package com.xda.one.auth;
public class AuthForumLoaderCallbacks
implements LoaderManager.LoaderCallbacks<List<ResponseForum>> {
private final Activity mActivity;
private final XDAAccount mAccount;
private final ProgressDialog mProgressDialog;
public AuthForumLoaderCallbacks(final Activity activity, final XDAAccount account,
final ProgressDialog progressDialog) {
mActivity = activity;
mAccount = account;
mProgressDialog = progressDialog;
}
@Override
public Loader<List<ResponseForum>> onCreateLoader(final int id, final Bundle args) {
return new ForumLoader(mActivity, ForumType.ALL, null, true);
}
@Override
public void onLoadFinished(final Loader<List<ResponseForum>> loader,
final List<ResponseForum> data) {
mProgressDialog.dismiss(); | if (Utils.isCollectionEmpty(data) || mAccount == null) { |
xda/XDA-One | android/src/main/java/com/xda/one/ui/MyDeviceFragment.java | // Path: android/src/main/java/com/xda/one/api/model/interfaces/Forum.java
// public interface Forum extends Parcelable {
//
// public String getTitle();
//
// public int getForumId();
//
// public int getParentId();
//
// public String getForumSlug();
//
// public boolean isSubscribed();
//
// public void setSubscribed(boolean subs);
//
// public String getImageUrl();
//
// public boolean hasChildren();
//
// public String getWebUri();
//
// public boolean canContainThreads();
// }
//
// Path: android/src/main/java/com/xda/one/api/model/response/ResponseUserProfile.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class ResponseUserProfile {
//
// private final ResponseAvatar mResponseAvatar = new ResponseAvatar();
//
// @JsonProperty("userid")
// private String mUserId;
//
// @JsonProperty("signature")
// private String mSignature;
//
// @JsonProperty("username")
// private String mUserName;
//
// @JsonProperty("usertitle")
// private String mUserTitle;
//
// @JsonProperty("posts")
// private int mPosts;
//
// @JsonProperty("post_thanks_thanked_posts")
// private int mThankedPosts;
//
// @JsonProperty("post_thanks_thanked_times")
// private int mThankedTimes;
//
// @JsonProperty("devices")
// private List<ResponseUserProfileDevice> mDevices;
//
// @JsonProperty("email")
// private String mEmail;
//
// @JsonProperty("notifications")
// private ResponseUserProfileNotificationContainer mNotifications;
//
// private CharSequence mParsedSignature;
//
// public CharSequence getParsedSignature() {
// return mParsedSignature;
// }
//
// public void setParsedSignature(final CharSequence parsedSignature) {
// mParsedSignature = parsedSignature;
// }
//
// public String getUserId() {
// return mUserId;
// }
//
// public String getSignature() {
// return mSignature;
// }
//
// public String getUserName() {
// return mUserName;
// }
//
// public String getUserTitle() {
// return mUserTitle;
// }
//
// public int getPosts() {
// return mPosts;
// }
//
// public int getThankedPosts() {
// return mThankedPosts;
// }
//
// public int getThankedTimes() {
// return mThankedTimes;
// }
//
// public List<ResponseUserProfileDevice> getDevices() {
// return mDevices;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public ResponseUserProfileNotificationContainer getNotifications() {
// return mNotifications;
// }
//
// // Delegate methods
// public String getAvatarUrl() {
// return mResponseAvatar.getAvatarUrl();
// }
//
// @JsonProperty(value = "avatar_url")
// public void setAvatarUrl(final String avatarUrl) {
// mResponseAvatar.setAvatarUrl(avatarUrl);
// }
// }
//
// Path: android/src/main/java/android/support/v7/widget/XDALinerLayoutManager.java
// public class XDALinerLayoutManager extends LinearLayoutManager {
//
// private boolean mListEnd = true;
//
// public XDALinerLayoutManager(final Context context) {
// super(context);
// }
//
// public XDALinerLayoutManager(final Context context, final int orientation,
// final boolean reverseLayout) {
// super(context, orientation, reverseLayout);
// }
//
// @Override
// int scrollBy(final int dy, final RecyclerView.Recycler recycler,
// final RecyclerView.State state) {
// int scrolled = super.scrollBy(dy, recycler, state);
// mListEnd = dy > 0 && dy > scrolled;
// return scrolled;
// }
//
// public boolean isListEnd() {
// return mListEnd;
// }
// }
| import com.squareup.picasso.Picasso;
import com.xda.one.R;
import com.xda.one.api.model.interfaces.Forum;
import com.xda.one.api.model.response.ResponseUserProfile;
import com.xda.one.loader.UserProfileLoader;
import com.xda.one.ui.helper.ActionModeHelper;
import com.xda.one.util.FragmentUtils;
import com.xda.one.util.UIUtils;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.XDALinerLayoutManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List; | package com.xda.one.ui;
public class MyDeviceFragment extends Fragment
implements LoaderManager.LoaderCallbacks<ResponseUserProfile> {
private ActionModeHelper mModeHelper;
private RecyclerView mRecyclerView;
| // Path: android/src/main/java/com/xda/one/api/model/interfaces/Forum.java
// public interface Forum extends Parcelable {
//
// public String getTitle();
//
// public int getForumId();
//
// public int getParentId();
//
// public String getForumSlug();
//
// public boolean isSubscribed();
//
// public void setSubscribed(boolean subs);
//
// public String getImageUrl();
//
// public boolean hasChildren();
//
// public String getWebUri();
//
// public boolean canContainThreads();
// }
//
// Path: android/src/main/java/com/xda/one/api/model/response/ResponseUserProfile.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class ResponseUserProfile {
//
// private final ResponseAvatar mResponseAvatar = new ResponseAvatar();
//
// @JsonProperty("userid")
// private String mUserId;
//
// @JsonProperty("signature")
// private String mSignature;
//
// @JsonProperty("username")
// private String mUserName;
//
// @JsonProperty("usertitle")
// private String mUserTitle;
//
// @JsonProperty("posts")
// private int mPosts;
//
// @JsonProperty("post_thanks_thanked_posts")
// private int mThankedPosts;
//
// @JsonProperty("post_thanks_thanked_times")
// private int mThankedTimes;
//
// @JsonProperty("devices")
// private List<ResponseUserProfileDevice> mDevices;
//
// @JsonProperty("email")
// private String mEmail;
//
// @JsonProperty("notifications")
// private ResponseUserProfileNotificationContainer mNotifications;
//
// private CharSequence mParsedSignature;
//
// public CharSequence getParsedSignature() {
// return mParsedSignature;
// }
//
// public void setParsedSignature(final CharSequence parsedSignature) {
// mParsedSignature = parsedSignature;
// }
//
// public String getUserId() {
// return mUserId;
// }
//
// public String getSignature() {
// return mSignature;
// }
//
// public String getUserName() {
// return mUserName;
// }
//
// public String getUserTitle() {
// return mUserTitle;
// }
//
// public int getPosts() {
// return mPosts;
// }
//
// public int getThankedPosts() {
// return mThankedPosts;
// }
//
// public int getThankedTimes() {
// return mThankedTimes;
// }
//
// public List<ResponseUserProfileDevice> getDevices() {
// return mDevices;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public ResponseUserProfileNotificationContainer getNotifications() {
// return mNotifications;
// }
//
// // Delegate methods
// public String getAvatarUrl() {
// return mResponseAvatar.getAvatarUrl();
// }
//
// @JsonProperty(value = "avatar_url")
// public void setAvatarUrl(final String avatarUrl) {
// mResponseAvatar.setAvatarUrl(avatarUrl);
// }
// }
//
// Path: android/src/main/java/android/support/v7/widget/XDALinerLayoutManager.java
// public class XDALinerLayoutManager extends LinearLayoutManager {
//
// private boolean mListEnd = true;
//
// public XDALinerLayoutManager(final Context context) {
// super(context);
// }
//
// public XDALinerLayoutManager(final Context context, final int orientation,
// final boolean reverseLayout) {
// super(context, orientation, reverseLayout);
// }
//
// @Override
// int scrollBy(final int dy, final RecyclerView.Recycler recycler,
// final RecyclerView.State state) {
// int scrolled = super.scrollBy(dy, recycler, state);
// mListEnd = dy > 0 && dy > scrolled;
// return scrolled;
// }
//
// public boolean isListEnd() {
// return mListEnd;
// }
// }
// Path: android/src/main/java/com/xda/one/ui/MyDeviceFragment.java
import com.squareup.picasso.Picasso;
import com.xda.one.R;
import com.xda.one.api.model.interfaces.Forum;
import com.xda.one.api.model.response.ResponseUserProfile;
import com.xda.one.loader.UserProfileLoader;
import com.xda.one.ui.helper.ActionModeHelper;
import com.xda.one.util.FragmentUtils;
import com.xda.one.util.UIUtils;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.XDALinerLayoutManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
package com.xda.one.ui;
public class MyDeviceFragment extends Fragment
implements LoaderManager.LoaderCallbacks<ResponseUserProfile> {
private ActionModeHelper mModeHelper;
private RecyclerView mRecyclerView;
| private ForumAdapter<Forum> mAdapter; |
xda/XDA-One | android/src/main/java/com/xda/one/ui/MyDeviceFragment.java | // Path: android/src/main/java/com/xda/one/api/model/interfaces/Forum.java
// public interface Forum extends Parcelable {
//
// public String getTitle();
//
// public int getForumId();
//
// public int getParentId();
//
// public String getForumSlug();
//
// public boolean isSubscribed();
//
// public void setSubscribed(boolean subs);
//
// public String getImageUrl();
//
// public boolean hasChildren();
//
// public String getWebUri();
//
// public boolean canContainThreads();
// }
//
// Path: android/src/main/java/com/xda/one/api/model/response/ResponseUserProfile.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class ResponseUserProfile {
//
// private final ResponseAvatar mResponseAvatar = new ResponseAvatar();
//
// @JsonProperty("userid")
// private String mUserId;
//
// @JsonProperty("signature")
// private String mSignature;
//
// @JsonProperty("username")
// private String mUserName;
//
// @JsonProperty("usertitle")
// private String mUserTitle;
//
// @JsonProperty("posts")
// private int mPosts;
//
// @JsonProperty("post_thanks_thanked_posts")
// private int mThankedPosts;
//
// @JsonProperty("post_thanks_thanked_times")
// private int mThankedTimes;
//
// @JsonProperty("devices")
// private List<ResponseUserProfileDevice> mDevices;
//
// @JsonProperty("email")
// private String mEmail;
//
// @JsonProperty("notifications")
// private ResponseUserProfileNotificationContainer mNotifications;
//
// private CharSequence mParsedSignature;
//
// public CharSequence getParsedSignature() {
// return mParsedSignature;
// }
//
// public void setParsedSignature(final CharSequence parsedSignature) {
// mParsedSignature = parsedSignature;
// }
//
// public String getUserId() {
// return mUserId;
// }
//
// public String getSignature() {
// return mSignature;
// }
//
// public String getUserName() {
// return mUserName;
// }
//
// public String getUserTitle() {
// return mUserTitle;
// }
//
// public int getPosts() {
// return mPosts;
// }
//
// public int getThankedPosts() {
// return mThankedPosts;
// }
//
// public int getThankedTimes() {
// return mThankedTimes;
// }
//
// public List<ResponseUserProfileDevice> getDevices() {
// return mDevices;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public ResponseUserProfileNotificationContainer getNotifications() {
// return mNotifications;
// }
//
// // Delegate methods
// public String getAvatarUrl() {
// return mResponseAvatar.getAvatarUrl();
// }
//
// @JsonProperty(value = "avatar_url")
// public void setAvatarUrl(final String avatarUrl) {
// mResponseAvatar.setAvatarUrl(avatarUrl);
// }
// }
//
// Path: android/src/main/java/android/support/v7/widget/XDALinerLayoutManager.java
// public class XDALinerLayoutManager extends LinearLayoutManager {
//
// private boolean mListEnd = true;
//
// public XDALinerLayoutManager(final Context context) {
// super(context);
// }
//
// public XDALinerLayoutManager(final Context context, final int orientation,
// final boolean reverseLayout) {
// super(context, orientation, reverseLayout);
// }
//
// @Override
// int scrollBy(final int dy, final RecyclerView.Recycler recycler,
// final RecyclerView.State state) {
// int scrolled = super.scrollBy(dy, recycler, state);
// mListEnd = dy > 0 && dy > scrolled;
// return scrolled;
// }
//
// public boolean isListEnd() {
// return mListEnd;
// }
// }
| import com.squareup.picasso.Picasso;
import com.xda.one.R;
import com.xda.one.api.model.interfaces.Forum;
import com.xda.one.api.model.response.ResponseUserProfile;
import com.xda.one.loader.UserProfileLoader;
import com.xda.one.ui.helper.ActionModeHelper;
import com.xda.one.util.FragmentUtils;
import com.xda.one.util.UIUtils;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.XDALinerLayoutManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List; | package com.xda.one.ui;
public class MyDeviceFragment extends Fragment
implements LoaderManager.LoaderCallbacks<ResponseUserProfile> {
private ActionModeHelper mModeHelper;
private RecyclerView mRecyclerView;
private ForumAdapter<Forum> mAdapter;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mModeHelper = new ActionModeHelper(getActivity(),
new ActionModeCallback(), new ClickListener(),
ActionModeHelper.SelectionMode.SINGLE);
mAdapter = new ForumAdapter<>(getActivity(), mModeHelper, mModeHelper, mModeHelper,
new ImageViewDeviceDelegate(), new SubscribeButtonDelegate());
}
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container,
@Nullable final Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_device_fragment, container, false);
}
@Override
public void onViewCreated(final View view, @Nullable final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(android.R.id.list); | // Path: android/src/main/java/com/xda/one/api/model/interfaces/Forum.java
// public interface Forum extends Parcelable {
//
// public String getTitle();
//
// public int getForumId();
//
// public int getParentId();
//
// public String getForumSlug();
//
// public boolean isSubscribed();
//
// public void setSubscribed(boolean subs);
//
// public String getImageUrl();
//
// public boolean hasChildren();
//
// public String getWebUri();
//
// public boolean canContainThreads();
// }
//
// Path: android/src/main/java/com/xda/one/api/model/response/ResponseUserProfile.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class ResponseUserProfile {
//
// private final ResponseAvatar mResponseAvatar = new ResponseAvatar();
//
// @JsonProperty("userid")
// private String mUserId;
//
// @JsonProperty("signature")
// private String mSignature;
//
// @JsonProperty("username")
// private String mUserName;
//
// @JsonProperty("usertitle")
// private String mUserTitle;
//
// @JsonProperty("posts")
// private int mPosts;
//
// @JsonProperty("post_thanks_thanked_posts")
// private int mThankedPosts;
//
// @JsonProperty("post_thanks_thanked_times")
// private int mThankedTimes;
//
// @JsonProperty("devices")
// private List<ResponseUserProfileDevice> mDevices;
//
// @JsonProperty("email")
// private String mEmail;
//
// @JsonProperty("notifications")
// private ResponseUserProfileNotificationContainer mNotifications;
//
// private CharSequence mParsedSignature;
//
// public CharSequence getParsedSignature() {
// return mParsedSignature;
// }
//
// public void setParsedSignature(final CharSequence parsedSignature) {
// mParsedSignature = parsedSignature;
// }
//
// public String getUserId() {
// return mUserId;
// }
//
// public String getSignature() {
// return mSignature;
// }
//
// public String getUserName() {
// return mUserName;
// }
//
// public String getUserTitle() {
// return mUserTitle;
// }
//
// public int getPosts() {
// return mPosts;
// }
//
// public int getThankedPosts() {
// return mThankedPosts;
// }
//
// public int getThankedTimes() {
// return mThankedTimes;
// }
//
// public List<ResponseUserProfileDevice> getDevices() {
// return mDevices;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public ResponseUserProfileNotificationContainer getNotifications() {
// return mNotifications;
// }
//
// // Delegate methods
// public String getAvatarUrl() {
// return mResponseAvatar.getAvatarUrl();
// }
//
// @JsonProperty(value = "avatar_url")
// public void setAvatarUrl(final String avatarUrl) {
// mResponseAvatar.setAvatarUrl(avatarUrl);
// }
// }
//
// Path: android/src/main/java/android/support/v7/widget/XDALinerLayoutManager.java
// public class XDALinerLayoutManager extends LinearLayoutManager {
//
// private boolean mListEnd = true;
//
// public XDALinerLayoutManager(final Context context) {
// super(context);
// }
//
// public XDALinerLayoutManager(final Context context, final int orientation,
// final boolean reverseLayout) {
// super(context, orientation, reverseLayout);
// }
//
// @Override
// int scrollBy(final int dy, final RecyclerView.Recycler recycler,
// final RecyclerView.State state) {
// int scrolled = super.scrollBy(dy, recycler, state);
// mListEnd = dy > 0 && dy > scrolled;
// return scrolled;
// }
//
// public boolean isListEnd() {
// return mListEnd;
// }
// }
// Path: android/src/main/java/com/xda/one/ui/MyDeviceFragment.java
import com.squareup.picasso.Picasso;
import com.xda.one.R;
import com.xda.one.api.model.interfaces.Forum;
import com.xda.one.api.model.response.ResponseUserProfile;
import com.xda.one.loader.UserProfileLoader;
import com.xda.one.ui.helper.ActionModeHelper;
import com.xda.one.util.FragmentUtils;
import com.xda.one.util.UIUtils;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.XDALinerLayoutManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
package com.xda.one.ui;
public class MyDeviceFragment extends Fragment
implements LoaderManager.LoaderCallbacks<ResponseUserProfile> {
private ActionModeHelper mModeHelper;
private RecyclerView mRecyclerView;
private ForumAdapter<Forum> mAdapter;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mModeHelper = new ActionModeHelper(getActivity(),
new ActionModeCallback(), new ClickListener(),
ActionModeHelper.SelectionMode.SINGLE);
mAdapter = new ForumAdapter<>(getActivity(), mModeHelper, mModeHelper, mModeHelper,
new ImageViewDeviceDelegate(), new SubscribeButtonDelegate());
}
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container,
@Nullable final Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_device_fragment, container, false);
}
@Override
public void onViewCreated(final View view, @Nullable final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(android.R.id.list); | mRecyclerView.setLayoutManager(new XDALinerLayoutManager(getActivity())); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.