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
|
---|---|---|---|---|---|---|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/MailUserInputProcessor.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
// public enum Assert {
// ;
//
// public static void isTrue(boolean statement, String errorMessage) throws ShellException {
// if (!statement) {
// throw new ShellException(errorMessage);
// }
// }
//
// public static void isNotNull(Object object, String errorMessage) throws ShellException {
// isTrue(Objects.nonNull(object), errorMessage);
// }
// }
|
import sshd.shell.springboot.util.Assert;
import java.util.Arrays;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Component
@Order(2)
@ConditionalOnProperty(prefix = "spring.mail", name = {"host", "port", "username", "password"})
@ConditionalOnClass(JavaMailSender.class)
@lombok.extern.slf4j.Slf4j
class MailUserInputProcessor extends BaseUserInputProcessor {
private final Pattern pattern = Pattern.compile("[\\w\\W]+\\s?\\|\\s?m (.+)");
@Autowired
private JavaMailSender mailSender;
@Override
public Optional<UsageInfo> getUsageInfo() {
return Optional.of(new UsageInfo(Arrays.<UsageInfo.Row>asList(
new UsageInfo.Row("m <emailId>", "Send response output of command execution to <emailId>"),
new UsageInfo.Row("", "Example usage: help | m [email protected]"))));
}
@Override
public Pattern getPattern() {
return pattern;
}
@Override
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
// public enum Assert {
// ;
//
// public static void isTrue(boolean statement, String errorMessage) throws ShellException {
// if (!statement) {
// throw new ShellException(errorMessage);
// }
// }
//
// public static void isNotNull(Object object, String errorMessage) throws ShellException {
// isTrue(Objects.nonNull(object), errorMessage);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/MailUserInputProcessor.java
import sshd.shell.springboot.util.Assert;
import java.util.Arrays;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Component
@Order(2)
@ConditionalOnProperty(prefix = "spring.mail", name = {"host", "port", "username", "password"})
@ConditionalOnClass(JavaMailSender.class)
@lombok.extern.slf4j.Slf4j
class MailUserInputProcessor extends BaseUserInputProcessor {
private final Pattern pattern = Pattern.compile("[\\w\\W]+\\s?\\|\\s?m (.+)");
@Autowired
private JavaMailSender mailSender;
@Override
public Optional<UsageInfo> getUsageInfo() {
return Optional.of(new UsageInfo(Arrays.<UsageInfo.Row>asList(
new UsageInfo.Row("m <emailId>", "Send response output of command execution to <emailId>"),
new UsageInfo.Row("", "Example usage: help | m [email protected]"))));
}
@Override
public Pattern getPattern() {
return pattern;
}
@Override
|
public void processUserInput(String userInput) throws InterruptedException, ShellException {
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/MailUserInputProcessor.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
// public enum Assert {
// ;
//
// public static void isTrue(boolean statement, String errorMessage) throws ShellException {
// if (!statement) {
// throw new ShellException(errorMessage);
// }
// }
//
// public static void isNotNull(Object object, String errorMessage) throws ShellException {
// isTrue(Objects.nonNull(object), errorMessage);
// }
// }
|
import sshd.shell.springboot.util.Assert;
import java.util.Arrays;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
|
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Component
@Order(2)
@ConditionalOnProperty(prefix = "spring.mail", name = {"host", "port", "username", "password"})
@ConditionalOnClass(JavaMailSender.class)
@lombok.extern.slf4j.Slf4j
class MailUserInputProcessor extends BaseUserInputProcessor {
private final Pattern pattern = Pattern.compile("[\\w\\W]+\\s?\\|\\s?m (.+)");
@Autowired
private JavaMailSender mailSender;
@Override
public Optional<UsageInfo> getUsageInfo() {
return Optional.of(new UsageInfo(Arrays.<UsageInfo.Row>asList(
new UsageInfo.Row("m <emailId>", "Send response output of command execution to <emailId>"),
new UsageInfo.Row("", "Example usage: help | m [email protected]"))));
}
@Override
public Pattern getPattern() {
return pattern;
}
@Override
public void processUserInput(String userInput) throws InterruptedException, ShellException {
String[] part = splitAndValidateCommand(userInput, "\\|", 2);
String emailId = getEmailId(userInput);
String commandExecution = part[0];
String output = processCommands(commandExecution);
sendMail(emailId, commandExecution, output);
}
private String getEmailId(String userInput) throws ShellException {
Matcher matcher = pattern.matcher(userInput);
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/ShellException.java
// public class ShellException extends Exception {
//
// private static final long serialVersionUID = 7114130906989289480L;
//
// public ShellException(String message) {
// super(message);
// }
//
// public ShellException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/Assert.java
// public enum Assert {
// ;
//
// public static void isTrue(boolean statement, String errorMessage) throws ShellException {
// if (!statement) {
// throw new ShellException(errorMessage);
// }
// }
//
// public static void isNotNull(Object object, String errorMessage) throws ShellException {
// isTrue(Objects.nonNull(object), errorMessage);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/console/MailUserInputProcessor.java
import sshd.shell.springboot.util.Assert;
import java.util.Arrays;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.ShellException;
/*
* Copyright 2017 anand.
*
* 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 sshd.shell.springboot.console;
/**
*
* @author anand
*/
@Component
@Order(2)
@ConditionalOnProperty(prefix = "spring.mail", name = {"host", "port", "username", "password"})
@ConditionalOnClass(JavaMailSender.class)
@lombok.extern.slf4j.Slf4j
class MailUserInputProcessor extends BaseUserInputProcessor {
private final Pattern pattern = Pattern.compile("[\\w\\W]+\\s?\\|\\s?m (.+)");
@Autowired
private JavaMailSender mailSender;
@Override
public Optional<UsageInfo> getUsageInfo() {
return Optional.of(new UsageInfo(Arrays.<UsageInfo.Row>asList(
new UsageInfo.Row("m <emailId>", "Send response output of command execution to <emailId>"),
new UsageInfo.Row("", "Example usage: help | m [email protected]"))));
}
@Override
public Pattern getPattern() {
return pattern;
}
@Override
public void processUserInput(String userInput) throws InterruptedException, ShellException {
String[] part = splitAndValidateCommand(userInput, "\\|", 2);
String emailId = getEmailId(userInput);
String commandExecution = part[0];
String output = processCommands(commandExecution);
sendMail(emailId, commandExecution, output);
}
private String getEmailId(String userInput) throws ShellException {
Matcher matcher = pattern.matcher(userInput);
|
Assert.isTrue(matcher.find(), "Unexpected error");
|
anand1st/sshd-shell-spring-boot
|
sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/CachesCommand.java
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
|
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.cache.CachesEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
|
/*
* Copyright 2018 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(CachesEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.caches.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "caches", description = "Caches info")
@lombok.extern.slf4j.Slf4j
public final class CachesCommand extends AbstractSystemCommand {
private final CachesEndpoint cachesEndpoint;
CachesCommand(@Value("${sshd.system.command.roles.caches}") String[] systemRoles, CachesEndpoint cachesEndpoint) {
super(systemRoles);
this.cachesEndpoint = cachesEndpoint;
}
@SshdShellCommand(value = "list", description = "Cache info")
public String cacheList(String arg) {
|
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/util/JsonUtils.java
// @lombok.extern.slf4j.Slf4j
// public enum JsonUtils {
// ;
//
// private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().findAndRegisterModules();
// private static final ObjectWriter WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter();
//
// public static String asJson(Object object) {
// try {
// return WRITER.writeValueAsString(object);
// } catch (JsonProcessingException ex) {
// log.error("Error processing json output", ex);
// return "Error processing json output: " + ex.getMessage();
// }
// }
//
// public static <E> E stringToObject(String json, Class<E> clazz) throws IOException {
// return OBJECT_MAPPER.readValue(json, clazz);
// }
// }
// Path: sshd-shell-spring-boot-starter/src/main/java/sshd/shell/springboot/command/CachesCommand.java
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.cache.CachesEndpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import sshd.shell.springboot.autoconfiguration.SshdShellCommand;
import sshd.shell.springboot.util.JsonUtils;
/*
* Copyright 2018 anand.
*
* 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 sshd.shell.springboot.command;
/**
*
* @author anand
*/
@Component
@ConditionalOnBean(CachesEndpoint.class)
@ConditionalOnProperty(name = "management.endpoint.caches.enabled", havingValue = "true", matchIfMissing = true)
@SshdShellCommand(value = "caches", description = "Caches info")
@lombok.extern.slf4j.Slf4j
public final class CachesCommand extends AbstractSystemCommand {
private final CachesEndpoint cachesEndpoint;
CachesCommand(@Value("${sshd.system.command.roles.caches}") String[] systemRoles, CachesEndpoint cachesEndpoint) {
super(systemRoles);
this.cachesEndpoint = cachesEndpoint;
}
@SshdShellCommand(value = "list", description = "Cache info")
public String cacheList(String arg) {
|
return JsonUtils.asJson(cachesEndpoint.caches());
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/view/bench/BenchmarkTableView.java
|
// Path: srcTools/magma/tools/benchmark/model/IModelReadOnly.java
// public interface IModelReadOnly {
// /**
// * @return the results per team
// */
// List<ITeamResult> getTeamResults();
//
// boolean isRunning();
//
// List<TeamConfiguration> loadConfigFile(File file) throws InvalidConfigFileException;
//
// void attach(IObserver<IModelReadOnly> observer);
//
// /**
// * Removes an observer from the list of observers
// *
// * @param observer The observer that wants to be removed
// * @return true if The observer has been in the list and was removed
// */
// boolean detach(IObserver<IModelReadOnly> observer);
// }
//
// Path: srcTools/magma/tools/benchmark/model/ITeamResult.java
// public interface ITeamResult extends ISingleResult {
// void addResult(ISingleResult result);
//
// float getAverageScore();
//
// int getFallenCount();
//
// int getPenaltyCount();
//
// @Override
// boolean isValid();
//
// int size();
//
// String getName();
//
// @Override
// String getStatusText();
//
// /** returns the nth result */
// ISingleResult getResult(int n);
// }
//
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
|
import hso.autonomy.util.observer.IObserver;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.List;
import javax.swing.AbstractCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import magma.tools.benchmark.model.IModelReadOnly;
import magma.tools.benchmark.model.ITeamResult;
import magma.tools.benchmark.model.TeamConfiguration;
|
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.view.bench;
/**
*
* @author kdorer
*/
public abstract class BenchmarkTableView implements IObserver<IModelReadOnly>
{
protected JTable table;
protected final IModelReadOnly model;
private final String startScriptFolder;
protected BenchmarkTableView(IModelReadOnly model, String startScriptFolder)
{
this.model = model;
this.startScriptFolder = startScriptFolder;
createTeamTable();
}
|
// Path: srcTools/magma/tools/benchmark/model/IModelReadOnly.java
// public interface IModelReadOnly {
// /**
// * @return the results per team
// */
// List<ITeamResult> getTeamResults();
//
// boolean isRunning();
//
// List<TeamConfiguration> loadConfigFile(File file) throws InvalidConfigFileException;
//
// void attach(IObserver<IModelReadOnly> observer);
//
// /**
// * Removes an observer from the list of observers
// *
// * @param observer The observer that wants to be removed
// * @return true if The observer has been in the list and was removed
// */
// boolean detach(IObserver<IModelReadOnly> observer);
// }
//
// Path: srcTools/magma/tools/benchmark/model/ITeamResult.java
// public interface ITeamResult extends ISingleResult {
// void addResult(ISingleResult result);
//
// float getAverageScore();
//
// int getFallenCount();
//
// int getPenaltyCount();
//
// @Override
// boolean isValid();
//
// int size();
//
// String getName();
//
// @Override
// String getStatusText();
//
// /** returns the nth result */
// ISingleResult getResult(int n);
// }
//
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
// Path: srcTools/magma/tools/benchmark/view/bench/BenchmarkTableView.java
import hso.autonomy.util.observer.IObserver;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.List;
import javax.swing.AbstractCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import magma.tools.benchmark.model.IModelReadOnly;
import magma.tools.benchmark.model.ITeamResult;
import magma.tools.benchmark.model.TeamConfiguration;
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.view.bench;
/**
*
* @author kdorer
*/
public abstract class BenchmarkTableView implements IObserver<IModelReadOnly>
{
protected JTable table;
protected final IModelReadOnly model;
private final String startScriptFolder;
protected BenchmarkTableView(IModelReadOnly model, String startScriptFolder)
{
this.model = model;
this.startScriptFolder = startScriptFolder;
createTeamTable();
}
|
public abstract List<TeamConfiguration> getTeamConfiguration();
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/view/bench/BenchmarkTableView.java
|
// Path: srcTools/magma/tools/benchmark/model/IModelReadOnly.java
// public interface IModelReadOnly {
// /**
// * @return the results per team
// */
// List<ITeamResult> getTeamResults();
//
// boolean isRunning();
//
// List<TeamConfiguration> loadConfigFile(File file) throws InvalidConfigFileException;
//
// void attach(IObserver<IModelReadOnly> observer);
//
// /**
// * Removes an observer from the list of observers
// *
// * @param observer The observer that wants to be removed
// * @return true if The observer has been in the list and was removed
// */
// boolean detach(IObserver<IModelReadOnly> observer);
// }
//
// Path: srcTools/magma/tools/benchmark/model/ITeamResult.java
// public interface ITeamResult extends ISingleResult {
// void addResult(ISingleResult result);
//
// float getAverageScore();
//
// int getFallenCount();
//
// int getPenaltyCount();
//
// @Override
// boolean isValid();
//
// int size();
//
// String getName();
//
// @Override
// String getStatusText();
//
// /** returns the nth result */
// ISingleResult getResult(int n);
// }
//
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
|
import hso.autonomy.util.observer.IObserver;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.List;
import javax.swing.AbstractCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import magma.tools.benchmark.model.IModelReadOnly;
import magma.tools.benchmark.model.ITeamResult;
import magma.tools.benchmark.model.TeamConfiguration;
|
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.view.bench;
/**
*
* @author kdorer
*/
public abstract class BenchmarkTableView implements IObserver<IModelReadOnly>
{
protected JTable table;
protected final IModelReadOnly model;
private final String startScriptFolder;
protected BenchmarkTableView(IModelReadOnly model, String startScriptFolder)
{
this.model = model;
this.startScriptFolder = startScriptFolder;
createTeamTable();
}
public abstract List<TeamConfiguration> getTeamConfiguration();
public void disableEditing()
{
table.setEnabled(false);
}
public void enableEditing()
{
table.setEnabled(true);
}
protected List<TeamConfiguration> getDefaultConfig()
{
return Collections.singletonList(new TeamConfiguration("magma", startScriptFolder, 0.4f));
}
|
// Path: srcTools/magma/tools/benchmark/model/IModelReadOnly.java
// public interface IModelReadOnly {
// /**
// * @return the results per team
// */
// List<ITeamResult> getTeamResults();
//
// boolean isRunning();
//
// List<TeamConfiguration> loadConfigFile(File file) throws InvalidConfigFileException;
//
// void attach(IObserver<IModelReadOnly> observer);
//
// /**
// * Removes an observer from the list of observers
// *
// * @param observer The observer that wants to be removed
// * @return true if The observer has been in the list and was removed
// */
// boolean detach(IObserver<IModelReadOnly> observer);
// }
//
// Path: srcTools/magma/tools/benchmark/model/ITeamResult.java
// public interface ITeamResult extends ISingleResult {
// void addResult(ISingleResult result);
//
// float getAverageScore();
//
// int getFallenCount();
//
// int getPenaltyCount();
//
// @Override
// boolean isValid();
//
// int size();
//
// String getName();
//
// @Override
// String getStatusText();
//
// /** returns the nth result */
// ISingleResult getResult(int n);
// }
//
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
// Path: srcTools/magma/tools/benchmark/view/bench/BenchmarkTableView.java
import hso.autonomy.util.observer.IObserver;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.List;
import javax.swing.AbstractCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import magma.tools.benchmark.model.IModelReadOnly;
import magma.tools.benchmark.model.ITeamResult;
import magma.tools.benchmark.model.TeamConfiguration;
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.view.bench;
/**
*
* @author kdorer
*/
public abstract class BenchmarkTableView implements IObserver<IModelReadOnly>
{
protected JTable table;
protected final IModelReadOnly model;
private final String startScriptFolder;
protected BenchmarkTableView(IModelReadOnly model, String startScriptFolder)
{
this.model = model;
this.startScriptFolder = startScriptFolder;
createTeamTable();
}
public abstract List<TeamConfiguration> getTeamConfiguration();
public void disableEditing()
{
table.setEnabled(false);
}
public void enableEditing()
{
table.setEnabled(true);
}
protected List<TeamConfiguration> getDefaultConfig()
{
return Collections.singletonList(new TeamConfiguration("magma", startScriptFolder, 0.4f));
}
|
private ITeamResult getTeamEntry(String name, List<ITeamResult> teamResults)
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/model/bench/kickchallenge/KickBenchmarkTeamResult.java
|
// Path: srcTools/magma/tools/benchmark/model/ISingleResult.java
// public interface ISingleResult {
// boolean isFallen();
//
// /**
// * @return true if a penalty was assigned with this try
// */
// boolean hasPenalty();
//
// boolean isValid();
//
// String getStatusText();
// }
//
// Path: srcTools/magma/tools/benchmark/model/bench/TeamResult.java
// public abstract class TeamResult implements ITeamResult
// {
// private final String name;
//
// protected final List<ISingleResult> results;
//
// public TeamResult(String name)
// {
// this.name = name;
// results = new ArrayList<>();
// }
//
// @Override
// public void addResult(ISingleResult result)
// {
// results.add(result);
// }
//
// @Override
// public abstract float getAverageScore();
//
// @Override
// public int getFallenCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int fallen = 0;
// for (ISingleResult result : results) {
// if (result.isFallen()) {
// fallen++;
// }
// }
// return fallen;
// }
//
// @Override
// public int getPenaltyCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int penalties = 0;
// for (ISingleResult result : results) {
// if (result.hasPenalty()) {
// penalties++;
// }
// }
// return penalties;
// }
//
// @Override
// public boolean isValid()
// {
// if (results.isEmpty()) {
// return false;
// }
// for (ISingleResult result : results) {
// if (!result.isValid()) {
// return false;
// }
// }
// return true;
// }
//
// @Override
// public int size()
// {
// return results.size();
// }
//
// @Override
// public String getName()
// {
// return name;
// }
//
// @Override
// public String getStatusText()
// {
// if (results.isEmpty()) {
// return "No results.";
// }
// StringBuilder buffer = new StringBuilder(1000);
// int i = 0;
// for (ISingleResult result : results) {
// if (!result.getStatusText().isEmpty()) {
// buffer.append(i + 1).append(": ");
// buffer.append(result.getStatusText()).append("\n");
// }
// i++;
// }
// String result = buffer.toString();
// if (result.isEmpty()) {
// result = "No problems.";
// }
// return result;
// }
//
// @Override
// public boolean isFallen()
// {
// return getFallenCount() > 0;
// }
//
// @Override
// public boolean hasPenalty()
// {
// return getPenaltyCount() > 0;
// }
//
// @Override
// public ISingleResult getResult(int n)
// {
// return results.get(n);
// }
// }
|
import magma.tools.benchmark.model.bench.TeamResult;
import magma.tools.benchmark.model.ISingleResult;
|
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.bench.kickchallenge;
/**
*
* @author kdorer
*/
public class KickBenchmarkTeamResult extends TeamResult
{
public KickBenchmarkTeamResult(String name)
{
super(name);
}
@Override
public float getAverageScore()
{
return getAverageDistance();
}
public float getAverageDistance()
{
if (results.isEmpty()) {
return 0.0f;
}
float avg = 0;
|
// Path: srcTools/magma/tools/benchmark/model/ISingleResult.java
// public interface ISingleResult {
// boolean isFallen();
//
// /**
// * @return true if a penalty was assigned with this try
// */
// boolean hasPenalty();
//
// boolean isValid();
//
// String getStatusText();
// }
//
// Path: srcTools/magma/tools/benchmark/model/bench/TeamResult.java
// public abstract class TeamResult implements ITeamResult
// {
// private final String name;
//
// protected final List<ISingleResult> results;
//
// public TeamResult(String name)
// {
// this.name = name;
// results = new ArrayList<>();
// }
//
// @Override
// public void addResult(ISingleResult result)
// {
// results.add(result);
// }
//
// @Override
// public abstract float getAverageScore();
//
// @Override
// public int getFallenCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int fallen = 0;
// for (ISingleResult result : results) {
// if (result.isFallen()) {
// fallen++;
// }
// }
// return fallen;
// }
//
// @Override
// public int getPenaltyCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int penalties = 0;
// for (ISingleResult result : results) {
// if (result.hasPenalty()) {
// penalties++;
// }
// }
// return penalties;
// }
//
// @Override
// public boolean isValid()
// {
// if (results.isEmpty()) {
// return false;
// }
// for (ISingleResult result : results) {
// if (!result.isValid()) {
// return false;
// }
// }
// return true;
// }
//
// @Override
// public int size()
// {
// return results.size();
// }
//
// @Override
// public String getName()
// {
// return name;
// }
//
// @Override
// public String getStatusText()
// {
// if (results.isEmpty()) {
// return "No results.";
// }
// StringBuilder buffer = new StringBuilder(1000);
// int i = 0;
// for (ISingleResult result : results) {
// if (!result.getStatusText().isEmpty()) {
// buffer.append(i + 1).append(": ");
// buffer.append(result.getStatusText()).append("\n");
// }
// i++;
// }
// String result = buffer.toString();
// if (result.isEmpty()) {
// result = "No problems.";
// }
// return result;
// }
//
// @Override
// public boolean isFallen()
// {
// return getFallenCount() > 0;
// }
//
// @Override
// public boolean hasPenalty()
// {
// return getPenaltyCount() > 0;
// }
//
// @Override
// public ISingleResult getResult(int n)
// {
// return results.get(n);
// }
// }
// Path: srcTools/magma/tools/benchmark/model/bench/kickchallenge/KickBenchmarkTeamResult.java
import magma.tools.benchmark.model.bench.TeamResult;
import magma.tools.benchmark.model.ISingleResult;
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.bench.kickchallenge;
/**
*
* @author kdorer
*/
public class KickBenchmarkTeamResult extends TeamResult
{
public KickBenchmarkTeamResult(String name)
{
super(name);
}
@Override
public float getAverageScore()
{
return getAverageDistance();
}
public float getAverageDistance()
{
if (results.isEmpty()) {
return 0.0f;
}
float avg = 0;
|
for (ISingleResult result : results) {
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/view/bench/runchallenge/RunBenchmarkTableModelExtension.java
|
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
|
import javax.swing.table.DefaultTableModel;
import magma.tools.benchmark.model.TeamConfiguration;
import java.util.List;
|
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.view.bench.runchallenge;
/**
*
* @author kdorer
*/
class RunBenchmarkTableModelExtension extends DefaultTableModel
{
static final int COLUMN_TEAMNAME = 0;
static final int COLUMN_STATUS = 1;
static final int COLUMN_SCORE = 2;
static final int COLUMN_RUNS = 3;
static final int COLUMN_FALLS = 4;
static final int COLUMN_SPEED = 5;
static final int COLUMN_OFF_GROUND = 6;
static final int COLUMN_ONE_LEG = 7;
static final int COLUMN_TWO_LEGS = 8;
static final int COLUMN_PATH = 9;
static final int COLUMN_DROP_HEIGHT = 10;
private final Class<?>[] columnTypes;
private final boolean[] editableColumns;
|
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
// Path: srcTools/magma/tools/benchmark/view/bench/runchallenge/RunBenchmarkTableModelExtension.java
import javax.swing.table.DefaultTableModel;
import magma.tools.benchmark.model.TeamConfiguration;
import java.util.List;
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.view.bench.runchallenge;
/**
*
* @author kdorer
*/
class RunBenchmarkTableModelExtension extends DefaultTableModel
{
static final int COLUMN_TEAMNAME = 0;
static final int COLUMN_STATUS = 1;
static final int COLUMN_SCORE = 2;
static final int COLUMN_RUNS = 3;
static final int COLUMN_FALLS = 4;
static final int COLUMN_SPEED = 5;
static final int COLUMN_OFF_GROUND = 6;
static final int COLUMN_ONE_LEG = 7;
static final int COLUMN_TWO_LEGS = 8;
static final int COLUMN_PATH = 9;
static final int COLUMN_DROP_HEIGHT = 10;
private final Class<?>[] columnTypes;
private final boolean[] editableColumns;
|
public static RunBenchmarkTableModelExtension getInstance(List<TeamConfiguration> config)
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/view/bench/keepawaychallenge/KeepAwayBenchmarkTableModelExtension.java
|
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
|
import java.util.List;
import javax.swing.table.DefaultTableModel;
import magma.tools.benchmark.model.TeamConfiguration;
|
package magma.tools.benchmark.view.bench.keepawaychallenge;
class KeepAwayBenchmarkTableModelExtension extends DefaultTableModel
{
static final int COLUMN_TEAMNAME = 0;
static final int COLUMN_STATUS = 1;
static final int COLUMN_TIME = 2;
static final int COLUMN_PATH = 3;
static final int COLUMN_DROP_HEIGHT = 4;
private final Class<?>[] columnTypes;
private final boolean[] editableColumns;
|
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
// Path: srcTools/magma/tools/benchmark/view/bench/keepawaychallenge/KeepAwayBenchmarkTableModelExtension.java
import java.util.List;
import javax.swing.table.DefaultTableModel;
import magma.tools.benchmark.model.TeamConfiguration;
package magma.tools.benchmark.view.bench.keepawaychallenge;
class KeepAwayBenchmarkTableModelExtension extends DefaultTableModel
{
static final int COLUMN_TEAMNAME = 0;
static final int COLUMN_STATUS = 1;
static final int COLUMN_TIME = 2;
static final int COLUMN_PATH = 3;
static final int COLUMN_DROP_HEIGHT = 4;
private final Class<?>[] columnTypes;
private final boolean[] editableColumns;
|
public static KeepAwayBenchmarkTableModelExtension getInstance(List<TeamConfiguration> config)
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/model/bench/goalieChallenge/GoalieBenchmarkTeamResult.java
|
// Path: srcTools/magma/tools/benchmark/model/ISingleResult.java
// public interface ISingleResult {
// boolean isFallen();
//
// /**
// * @return true if a penalty was assigned with this try
// */
// boolean hasPenalty();
//
// boolean isValid();
//
// String getStatusText();
// }
//
// Path: srcTools/magma/tools/benchmark/model/bench/TeamResult.java
// public abstract class TeamResult implements ITeamResult
// {
// private final String name;
//
// protected final List<ISingleResult> results;
//
// public TeamResult(String name)
// {
// this.name = name;
// results = new ArrayList<>();
// }
//
// @Override
// public void addResult(ISingleResult result)
// {
// results.add(result);
// }
//
// @Override
// public abstract float getAverageScore();
//
// @Override
// public int getFallenCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int fallen = 0;
// for (ISingleResult result : results) {
// if (result.isFallen()) {
// fallen++;
// }
// }
// return fallen;
// }
//
// @Override
// public int getPenaltyCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int penalties = 0;
// for (ISingleResult result : results) {
// if (result.hasPenalty()) {
// penalties++;
// }
// }
// return penalties;
// }
//
// @Override
// public boolean isValid()
// {
// if (results.isEmpty()) {
// return false;
// }
// for (ISingleResult result : results) {
// if (!result.isValid()) {
// return false;
// }
// }
// return true;
// }
//
// @Override
// public int size()
// {
// return results.size();
// }
//
// @Override
// public String getName()
// {
// return name;
// }
//
// @Override
// public String getStatusText()
// {
// if (results.isEmpty()) {
// return "No results.";
// }
// StringBuilder buffer = new StringBuilder(1000);
// int i = 0;
// for (ISingleResult result : results) {
// if (!result.getStatusText().isEmpty()) {
// buffer.append(i + 1).append(": ");
// buffer.append(result.getStatusText()).append("\n");
// }
// i++;
// }
// String result = buffer.toString();
// if (result.isEmpty()) {
// result = "No problems.";
// }
// return result;
// }
//
// @Override
// public boolean isFallen()
// {
// return getFallenCount() > 0;
// }
//
// @Override
// public boolean hasPenalty()
// {
// return getPenaltyCount() > 0;
// }
//
// @Override
// public ISingleResult getResult(int n)
// {
// return results.get(n);
// }
// }
|
import magma.tools.benchmark.model.bench.TeamResult;
import magma.tools.benchmark.model.ISingleResult;
|
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.bench.goaliechallenge;
/**
*
* @author kdorer
*/
public class GoalieBenchmarkTeamResult extends TeamResult
{
public GoalieBenchmarkTeamResult(String name)
{
super(name);
}
@Override
public float getAverageScore()
{
return getAverageDistance();
}
public float getAverageDistance()
{
if (results.isEmpty()) {
return 0.0f;
}
float avg = 0;
|
// Path: srcTools/magma/tools/benchmark/model/ISingleResult.java
// public interface ISingleResult {
// boolean isFallen();
//
// /**
// * @return true if a penalty was assigned with this try
// */
// boolean hasPenalty();
//
// boolean isValid();
//
// String getStatusText();
// }
//
// Path: srcTools/magma/tools/benchmark/model/bench/TeamResult.java
// public abstract class TeamResult implements ITeamResult
// {
// private final String name;
//
// protected final List<ISingleResult> results;
//
// public TeamResult(String name)
// {
// this.name = name;
// results = new ArrayList<>();
// }
//
// @Override
// public void addResult(ISingleResult result)
// {
// results.add(result);
// }
//
// @Override
// public abstract float getAverageScore();
//
// @Override
// public int getFallenCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int fallen = 0;
// for (ISingleResult result : results) {
// if (result.isFallen()) {
// fallen++;
// }
// }
// return fallen;
// }
//
// @Override
// public int getPenaltyCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int penalties = 0;
// for (ISingleResult result : results) {
// if (result.hasPenalty()) {
// penalties++;
// }
// }
// return penalties;
// }
//
// @Override
// public boolean isValid()
// {
// if (results.isEmpty()) {
// return false;
// }
// for (ISingleResult result : results) {
// if (!result.isValid()) {
// return false;
// }
// }
// return true;
// }
//
// @Override
// public int size()
// {
// return results.size();
// }
//
// @Override
// public String getName()
// {
// return name;
// }
//
// @Override
// public String getStatusText()
// {
// if (results.isEmpty()) {
// return "No results.";
// }
// StringBuilder buffer = new StringBuilder(1000);
// int i = 0;
// for (ISingleResult result : results) {
// if (!result.getStatusText().isEmpty()) {
// buffer.append(i + 1).append(": ");
// buffer.append(result.getStatusText()).append("\n");
// }
// i++;
// }
// String result = buffer.toString();
// if (result.isEmpty()) {
// result = "No problems.";
// }
// return result;
// }
//
// @Override
// public boolean isFallen()
// {
// return getFallenCount() > 0;
// }
//
// @Override
// public boolean hasPenalty()
// {
// return getPenaltyCount() > 0;
// }
//
// @Override
// public ISingleResult getResult(int n)
// {
// return results.get(n);
// }
// }
// Path: srcTools/magma/tools/benchmark/model/bench/goalieChallenge/GoalieBenchmarkTeamResult.java
import magma.tools.benchmark.model.bench.TeamResult;
import magma.tools.benchmark.model.ISingleResult;
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.bench.goaliechallenge;
/**
*
* @author kdorer
*/
public class GoalieBenchmarkTeamResult extends TeamResult
{
public GoalieBenchmarkTeamResult(String name)
{
super(name);
}
@Override
public float getAverageScore()
{
return getAverageDistance();
}
public float getAverageDistance()
{
if (results.isEmpty()) {
return 0.0f;
}
float avg = 0;
|
for (ISingleResult result : results) {
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/model/proxy/BenchmarkAgentProxy.java
|
// Path: srcTools/magma/tools/benchmark/model/bench/RunInformation.java
// public class RunInformation
// {
// /** the counter for which run it is currently */
// private final int runID;
//
// /** x coordinate on the field */
// private final double beamX;
//
// /** y coordinate on the field */
// private final double beamY;
//
// /** x coordinate of ball on the field */
// private final double ballX;
//
// /** y coordinate of ball on the field */
// private final double ballY;
//
// /** x coordinate of ball vel n the field */
// private final double ballVelX;
//
// /** y coordinate of ball vel on the field */
// private final double ballVelY;
//
// /** z coordinate of ball vel on the field */
// private final double ballVelZ;
//
// public RunInformation()
// {
// this(0, -13.5, 0, 0, 0);
// }
//
// public RunInformation(int runID, double beamX, double beamY, double ballX, double ballY)
// {
// super();
// this.runID = runID;
// this.beamX = beamX;
// this.beamY = beamY;
// this.ballX = ballX;
// this.ballY = ballY;
// this.ballVelX = 0.0;
// this.ballVelY = 0.0;
// this.ballVelZ = 0.0;
// }
//
// public RunInformation(int runID, double ballX, double ballY, double ballVelX, double ballVelY, double ballVelZ)
// {
// super();
// this.runID = runID;
// this.beamX = 0.0;
// this.beamY = 0.0;
// this.ballX = ballX;
// this.ballY = ballY;
// this.ballVelX = ballVelX;
// this.ballVelY = ballVelY;
// this.ballVelZ = ballVelZ;
// }
//
// public int getRunID()
// {
// return runID;
// }
//
// public double getBeamX()
// {
// return beamX;
// }
//
// public double getBeamY()
// {
// return beamY;
// }
//
// public double getBallX()
// {
// return ballX;
// }
//
// public double getBallY()
// {
// return ballY;
// }
//
// public double getBallVelX()
// {
// return ballVelX;
// }
//
// public double getBallVelY()
// {
// return ballVelY;
// }
//
// public double getBallVelZ()
// {
// return ballVelZ;
// }
// }
|
import hso.autonomy.util.symboltreeparser.SymbolNode;
import hso.autonomy.util.symboltreeparser.SymbolTreeParser;
import java.net.Socket;
import magma.tools.SAProxy.impl.AgentProxy;
import magma.tools.benchmark.model.bench.RunInformation;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
|
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.proxy;
/**
* Special proxy for benchmarking agents
* @author kdorer
*/
public class BenchmarkAgentProxy extends AgentProxy
{
/** counts the number of cycles both legs do not have force */
private int bothLegsOffGround;
/** counts the number of cycles one leg do not have force */
private int oneLegOffGround;
/** counts the number of cycles both legs have force */
private int noLegOffGround;
/** counts the number of cycles in which at least one leg has force */
private int legOnGround;
private boolean startCount;
private boolean stopCount;
private boolean beaming;
private final boolean allowPlayerBeaming;
private final boolean isGazebo;
|
// Path: srcTools/magma/tools/benchmark/model/bench/RunInformation.java
// public class RunInformation
// {
// /** the counter for which run it is currently */
// private final int runID;
//
// /** x coordinate on the field */
// private final double beamX;
//
// /** y coordinate on the field */
// private final double beamY;
//
// /** x coordinate of ball on the field */
// private final double ballX;
//
// /** y coordinate of ball on the field */
// private final double ballY;
//
// /** x coordinate of ball vel n the field */
// private final double ballVelX;
//
// /** y coordinate of ball vel on the field */
// private final double ballVelY;
//
// /** z coordinate of ball vel on the field */
// private final double ballVelZ;
//
// public RunInformation()
// {
// this(0, -13.5, 0, 0, 0);
// }
//
// public RunInformation(int runID, double beamX, double beamY, double ballX, double ballY)
// {
// super();
// this.runID = runID;
// this.beamX = beamX;
// this.beamY = beamY;
// this.ballX = ballX;
// this.ballY = ballY;
// this.ballVelX = 0.0;
// this.ballVelY = 0.0;
// this.ballVelZ = 0.0;
// }
//
// public RunInformation(int runID, double ballX, double ballY, double ballVelX, double ballVelY, double ballVelZ)
// {
// super();
// this.runID = runID;
// this.beamX = 0.0;
// this.beamY = 0.0;
// this.ballX = ballX;
// this.ballY = ballY;
// this.ballVelX = ballVelX;
// this.ballVelY = ballVelY;
// this.ballVelZ = ballVelZ;
// }
//
// public int getRunID()
// {
// return runID;
// }
//
// public double getBeamX()
// {
// return beamX;
// }
//
// public double getBeamY()
// {
// return beamY;
// }
//
// public double getBallX()
// {
// return ballX;
// }
//
// public double getBallY()
// {
// return ballY;
// }
//
// public double getBallVelX()
// {
// return ballVelX;
// }
//
// public double getBallVelY()
// {
// return ballVelY;
// }
//
// public double getBallVelZ()
// {
// return ballVelZ;
// }
// }
// Path: srcTools/magma/tools/benchmark/model/proxy/BenchmarkAgentProxy.java
import hso.autonomy.util.symboltreeparser.SymbolNode;
import hso.autonomy.util.symboltreeparser.SymbolTreeParser;
import java.net.Socket;
import magma.tools.SAProxy.impl.AgentProxy;
import magma.tools.benchmark.model.bench.RunInformation;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.proxy;
/**
* Special proxy for benchmarking agents
* @author kdorer
*/
public class BenchmarkAgentProxy extends AgentProxy
{
/** counts the number of cycles both legs do not have force */
private int bothLegsOffGround;
/** counts the number of cycles one leg do not have force */
private int oneLegOffGround;
/** counts the number of cycles both legs have force */
private int noLegOffGround;
/** counts the number of cycles in which at least one leg has force */
private int legOnGround;
private boolean startCount;
private boolean stopCount;
private boolean beaming;
private final boolean allowPlayerBeaming;
private final boolean isGazebo;
|
private RunInformation runInfo;
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/view/bench/kickchallenge/KickBenchmarkTableModelExtension.java
|
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
|
import javax.swing.table.DefaultTableModel;
import magma.tools.benchmark.model.TeamConfiguration;
import java.util.List;
|
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.view.bench.kickchallenge;
/**
*
* @author kdorer
*/
class KickBenchmarkTableModelExtension extends DefaultTableModel
{
static final int COLUMN_TEAMNAME = 0;
static final int COLUMN_STATUS = 1;
static final int COLUMN_SCORE = 2;
static final int COLUMN_RUNS = 3;
static final int COLUMN_PENALTIES = 4;
static final int COLUMN_DISTANCE = 5;
static final int COLUMN_PATH = 6;
static final int COLUMN_DROP_HEIGHT = 7;
private final Class<?>[] columnTypes;
private final boolean[] editableColumns;
|
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
// Path: srcTools/magma/tools/benchmark/view/bench/kickchallenge/KickBenchmarkTableModelExtension.java
import javax.swing.table.DefaultTableModel;
import magma.tools.benchmark.model.TeamConfiguration;
import java.util.List;
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.view.bench.kickchallenge;
/**
*
* @author kdorer
*/
class KickBenchmarkTableModelExtension extends DefaultTableModel
{
static final int COLUMN_TEAMNAME = 0;
static final int COLUMN_STATUS = 1;
static final int COLUMN_SCORE = 2;
static final int COLUMN_RUNS = 3;
static final int COLUMN_PENALTIES = 4;
static final int COLUMN_DISTANCE = 5;
static final int COLUMN_PATH = 6;
static final int COLUMN_DROP_HEIGHT = 7;
private final Class<?>[] columnTypes;
private final boolean[] editableColumns;
|
public static KickBenchmarkTableModelExtension getInstance(List<TeamConfiguration> config)
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/view/bench/passingchallenge/PassingBenchmarkTableModelExtension.java
|
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
|
import java.util.List;
import javax.swing.table.DefaultTableModel;
import magma.tools.benchmark.model.TeamConfiguration;
|
package magma.tools.benchmark.view.bench.passingchallenge;
public class PassingBenchmarkTableModelExtension extends DefaultTableModel
{
static final int COLUMN_TEAMNAME = 0;
static final int COLUMN_STATUS = 1;
static final int COLUMN_TIME = 2;
static final int COLUMN_BEST_TIME = 3;
static final int COLUMN_2_BEST_TIME = 4;
static final int COLUMN_3_BEST_TIME = 5;
static final int COLUMN_PATH = 6;
static final int COLUMN_DROP_HEIGHT = 7;
private final Class<?>[] columnTypes;
private final boolean[] editableColumns;
|
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
// Path: srcTools/magma/tools/benchmark/view/bench/passingchallenge/PassingBenchmarkTableModelExtension.java
import java.util.List;
import javax.swing.table.DefaultTableModel;
import magma.tools.benchmark.model.TeamConfiguration;
package magma.tools.benchmark.view.bench.passingchallenge;
public class PassingBenchmarkTableModelExtension extends DefaultTableModel
{
static final int COLUMN_TEAMNAME = 0;
static final int COLUMN_STATUS = 1;
static final int COLUMN_TIME = 2;
static final int COLUMN_BEST_TIME = 3;
static final int COLUMN_2_BEST_TIME = 4;
static final int COLUMN_3_BEST_TIME = 5;
static final int COLUMN_PATH = 6;
static final int COLUMN_DROP_HEIGHT = 7;
private final Class<?>[] columnTypes;
private final boolean[] editableColumns;
|
public static PassingBenchmarkTableModelExtension getInstance(List<TeamConfiguration> config)
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/model/bench/ConfigLoader.java
|
// Path: srcTools/magma/tools/benchmark/model/InvalidConfigFileException.java
// public class InvalidConfigFileException extends Exception
// {
// public InvalidConfigFileException(String message)
// {
// super(message);
// }
//
// public InvalidConfigFileException(Throwable cause)
// {
// super(cause);
// }
//
// public InvalidConfigFileException(String message, Throwable cause)
// {
// super(message, cause);
// }
// }
//
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
|
import hso.autonomy.util.file.CSVFileUtil;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import magma.tools.benchmark.model.InvalidConfigFileException;
import magma.tools.benchmark.model.TeamConfiguration;
|
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.bench;
/**
*
* @author kdorer
*/
public class ConfigLoader
{
|
// Path: srcTools/magma/tools/benchmark/model/InvalidConfigFileException.java
// public class InvalidConfigFileException extends Exception
// {
// public InvalidConfigFileException(String message)
// {
// super(message);
// }
//
// public InvalidConfigFileException(Throwable cause)
// {
// super(cause);
// }
//
// public InvalidConfigFileException(String message, Throwable cause)
// {
// super(message, cause);
// }
// }
//
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
// Path: srcTools/magma/tools/benchmark/model/bench/ConfigLoader.java
import hso.autonomy.util.file.CSVFileUtil;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import magma.tools.benchmark.model.InvalidConfigFileException;
import magma.tools.benchmark.model.TeamConfiguration;
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.bench;
/**
*
* @author kdorer
*/
public class ConfigLoader
{
|
public List<TeamConfiguration> loadConfigFile(File file) throws InvalidConfigFileException
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/model/bench/ConfigLoader.java
|
// Path: srcTools/magma/tools/benchmark/model/InvalidConfigFileException.java
// public class InvalidConfigFileException extends Exception
// {
// public InvalidConfigFileException(String message)
// {
// super(message);
// }
//
// public InvalidConfigFileException(Throwable cause)
// {
// super(cause);
// }
//
// public InvalidConfigFileException(String message, Throwable cause)
// {
// super(message, cause);
// }
// }
//
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
|
import hso.autonomy.util.file.CSVFileUtil;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import magma.tools.benchmark.model.InvalidConfigFileException;
import magma.tools.benchmark.model.TeamConfiguration;
|
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.bench;
/**
*
* @author kdorer
*/
public class ConfigLoader
{
|
// Path: srcTools/magma/tools/benchmark/model/InvalidConfigFileException.java
// public class InvalidConfigFileException extends Exception
// {
// public InvalidConfigFileException(String message)
// {
// super(message);
// }
//
// public InvalidConfigFileException(Throwable cause)
// {
// super(cause);
// }
//
// public InvalidConfigFileException(String message, Throwable cause)
// {
// super(message, cause);
// }
// }
//
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
// Path: srcTools/magma/tools/benchmark/model/bench/ConfigLoader.java
import hso.autonomy.util.file.CSVFileUtil;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import magma.tools.benchmark.model.InvalidConfigFileException;
import magma.tools.benchmark.model.TeamConfiguration;
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.bench;
/**
*
* @author kdorer
*/
public class ConfigLoader
{
|
public List<TeamConfiguration> loadConfigFile(File file) throws InvalidConfigFileException
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/view/bench/goalieChallenge/GoalieBenchmarkTableModelExtension.java
|
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
|
import javax.swing.table.DefaultTableModel;
import magma.tools.benchmark.model.TeamConfiguration;
import java.util.List;
|
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.view.bench.goaliechallenge;
/**
*
* @author kdorer
*/
class GoalieBenchmarkTableModelExtension extends DefaultTableModel
{
static final int COLUMN_TEAMNAME = 0;
static final int COLUMN_STATUS = 1;
static final int COLUMN_SCORE = 2;
static final int COLUMN_RUNS = 3;
static final int COLUMN_PATH = 4;
private final Class<?>[] columnTypes;
private final boolean[] editableColumns;
|
// Path: srcTools/magma/tools/benchmark/model/TeamConfiguration.java
// public class TeamConfiguration
// {
// private final String name;
//
// private final String path;
//
// private final float dropHeight;
//
// public TeamConfiguration(String name, String path, float dropHeight)
// {
// this.name = name;
// this.path = path;
// this.dropHeight = dropHeight;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getPath()
// {
// return path;
// }
//
// /**
// * @return the dropHeight of the player
// */
// public float getDropHeight()
// {
// return dropHeight;
// }
// }
// Path: srcTools/magma/tools/benchmark/view/bench/goalieChallenge/GoalieBenchmarkTableModelExtension.java
import javax.swing.table.DefaultTableModel;
import magma.tools.benchmark.model.TeamConfiguration;
import java.util.List;
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.view.bench.goaliechallenge;
/**
*
* @author kdorer
*/
class GoalieBenchmarkTableModelExtension extends DefaultTableModel
{
static final int COLUMN_TEAMNAME = 0;
static final int COLUMN_STATUS = 1;
static final int COLUMN_SCORE = 2;
static final int COLUMN_RUNS = 3;
static final int COLUMN_PATH = 4;
private final Class<?>[] columnTypes;
private final boolean[] editableColumns;
|
public static GoalieBenchmarkTableModelExtension getInstance(List<TeamConfiguration> config)
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/model/proxy/BenchmarkAgentProxyServer.java
|
// Path: srcTools/magma/tools/benchmark/model/bench/RunInformation.java
// public class RunInformation
// {
// /** the counter for which run it is currently */
// private final int runID;
//
// /** x coordinate on the field */
// private final double beamX;
//
// /** y coordinate on the field */
// private final double beamY;
//
// /** x coordinate of ball on the field */
// private final double ballX;
//
// /** y coordinate of ball on the field */
// private final double ballY;
//
// /** x coordinate of ball vel n the field */
// private final double ballVelX;
//
// /** y coordinate of ball vel on the field */
// private final double ballVelY;
//
// /** z coordinate of ball vel on the field */
// private final double ballVelZ;
//
// public RunInformation()
// {
// this(0, -13.5, 0, 0, 0);
// }
//
// public RunInformation(int runID, double beamX, double beamY, double ballX, double ballY)
// {
// super();
// this.runID = runID;
// this.beamX = beamX;
// this.beamY = beamY;
// this.ballX = ballX;
// this.ballY = ballY;
// this.ballVelX = 0.0;
// this.ballVelY = 0.0;
// this.ballVelZ = 0.0;
// }
//
// public RunInformation(int runID, double ballX, double ballY, double ballVelX, double ballVelY, double ballVelZ)
// {
// super();
// this.runID = runID;
// this.beamX = 0.0;
// this.beamY = 0.0;
// this.ballX = ballX;
// this.ballY = ballY;
// this.ballVelX = ballVelX;
// this.ballVelY = ballVelY;
// this.ballVelZ = ballVelZ;
// }
//
// public int getRunID()
// {
// return runID;
// }
//
// public double getBeamX()
// {
// return beamX;
// }
//
// public double getBeamY()
// {
// return beamY;
// }
//
// public double getBallX()
// {
// return ballX;
// }
//
// public double getBallY()
// {
// return ballY;
// }
//
// public double getBallVelX()
// {
// return ballVelX;
// }
//
// public double getBallVelY()
// {
// return ballVelY;
// }
//
// public double getBallVelZ()
// {
// return ballVelZ;
// }
// }
|
import java.net.Socket;
import magma.tools.SAProxy.impl.AgentProxy;
import magma.tools.SAProxy.impl.SimsparkAgentProxyServer;
import magma.tools.benchmark.model.bench.RunInformation;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
|
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.proxy;
/**
*
* @author kdorer
*/
public class BenchmarkAgentProxyServer extends SimsparkAgentProxyServer
{
private final int allowedPlayers;
private final boolean allowPlayerBeaming;
private final boolean isGazebo;
|
// Path: srcTools/magma/tools/benchmark/model/bench/RunInformation.java
// public class RunInformation
// {
// /** the counter for which run it is currently */
// private final int runID;
//
// /** x coordinate on the field */
// private final double beamX;
//
// /** y coordinate on the field */
// private final double beamY;
//
// /** x coordinate of ball on the field */
// private final double ballX;
//
// /** y coordinate of ball on the field */
// private final double ballY;
//
// /** x coordinate of ball vel n the field */
// private final double ballVelX;
//
// /** y coordinate of ball vel on the field */
// private final double ballVelY;
//
// /** z coordinate of ball vel on the field */
// private final double ballVelZ;
//
// public RunInformation()
// {
// this(0, -13.5, 0, 0, 0);
// }
//
// public RunInformation(int runID, double beamX, double beamY, double ballX, double ballY)
// {
// super();
// this.runID = runID;
// this.beamX = beamX;
// this.beamY = beamY;
// this.ballX = ballX;
// this.ballY = ballY;
// this.ballVelX = 0.0;
// this.ballVelY = 0.0;
// this.ballVelZ = 0.0;
// }
//
// public RunInformation(int runID, double ballX, double ballY, double ballVelX, double ballVelY, double ballVelZ)
// {
// super();
// this.runID = runID;
// this.beamX = 0.0;
// this.beamY = 0.0;
// this.ballX = ballX;
// this.ballY = ballY;
// this.ballVelX = ballVelX;
// this.ballVelY = ballVelY;
// this.ballVelZ = ballVelZ;
// }
//
// public int getRunID()
// {
// return runID;
// }
//
// public double getBeamX()
// {
// return beamX;
// }
//
// public double getBeamY()
// {
// return beamY;
// }
//
// public double getBallX()
// {
// return ballX;
// }
//
// public double getBallY()
// {
// return ballY;
// }
//
// public double getBallVelX()
// {
// return ballVelX;
// }
//
// public double getBallVelY()
// {
// return ballVelY;
// }
//
// public double getBallVelZ()
// {
// return ballVelZ;
// }
// }
// Path: srcTools/magma/tools/benchmark/model/proxy/BenchmarkAgentProxyServer.java
import java.net.Socket;
import magma.tools.SAProxy.impl.AgentProxy;
import magma.tools.SAProxy.impl.SimsparkAgentProxyServer;
import magma.tools.benchmark.model.bench.RunInformation;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.proxy;
/**
*
* @author kdorer
*/
public class BenchmarkAgentProxyServer extends SimsparkAgentProxyServer
{
private final int allowedPlayers;
private final boolean allowPlayerBeaming;
private final boolean isGazebo;
|
private RunInformation runInfo;
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/model/bench/TeamResult.java
|
// Path: srcTools/magma/tools/benchmark/model/ISingleResult.java
// public interface ISingleResult {
// boolean isFallen();
//
// /**
// * @return true if a penalty was assigned with this try
// */
// boolean hasPenalty();
//
// boolean isValid();
//
// String getStatusText();
// }
//
// Path: srcTools/magma/tools/benchmark/model/ITeamResult.java
// public interface ITeamResult extends ISingleResult {
// void addResult(ISingleResult result);
//
// float getAverageScore();
//
// int getFallenCount();
//
// int getPenaltyCount();
//
// @Override
// boolean isValid();
//
// int size();
//
// String getName();
//
// @Override
// String getStatusText();
//
// /** returns the nth result */
// ISingleResult getResult(int n);
// }
|
import java.util.List;
import magma.tools.benchmark.model.ISingleResult;
import magma.tools.benchmark.model.ITeamResult;
import java.util.ArrayList;
|
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.bench;
/**
*
* @author kdorer
*/
public abstract class TeamResult implements ITeamResult
{
private final String name;
|
// Path: srcTools/magma/tools/benchmark/model/ISingleResult.java
// public interface ISingleResult {
// boolean isFallen();
//
// /**
// * @return true if a penalty was assigned with this try
// */
// boolean hasPenalty();
//
// boolean isValid();
//
// String getStatusText();
// }
//
// Path: srcTools/magma/tools/benchmark/model/ITeamResult.java
// public interface ITeamResult extends ISingleResult {
// void addResult(ISingleResult result);
//
// float getAverageScore();
//
// int getFallenCount();
//
// int getPenaltyCount();
//
// @Override
// boolean isValid();
//
// int size();
//
// String getName();
//
// @Override
// String getStatusText();
//
// /** returns the nth result */
// ISingleResult getResult(int n);
// }
// Path: srcTools/magma/tools/benchmark/model/bench/TeamResult.java
import java.util.List;
import magma.tools.benchmark.model.ISingleResult;
import magma.tools.benchmark.model.ITeamResult;
import java.util.ArrayList;
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.bench;
/**
*
* @author kdorer
*/
public abstract class TeamResult implements ITeamResult
{
private final String name;
|
protected final List<ISingleResult> results;
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/model/bench/runchallenge/RunBenchmarkTeamResult.java
|
// Path: srcTools/magma/tools/benchmark/model/ISingleResult.java
// public interface ISingleResult {
// boolean isFallen();
//
// /**
// * @return true if a penalty was assigned with this try
// */
// boolean hasPenalty();
//
// boolean isValid();
//
// String getStatusText();
// }
//
// Path: srcTools/magma/tools/benchmark/model/bench/TeamResult.java
// public abstract class TeamResult implements ITeamResult
// {
// private final String name;
//
// protected final List<ISingleResult> results;
//
// public TeamResult(String name)
// {
// this.name = name;
// results = new ArrayList<>();
// }
//
// @Override
// public void addResult(ISingleResult result)
// {
// results.add(result);
// }
//
// @Override
// public abstract float getAverageScore();
//
// @Override
// public int getFallenCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int fallen = 0;
// for (ISingleResult result : results) {
// if (result.isFallen()) {
// fallen++;
// }
// }
// return fallen;
// }
//
// @Override
// public int getPenaltyCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int penalties = 0;
// for (ISingleResult result : results) {
// if (result.hasPenalty()) {
// penalties++;
// }
// }
// return penalties;
// }
//
// @Override
// public boolean isValid()
// {
// if (results.isEmpty()) {
// return false;
// }
// for (ISingleResult result : results) {
// if (!result.isValid()) {
// return false;
// }
// }
// return true;
// }
//
// @Override
// public int size()
// {
// return results.size();
// }
//
// @Override
// public String getName()
// {
// return name;
// }
//
// @Override
// public String getStatusText()
// {
// if (results.isEmpty()) {
// return "No results.";
// }
// StringBuilder buffer = new StringBuilder(1000);
// int i = 0;
// for (ISingleResult result : results) {
// if (!result.getStatusText().isEmpty()) {
// buffer.append(i + 1).append(": ");
// buffer.append(result.getStatusText()).append("\n");
// }
// i++;
// }
// String result = buffer.toString();
// if (result.isEmpty()) {
// result = "No problems.";
// }
// return result;
// }
//
// @Override
// public boolean isFallen()
// {
// return getFallenCount() > 0;
// }
//
// @Override
// public boolean hasPenalty()
// {
// return getPenaltyCount() > 0;
// }
//
// @Override
// public ISingleResult getResult(int n)
// {
// return results.get(n);
// }
// }
|
import magma.tools.benchmark.model.bench.TeamResult;
import magma.tools.benchmark.model.ISingleResult;
|
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.bench.runchallenge;
/**
*
* @author kdorer
*/
public class RunBenchmarkTeamResult extends TeamResult
{
public RunBenchmarkTeamResult(String name)
{
super(name);
}
@Override
public float getAverageScore()
{
return getAverageSpeed() + getAverageOffGround();
}
public float getAverageSpeed()
{
if (results.isEmpty()) {
return 0.0f;
}
float avg = 0;
|
// Path: srcTools/magma/tools/benchmark/model/ISingleResult.java
// public interface ISingleResult {
// boolean isFallen();
//
// /**
// * @return true if a penalty was assigned with this try
// */
// boolean hasPenalty();
//
// boolean isValid();
//
// String getStatusText();
// }
//
// Path: srcTools/magma/tools/benchmark/model/bench/TeamResult.java
// public abstract class TeamResult implements ITeamResult
// {
// private final String name;
//
// protected final List<ISingleResult> results;
//
// public TeamResult(String name)
// {
// this.name = name;
// results = new ArrayList<>();
// }
//
// @Override
// public void addResult(ISingleResult result)
// {
// results.add(result);
// }
//
// @Override
// public abstract float getAverageScore();
//
// @Override
// public int getFallenCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int fallen = 0;
// for (ISingleResult result : results) {
// if (result.isFallen()) {
// fallen++;
// }
// }
// return fallen;
// }
//
// @Override
// public int getPenaltyCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int penalties = 0;
// for (ISingleResult result : results) {
// if (result.hasPenalty()) {
// penalties++;
// }
// }
// return penalties;
// }
//
// @Override
// public boolean isValid()
// {
// if (results.isEmpty()) {
// return false;
// }
// for (ISingleResult result : results) {
// if (!result.isValid()) {
// return false;
// }
// }
// return true;
// }
//
// @Override
// public int size()
// {
// return results.size();
// }
//
// @Override
// public String getName()
// {
// return name;
// }
//
// @Override
// public String getStatusText()
// {
// if (results.isEmpty()) {
// return "No results.";
// }
// StringBuilder buffer = new StringBuilder(1000);
// int i = 0;
// for (ISingleResult result : results) {
// if (!result.getStatusText().isEmpty()) {
// buffer.append(i + 1).append(": ");
// buffer.append(result.getStatusText()).append("\n");
// }
// i++;
// }
// String result = buffer.toString();
// if (result.isEmpty()) {
// result = "No problems.";
// }
// return result;
// }
//
// @Override
// public boolean isFallen()
// {
// return getFallenCount() > 0;
// }
//
// @Override
// public boolean hasPenalty()
// {
// return getPenaltyCount() > 0;
// }
//
// @Override
// public ISingleResult getResult(int n)
// {
// return results.get(n);
// }
// }
// Path: srcTools/magma/tools/benchmark/model/bench/runchallenge/RunBenchmarkTeamResult.java
import magma.tools.benchmark.model.bench.TeamResult;
import magma.tools.benchmark.model.ISingleResult;
/* Copyright 2009 Hochschule Offenburg
* Klaus Dorer, Mathias Ehret, Stefan Glaser, Thomas Huber,
* Simon Raffeiner, Srinivasa Ragavan, Thomas Rinklin,
* Joachim Schilling, Rajit Shahi
*
* This file is part of magmaOffenburg.
*
* magmaOffenburg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* magmaOffenburg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with magmaOffenburg. If not, see <http://www.gnu.org/licenses/>.
*/
package magma.tools.benchmark.model.bench.runchallenge;
/**
*
* @author kdorer
*/
public class RunBenchmarkTeamResult extends TeamResult
{
public RunBenchmarkTeamResult(String name)
{
super(name);
}
@Override
public float getAverageScore()
{
return getAverageSpeed() + getAverageOffGround();
}
public float getAverageSpeed()
{
if (results.isEmpty()) {
return 0.0f;
}
float avg = 0;
|
for (ISingleResult result : results) {
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/model/bench/passingchallenge/PassingBenchmarkTeamResult.java
|
// Path: srcTools/magma/tools/benchmark/model/ISingleResult.java
// public interface ISingleResult {
// boolean isFallen();
//
// /**
// * @return true if a penalty was assigned with this try
// */
// boolean hasPenalty();
//
// boolean isValid();
//
// String getStatusText();
// }
//
// Path: srcTools/magma/tools/benchmark/model/bench/TeamResult.java
// public abstract class TeamResult implements ITeamResult
// {
// private final String name;
//
// protected final List<ISingleResult> results;
//
// public TeamResult(String name)
// {
// this.name = name;
// results = new ArrayList<>();
// }
//
// @Override
// public void addResult(ISingleResult result)
// {
// results.add(result);
// }
//
// @Override
// public abstract float getAverageScore();
//
// @Override
// public int getFallenCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int fallen = 0;
// for (ISingleResult result : results) {
// if (result.isFallen()) {
// fallen++;
// }
// }
// return fallen;
// }
//
// @Override
// public int getPenaltyCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int penalties = 0;
// for (ISingleResult result : results) {
// if (result.hasPenalty()) {
// penalties++;
// }
// }
// return penalties;
// }
//
// @Override
// public boolean isValid()
// {
// if (results.isEmpty()) {
// return false;
// }
// for (ISingleResult result : results) {
// if (!result.isValid()) {
// return false;
// }
// }
// return true;
// }
//
// @Override
// public int size()
// {
// return results.size();
// }
//
// @Override
// public String getName()
// {
// return name;
// }
//
// @Override
// public String getStatusText()
// {
// if (results.isEmpty()) {
// return "No results.";
// }
// StringBuilder buffer = new StringBuilder(1000);
// int i = 0;
// for (ISingleResult result : results) {
// if (!result.getStatusText().isEmpty()) {
// buffer.append(i + 1).append(": ");
// buffer.append(result.getStatusText()).append("\n");
// }
// i++;
// }
// String result = buffer.toString();
// if (result.isEmpty()) {
// result = "No problems.";
// }
// return result;
// }
//
// @Override
// public boolean isFallen()
// {
// return getFallenCount() > 0;
// }
//
// @Override
// public boolean hasPenalty()
// {
// return getPenaltyCount() > 0;
// }
//
// @Override
// public ISingleResult getResult(int n)
// {
// return results.get(n);
// }
// }
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import magma.tools.benchmark.model.ISingleResult;
import magma.tools.benchmark.model.bench.TeamResult;
|
if (scores.size() > 0) {
return scores.get(0);
} else {
return 0;
}
}
public float getSecondBestScore()
{
sortSingle();
if (scores.size() > 1) {
return scores.get(1);
} else {
return 0;
}
}
public float getThirdBestScore()
{
sortSingle();
if (scores.size() > 2) {
return scores.get(2);
} else {
return 0;
}
}
public void sortSingle()
{
int size = 0;
|
// Path: srcTools/magma/tools/benchmark/model/ISingleResult.java
// public interface ISingleResult {
// boolean isFallen();
//
// /**
// * @return true if a penalty was assigned with this try
// */
// boolean hasPenalty();
//
// boolean isValid();
//
// String getStatusText();
// }
//
// Path: srcTools/magma/tools/benchmark/model/bench/TeamResult.java
// public abstract class TeamResult implements ITeamResult
// {
// private final String name;
//
// protected final List<ISingleResult> results;
//
// public TeamResult(String name)
// {
// this.name = name;
// results = new ArrayList<>();
// }
//
// @Override
// public void addResult(ISingleResult result)
// {
// results.add(result);
// }
//
// @Override
// public abstract float getAverageScore();
//
// @Override
// public int getFallenCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int fallen = 0;
// for (ISingleResult result : results) {
// if (result.isFallen()) {
// fallen++;
// }
// }
// return fallen;
// }
//
// @Override
// public int getPenaltyCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int penalties = 0;
// for (ISingleResult result : results) {
// if (result.hasPenalty()) {
// penalties++;
// }
// }
// return penalties;
// }
//
// @Override
// public boolean isValid()
// {
// if (results.isEmpty()) {
// return false;
// }
// for (ISingleResult result : results) {
// if (!result.isValid()) {
// return false;
// }
// }
// return true;
// }
//
// @Override
// public int size()
// {
// return results.size();
// }
//
// @Override
// public String getName()
// {
// return name;
// }
//
// @Override
// public String getStatusText()
// {
// if (results.isEmpty()) {
// return "No results.";
// }
// StringBuilder buffer = new StringBuilder(1000);
// int i = 0;
// for (ISingleResult result : results) {
// if (!result.getStatusText().isEmpty()) {
// buffer.append(i + 1).append(": ");
// buffer.append(result.getStatusText()).append("\n");
// }
// i++;
// }
// String result = buffer.toString();
// if (result.isEmpty()) {
// result = "No problems.";
// }
// return result;
// }
//
// @Override
// public boolean isFallen()
// {
// return getFallenCount() > 0;
// }
//
// @Override
// public boolean hasPenalty()
// {
// return getPenaltyCount() > 0;
// }
//
// @Override
// public ISingleResult getResult(int n)
// {
// return results.get(n);
// }
// }
// Path: srcTools/magma/tools/benchmark/model/bench/passingchallenge/PassingBenchmarkTeamResult.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import magma.tools.benchmark.model.ISingleResult;
import magma.tools.benchmark.model.bench.TeamResult;
if (scores.size() > 0) {
return scores.get(0);
} else {
return 0;
}
}
public float getSecondBestScore()
{
sortSingle();
if (scores.size() > 1) {
return scores.get(1);
} else {
return 0;
}
}
public float getThirdBestScore()
{
sortSingle();
if (scores.size() > 2) {
return scores.get(2);
} else {
return 0;
}
}
public void sortSingle()
{
int size = 0;
|
for (ISingleResult result : results) {
|
magmaOffenburg/magmaChallenge
|
srcTools/magma/tools/benchmark/model/bench/keepawaychallenge/KeepAwayBenchmarkTeamResult.java
|
// Path: srcTools/magma/tools/benchmark/model/ISingleResult.java
// public interface ISingleResult {
// boolean isFallen();
//
// /**
// * @return true if a penalty was assigned with this try
// */
// boolean hasPenalty();
//
// boolean isValid();
//
// String getStatusText();
// }
//
// Path: srcTools/magma/tools/benchmark/model/bench/TeamResult.java
// public abstract class TeamResult implements ITeamResult
// {
// private final String name;
//
// protected final List<ISingleResult> results;
//
// public TeamResult(String name)
// {
// this.name = name;
// results = new ArrayList<>();
// }
//
// @Override
// public void addResult(ISingleResult result)
// {
// results.add(result);
// }
//
// @Override
// public abstract float getAverageScore();
//
// @Override
// public int getFallenCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int fallen = 0;
// for (ISingleResult result : results) {
// if (result.isFallen()) {
// fallen++;
// }
// }
// return fallen;
// }
//
// @Override
// public int getPenaltyCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int penalties = 0;
// for (ISingleResult result : results) {
// if (result.hasPenalty()) {
// penalties++;
// }
// }
// return penalties;
// }
//
// @Override
// public boolean isValid()
// {
// if (results.isEmpty()) {
// return false;
// }
// for (ISingleResult result : results) {
// if (!result.isValid()) {
// return false;
// }
// }
// return true;
// }
//
// @Override
// public int size()
// {
// return results.size();
// }
//
// @Override
// public String getName()
// {
// return name;
// }
//
// @Override
// public String getStatusText()
// {
// if (results.isEmpty()) {
// return "No results.";
// }
// StringBuilder buffer = new StringBuilder(1000);
// int i = 0;
// for (ISingleResult result : results) {
// if (!result.getStatusText().isEmpty()) {
// buffer.append(i + 1).append(": ");
// buffer.append(result.getStatusText()).append("\n");
// }
// i++;
// }
// String result = buffer.toString();
// if (result.isEmpty()) {
// result = "No problems.";
// }
// return result;
// }
//
// @Override
// public boolean isFallen()
// {
// return getFallenCount() > 0;
// }
//
// @Override
// public boolean hasPenalty()
// {
// return getPenaltyCount() > 0;
// }
//
// @Override
// public ISingleResult getResult(int n)
// {
// return results.get(n);
// }
// }
|
import magma.tools.benchmark.model.ISingleResult;
import magma.tools.benchmark.model.bench.TeamResult;
|
package magma.tools.benchmark.model.bench.keepawaychallenge;
public class KeepAwayBenchmarkTeamResult extends TeamResult
{
public KeepAwayBenchmarkTeamResult(String name)
{
super(name);
}
@Override
public float getAverageScore()
{
return getAverageTime();
}
public float getAverageTime()
{
if (results.isEmpty()) {
return 0;
}
float avg = 0;
|
// Path: srcTools/magma/tools/benchmark/model/ISingleResult.java
// public interface ISingleResult {
// boolean isFallen();
//
// /**
// * @return true if a penalty was assigned with this try
// */
// boolean hasPenalty();
//
// boolean isValid();
//
// String getStatusText();
// }
//
// Path: srcTools/magma/tools/benchmark/model/bench/TeamResult.java
// public abstract class TeamResult implements ITeamResult
// {
// private final String name;
//
// protected final List<ISingleResult> results;
//
// public TeamResult(String name)
// {
// this.name = name;
// results = new ArrayList<>();
// }
//
// @Override
// public void addResult(ISingleResult result)
// {
// results.add(result);
// }
//
// @Override
// public abstract float getAverageScore();
//
// @Override
// public int getFallenCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int fallen = 0;
// for (ISingleResult result : results) {
// if (result.isFallen()) {
// fallen++;
// }
// }
// return fallen;
// }
//
// @Override
// public int getPenaltyCount()
// {
// if (results.isEmpty()) {
// return 0;
// }
// int penalties = 0;
// for (ISingleResult result : results) {
// if (result.hasPenalty()) {
// penalties++;
// }
// }
// return penalties;
// }
//
// @Override
// public boolean isValid()
// {
// if (results.isEmpty()) {
// return false;
// }
// for (ISingleResult result : results) {
// if (!result.isValid()) {
// return false;
// }
// }
// return true;
// }
//
// @Override
// public int size()
// {
// return results.size();
// }
//
// @Override
// public String getName()
// {
// return name;
// }
//
// @Override
// public String getStatusText()
// {
// if (results.isEmpty()) {
// return "No results.";
// }
// StringBuilder buffer = new StringBuilder(1000);
// int i = 0;
// for (ISingleResult result : results) {
// if (!result.getStatusText().isEmpty()) {
// buffer.append(i + 1).append(": ");
// buffer.append(result.getStatusText()).append("\n");
// }
// i++;
// }
// String result = buffer.toString();
// if (result.isEmpty()) {
// result = "No problems.";
// }
// return result;
// }
//
// @Override
// public boolean isFallen()
// {
// return getFallenCount() > 0;
// }
//
// @Override
// public boolean hasPenalty()
// {
// return getPenaltyCount() > 0;
// }
//
// @Override
// public ISingleResult getResult(int n)
// {
// return results.get(n);
// }
// }
// Path: srcTools/magma/tools/benchmark/model/bench/keepawaychallenge/KeepAwayBenchmarkTeamResult.java
import magma.tools.benchmark.model.ISingleResult;
import magma.tools.benchmark.model.bench.TeamResult;
package magma.tools.benchmark.model.bench.keepawaychallenge;
public class KeepAwayBenchmarkTeamResult extends TeamResult
{
public KeepAwayBenchmarkTeamResult(String name)
{
super(name);
}
@Override
public float getAverageScore()
{
return getAverageTime();
}
public float getAverageTime()
{
if (results.isEmpty()) {
return 0;
}
float avg = 0;
|
for (ISingleResult result : results) {
|
Codpoe/OnlyWeather
|
app/src/main/java/me/codpoe/onlyweather/ui/fragment/ForecastFragment.java
|
// Path: app/src/main/java/me/codpoe/onlyweather/ui/adapter/ForecastRvAdapter.java
// public class ForecastRvAdapter extends RecyclerView.Adapter {
//
// private Context mContext;
// private WeatherBean mWeathrData;
//
// public ForecastRvAdapter(Context context, WeatherBean weatherBean) {
// mContext = context;
// mWeathrData = weatherBean;
// }
//
// @Override
// public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return new ForecastViewHolder(LayoutInflater.from(mContext)
// .inflate(R.layout.forecast_rv_item, parent, false));
// }
//
// @Override
// public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// try {
// ((ForecastViewHolder) holder).mWeekText.setText(
// String.format("%s",
// Utils.dateToWeek(mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getDate()))
// );
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// ((ForecastViewHolder) holder).mCondText.setText(
// String.format("%s", mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getCond().getTxtD())
// );
// ((ForecastViewHolder) holder).mTmpText.setText(
// String.format("%s ~ %s", mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getTmp().getMin(),
// mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getTmp().getMax())
// );
//
// ((ForecastViewHolder) holder).mHumText.setText(
// String.format("湿度: %s", mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getHum())
// );
// ((ForecastViewHolder) holder).mWindText.setText(
// String.format("%s %s", mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getWind().getDir(),
// mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getWind().getSc())
// );
// ((ForecastViewHolder) holder).mRainText.setText(
// String.format("降水概率: %s", mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getPop())
// );
// ((ForecastViewHolder) holder).mVisText.setText(
// String.format("能见度: %s km", mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getVis())
// );
// }
//
// @Override
// public int getItemCount() {
// return mWeathrData.getHeWeatherDataService().get(0).getDailyForecast().size();
// }
//
// static class ForecastViewHolder extends RecyclerView.ViewHolder{
//
// private TextView mWeekText;
// private TextView mCondText;
// private TextView mTmpText;
// private TextView mHumText;
// private TextView mWindText;
// private TextView mRainText;
// private TextView mVisText;
//
// public ForecastViewHolder(View itemView) {
// super(itemView);
// mWeekText = (TextView) itemView.findViewById(R.id.forecast_date_text);
// mCondText = (TextView) itemView.findViewById(R.id.forecast_cond_text);
// mTmpText = (TextView) itemView.findViewById(R.id.forecast_tmp_text);
// mHumText = (TextView) itemView.findViewById(R.id.forecast_hum_text);
// mWindText = (TextView) itemView.findViewById(R.id.forecast_wind_text);
// mRainText = (TextView) itemView.findViewById(R.id.forecast_rain_text);
// mVisText = (TextView) itemView.findViewById(R.id.forecast_vis_text);
// }
// }
//
// }
|
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter;
import me.codpoe.onlyweather.R;
import me.codpoe.onlyweather.model.entity.WeatherBean;
import me.codpoe.onlyweather.ui.adapter.ForecastRvAdapter;
|
package me.codpoe.onlyweather.ui.fragment;
/**
* Created by Codpoe on 2016/5/13.
*/
public class ForecastFragment extends Fragment {
private View view;
private RecyclerView mMoreRecyclerView;
|
// Path: app/src/main/java/me/codpoe/onlyweather/ui/adapter/ForecastRvAdapter.java
// public class ForecastRvAdapter extends RecyclerView.Adapter {
//
// private Context mContext;
// private WeatherBean mWeathrData;
//
// public ForecastRvAdapter(Context context, WeatherBean weatherBean) {
// mContext = context;
// mWeathrData = weatherBean;
// }
//
// @Override
// public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return new ForecastViewHolder(LayoutInflater.from(mContext)
// .inflate(R.layout.forecast_rv_item, parent, false));
// }
//
// @Override
// public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// try {
// ((ForecastViewHolder) holder).mWeekText.setText(
// String.format("%s",
// Utils.dateToWeek(mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getDate()))
// );
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// ((ForecastViewHolder) holder).mCondText.setText(
// String.format("%s", mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getCond().getTxtD())
// );
// ((ForecastViewHolder) holder).mTmpText.setText(
// String.format("%s ~ %s", mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getTmp().getMin(),
// mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getTmp().getMax())
// );
//
// ((ForecastViewHolder) holder).mHumText.setText(
// String.format("湿度: %s", mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getHum())
// );
// ((ForecastViewHolder) holder).mWindText.setText(
// String.format("%s %s", mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getWind().getDir(),
// mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getWind().getSc())
// );
// ((ForecastViewHolder) holder).mRainText.setText(
// String.format("降水概率: %s", mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getPop())
// );
// ((ForecastViewHolder) holder).mVisText.setText(
// String.format("能见度: %s km", mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
// .get(position).getVis())
// );
// }
//
// @Override
// public int getItemCount() {
// return mWeathrData.getHeWeatherDataService().get(0).getDailyForecast().size();
// }
//
// static class ForecastViewHolder extends RecyclerView.ViewHolder{
//
// private TextView mWeekText;
// private TextView mCondText;
// private TextView mTmpText;
// private TextView mHumText;
// private TextView mWindText;
// private TextView mRainText;
// private TextView mVisText;
//
// public ForecastViewHolder(View itemView) {
// super(itemView);
// mWeekText = (TextView) itemView.findViewById(R.id.forecast_date_text);
// mCondText = (TextView) itemView.findViewById(R.id.forecast_cond_text);
// mTmpText = (TextView) itemView.findViewById(R.id.forecast_tmp_text);
// mHumText = (TextView) itemView.findViewById(R.id.forecast_hum_text);
// mWindText = (TextView) itemView.findViewById(R.id.forecast_wind_text);
// mRainText = (TextView) itemView.findViewById(R.id.forecast_rain_text);
// mVisText = (TextView) itemView.findViewById(R.id.forecast_vis_text);
// }
// }
//
// }
// Path: app/src/main/java/me/codpoe/onlyweather/ui/fragment/ForecastFragment.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter;
import me.codpoe.onlyweather.R;
import me.codpoe.onlyweather.model.entity.WeatherBean;
import me.codpoe.onlyweather.ui.adapter.ForecastRvAdapter;
package me.codpoe.onlyweather.ui.fragment;
/**
* Created by Codpoe on 2016/5/13.
*/
public class ForecastFragment extends Fragment {
private View view;
private RecyclerView mMoreRecyclerView;
|
private ForecastRvAdapter mForecastRvAdapter;
|
Codpoe/OnlyWeather
|
app/src/main/java/me/codpoe/onlyweather/ui/adapter/ForecastRvAdapter.java
|
// Path: app/src/main/java/me/codpoe/onlyweather/util/Utils.java
// public class Utils {
//
// // 日期转星期
// public static String dateToWeek(String pTime) throws Exception {
// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
// Calendar c = Calendar.getInstance();
// c.setTime(format.parse(pTime));
// int dayForWeek = 0;
// String week = "";
// dayForWeek = c.get(Calendar.DAY_OF_WEEK);
// switch (dayForWeek) {
// case 1:
// week = "周日";
// break;
// case 2:
// week = "周一";
// break;
// case 3:
// week = "周二";
// break;
// case 4:
// week = "周三";
// break;
// case 5:
// week = "周四";
// break;
// case 6:
// week = "周五";
// break;
// case 7:
// week = "周六";
// break;
// }
// return week;
// }
//
// // 通过星座名,返回星座图片 id
// public static int getConsImg(String consName) {
// switch (consName) {
// case "白羊座":
// return R.drawable.ic_bai_yang;
// case "金牛座":
// return R.drawable.ic_jin_niu;
// case "双子座":
// return R.drawable.ic_shuang_zi;
// case "巨蟹座":
// return R.drawable.ic_ju_xie;
// case "狮子座":
// return R.drawable.ic_shi_zi;
// case "处女座":
// return R.drawable.ic_chu_nv;
// case "天秤座":
// return R.drawable.ic_tian_ping;
// case "天蝎座":
// return R.drawable.ic_tian_xie;
// case "射手座":
// return R.drawable.ic_sagittarius;
// case "摩羯座":
// return R.drawable.ic_mo_jie;
// case "水瓶座":
// return R.drawable.ic_shui_ping;
// case "双鱼座":
// return R.drawable.ic_shuang_yu;
// default:
// return 0;
//
// }
// }
//
// // 正则表达式匹配百分数中的数字,例如:从 “75%” 中提取 “75”,并返回对应的星数
// public static float getRatingFromPercent(String percent) {
// Pattern p = Pattern.compile("[0-9]*");
// Matcher m = p.matcher(percent);
// if (m.find()) {
// return Float.valueOf(m.group()) / 20f;
// }
// return 2.5f;
// }
//
// // 正则表达式过滤高德地图定位获取的城市中的“市”,例如:从“广州市”中去掉“市”
// public static String getCityNameFromAMap(String cityName) {
// Pattern p = Pattern.compile("[\u5e02]");
// Matcher m = p.matcher(cityName);
// if (m.find()) {
// return m.replaceAll("");
// }
// return cityName;
// }
// }
|
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import me.codpoe.onlyweather.R;
import me.codpoe.onlyweather.model.entity.WeatherBean;
import me.codpoe.onlyweather.util.Utils;
|
package me.codpoe.onlyweather.ui.adapter;
/**
* Created by Codpoe on 2016/5/22.
*/
public class ForecastRvAdapter extends RecyclerView.Adapter {
private Context mContext;
private WeatherBean mWeathrData;
public ForecastRvAdapter(Context context, WeatherBean weatherBean) {
mContext = context;
mWeathrData = weatherBean;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ForecastViewHolder(LayoutInflater.from(mContext)
.inflate(R.layout.forecast_rv_item, parent, false));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try {
((ForecastViewHolder) holder).mWeekText.setText(
String.format("%s",
|
// Path: app/src/main/java/me/codpoe/onlyweather/util/Utils.java
// public class Utils {
//
// // 日期转星期
// public static String dateToWeek(String pTime) throws Exception {
// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
// Calendar c = Calendar.getInstance();
// c.setTime(format.parse(pTime));
// int dayForWeek = 0;
// String week = "";
// dayForWeek = c.get(Calendar.DAY_OF_WEEK);
// switch (dayForWeek) {
// case 1:
// week = "周日";
// break;
// case 2:
// week = "周一";
// break;
// case 3:
// week = "周二";
// break;
// case 4:
// week = "周三";
// break;
// case 5:
// week = "周四";
// break;
// case 6:
// week = "周五";
// break;
// case 7:
// week = "周六";
// break;
// }
// return week;
// }
//
// // 通过星座名,返回星座图片 id
// public static int getConsImg(String consName) {
// switch (consName) {
// case "白羊座":
// return R.drawable.ic_bai_yang;
// case "金牛座":
// return R.drawable.ic_jin_niu;
// case "双子座":
// return R.drawable.ic_shuang_zi;
// case "巨蟹座":
// return R.drawable.ic_ju_xie;
// case "狮子座":
// return R.drawable.ic_shi_zi;
// case "处女座":
// return R.drawable.ic_chu_nv;
// case "天秤座":
// return R.drawable.ic_tian_ping;
// case "天蝎座":
// return R.drawable.ic_tian_xie;
// case "射手座":
// return R.drawable.ic_sagittarius;
// case "摩羯座":
// return R.drawable.ic_mo_jie;
// case "水瓶座":
// return R.drawable.ic_shui_ping;
// case "双鱼座":
// return R.drawable.ic_shuang_yu;
// default:
// return 0;
//
// }
// }
//
// // 正则表达式匹配百分数中的数字,例如:从 “75%” 中提取 “75”,并返回对应的星数
// public static float getRatingFromPercent(String percent) {
// Pattern p = Pattern.compile("[0-9]*");
// Matcher m = p.matcher(percent);
// if (m.find()) {
// return Float.valueOf(m.group()) / 20f;
// }
// return 2.5f;
// }
//
// // 正则表达式过滤高德地图定位获取的城市中的“市”,例如:从“广州市”中去掉“市”
// public static String getCityNameFromAMap(String cityName) {
// Pattern p = Pattern.compile("[\u5e02]");
// Matcher m = p.matcher(cityName);
// if (m.find()) {
// return m.replaceAll("");
// }
// return cityName;
// }
// }
// Path: app/src/main/java/me/codpoe/onlyweather/ui/adapter/ForecastRvAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import me.codpoe.onlyweather.R;
import me.codpoe.onlyweather.model.entity.WeatherBean;
import me.codpoe.onlyweather.util.Utils;
package me.codpoe.onlyweather.ui.adapter;
/**
* Created by Codpoe on 2016/5/22.
*/
public class ForecastRvAdapter extends RecyclerView.Adapter {
private Context mContext;
private WeatherBean mWeathrData;
public ForecastRvAdapter(Context context, WeatherBean weatherBean) {
mContext = context;
mWeathrData = weatherBean;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ForecastViewHolder(LayoutInflater.from(mContext)
.inflate(R.layout.forecast_rv_item, parent, false));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try {
((ForecastViewHolder) holder).mWeekText.setText(
String.format("%s",
|
Utils.dateToWeek(mWeathrData.getHeWeatherDataService().get(0).getDailyForecast()
|
Codpoe/OnlyWeather
|
app/src/main/java/me/codpoe/onlyweather/util/SettingUtils.java
|
// Path: app/src/main/java/me/codpoe/onlyweather/base/BaseApplication.java
// public class BaseApplication extends Application {
//
// public static Context mAppContext = null;
//
// @Override
// public void onCreate() {
// super.onCreate();
// mAppContext = getApplicationContext();
// FIR.init(this);
// }
//
// public static Context getAppContext() {
// return mAppContext;
// }
//
// }
|
import android.content.Context;
import android.content.SharedPreferences;
import me.codpoe.onlyweather.base.BaseApplication;
|
package me.codpoe.onlyweather.util;
/**
* Created by Codpoe on 2016/5/23.
*/
public class SettingUtils {
private static SettingUtils mSettingUtils;
private SharedPreferences mPrefs;
// 私有化构造方法
private SettingUtils() {
|
// Path: app/src/main/java/me/codpoe/onlyweather/base/BaseApplication.java
// public class BaseApplication extends Application {
//
// public static Context mAppContext = null;
//
// @Override
// public void onCreate() {
// super.onCreate();
// mAppContext = getApplicationContext();
// FIR.init(this);
// }
//
// public static Context getAppContext() {
// return mAppContext;
// }
//
// }
// Path: app/src/main/java/me/codpoe/onlyweather/util/SettingUtils.java
import android.content.Context;
import android.content.SharedPreferences;
import me.codpoe.onlyweather.base.BaseApplication;
package me.codpoe.onlyweather.util;
/**
* Created by Codpoe on 2016/5/23.
*/
public class SettingUtils {
private static SettingUtils mSettingUtils;
private SharedPreferences mPrefs;
// 私有化构造方法
private SettingUtils() {
|
mPrefs = BaseApplication.getAppContext().getSharedPreferences("setting", Context.MODE_PRIVATE);
|
Codpoe/OnlyWeather
|
app/src/main/java/me/codpoe/onlyweather/ui/activity/AboutActivity.java
|
// Path: app/src/main/java/me/codpoe/onlyweather/ui/fragment/AboutFragment.java
// public class AboutFragment extends PreferenceFragment implements Preference.OnPreferenceClickListener{
//
// private Preference mIntroductionPref;
// private Preference mCheckVersionPref;
// private Preference mStarPref;
// private Preference mMePref;
// private Preference mSupportPref;
// private Preference mFeedbackPref;
// private Preference mWeatherApiPref;
// private Preference mImagePref;
// private Preference mOpenSourcePref;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// addPreferencesFromResource(R.xml.about);
//
// findPreferences();
//
// mIntroductionPref.setOnPreferenceClickListener(this);
// mCheckVersionPref.setOnPreferenceClickListener(this);
// mStarPref.setOnPreferenceClickListener(this);
// mMePref.setOnPreferenceClickListener(this);
// mSupportPref.setOnPreferenceClickListener(this);
// mFeedbackPref.setOnPreferenceClickListener(this);
// mWeatherApiPref.setOnPreferenceClickListener(this);
// mImagePref.setOnPreferenceClickListener(this);
// mOpenSourcePref.setOnPreferenceClickListener(this);
//
// mCheckVersionPref.setSummary("当前版本: " + VersionUtils.getCurVersion(getActivity()));
//
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// }
//
// public void findPreferences() {
// mIntroductionPref = findPreference("introduction");
// mCheckVersionPref = findPreference("check_version");
// mStarPref = findPreference("star");
// mMePref = findPreference("me");
// mSupportPref = findPreference("support");
// mFeedbackPref = findPreference("feedback");
// mWeatherApiPref = findPreference("data_source");
// mImagePref = findPreference("img_source");
// mOpenSourcePref = findPreference("open_source");
// }
//
// @Override
// public boolean onPreferenceClick(Preference preference) {
// switch (preference.getKey()) {
// case "introduction":
// DialogUtils.showIntroduction(getActivity());
// break;
// case "check_version":
// VersionUtils.checkVersion(getActivity());
// break;
// case "star":
// DialogUtils.showStar(getActivity());
// break;
// case "me":
// DialogUtils.showMe(getActivity());
// break;
// case "support":
// DialogUtils.showSupport(getActivity());
// break;
// case "feedback":
// ClipboardManager clipboardManager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
// clipboardManager.setPrimaryClip(ClipData.newPlainText(null, "[email protected]"));
// Snackbar.make(getView(), "复制成功", Snackbar.LENGTH_SHORT).show();
// break;
// case "data_source":
// DialogUtils.showDataSource(getActivity());
// break;
// case "img_source":
// Uri uri1 = Uri.parse("http://www.coolapk.com/apk/com.backdrops.wallpapers");
// Intent intent1 = new Intent();
// intent1.setAction(Intent.ACTION_VIEW);
// intent1.setData(uri1);
// getActivity().startActivity(intent1);
// break;
// case "open_source":
// DialogUtils.showOpenSource(getActivity());
// break;
// }
// return false;
// }
// }
|
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import me.codpoe.onlyweather.R;
import me.codpoe.onlyweather.ui.fragment.AboutFragment;
|
package me.codpoe.onlyweather.ui.activity;
/**
* Created by Codpoe on 2016/5/23.
*/
public class AboutActivity extends AppCompatActivity{
private CoordinatorLayout mCoordinatorLayout;
private Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
findViews();
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
getFragmentManager().beginTransaction()
|
// Path: app/src/main/java/me/codpoe/onlyweather/ui/fragment/AboutFragment.java
// public class AboutFragment extends PreferenceFragment implements Preference.OnPreferenceClickListener{
//
// private Preference mIntroductionPref;
// private Preference mCheckVersionPref;
// private Preference mStarPref;
// private Preference mMePref;
// private Preference mSupportPref;
// private Preference mFeedbackPref;
// private Preference mWeatherApiPref;
// private Preference mImagePref;
// private Preference mOpenSourcePref;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// addPreferencesFromResource(R.xml.about);
//
// findPreferences();
//
// mIntroductionPref.setOnPreferenceClickListener(this);
// mCheckVersionPref.setOnPreferenceClickListener(this);
// mStarPref.setOnPreferenceClickListener(this);
// mMePref.setOnPreferenceClickListener(this);
// mSupportPref.setOnPreferenceClickListener(this);
// mFeedbackPref.setOnPreferenceClickListener(this);
// mWeatherApiPref.setOnPreferenceClickListener(this);
// mImagePref.setOnPreferenceClickListener(this);
// mOpenSourcePref.setOnPreferenceClickListener(this);
//
// mCheckVersionPref.setSummary("当前版本: " + VersionUtils.getCurVersion(getActivity()));
//
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// }
//
// public void findPreferences() {
// mIntroductionPref = findPreference("introduction");
// mCheckVersionPref = findPreference("check_version");
// mStarPref = findPreference("star");
// mMePref = findPreference("me");
// mSupportPref = findPreference("support");
// mFeedbackPref = findPreference("feedback");
// mWeatherApiPref = findPreference("data_source");
// mImagePref = findPreference("img_source");
// mOpenSourcePref = findPreference("open_source");
// }
//
// @Override
// public boolean onPreferenceClick(Preference preference) {
// switch (preference.getKey()) {
// case "introduction":
// DialogUtils.showIntroduction(getActivity());
// break;
// case "check_version":
// VersionUtils.checkVersion(getActivity());
// break;
// case "star":
// DialogUtils.showStar(getActivity());
// break;
// case "me":
// DialogUtils.showMe(getActivity());
// break;
// case "support":
// DialogUtils.showSupport(getActivity());
// break;
// case "feedback":
// ClipboardManager clipboardManager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
// clipboardManager.setPrimaryClip(ClipData.newPlainText(null, "[email protected]"));
// Snackbar.make(getView(), "复制成功", Snackbar.LENGTH_SHORT).show();
// break;
// case "data_source":
// DialogUtils.showDataSource(getActivity());
// break;
// case "img_source":
// Uri uri1 = Uri.parse("http://www.coolapk.com/apk/com.backdrops.wallpapers");
// Intent intent1 = new Intent();
// intent1.setAction(Intent.ACTION_VIEW);
// intent1.setData(uri1);
// getActivity().startActivity(intent1);
// break;
// case "open_source":
// DialogUtils.showOpenSource(getActivity());
// break;
// }
// return false;
// }
// }
// Path: app/src/main/java/me/codpoe/onlyweather/ui/activity/AboutActivity.java
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import me.codpoe.onlyweather.R;
import me.codpoe.onlyweather.ui.fragment.AboutFragment;
package me.codpoe.onlyweather.ui.activity;
/**
* Created by Codpoe on 2016/5/23.
*/
public class AboutActivity extends AppCompatActivity{
private CoordinatorLayout mCoordinatorLayout;
private Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
findViews();
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
getFragmentManager().beginTransaction()
|
.replace(R.id.about_frame, new AboutFragment())
|
Codpoe/OnlyWeather
|
app/src/main/java/me/codpoe/onlyweather/db/OnlyWeatherDB.java
|
// Path: app/src/main/java/me/codpoe/onlyweather/model/City.java
// public class City {
// private int id;
// private String cityName;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getCityName() {
// return cityName;
// }
//
// public void setCityName(String cityName) {
// this.cityName = cityName;
// }
// }
|
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import me.codpoe.onlyweather.model.City;
|
package me.codpoe.onlyweather.db;
/**
* Created by Codpoe on 2016/5/12.
*/
public class OnlyWeatherDB {
// 数据库名
public static final String DB_NAME = "only_weather";
// 数据库版本
public static final int VERSION = 1;
private static OnlyWeatherDB sOnlyWeatherDB;
private SQLiteDatabase mSQLiteDatabase;
// 构造方法私有化
private OnlyWeatherDB(Context context) {
OnlyWeatherOpenHelper dbHelper = new OnlyWeatherOpenHelper(context,
DB_NAME, null, VERSION);
mSQLiteDatabase = dbHelper.getWritableDatabase();
}
/**
* 对外的方法
*/
// 获取 OnlyWeatherDB 的实例
public synchronized static OnlyWeatherDB getInstance(Context context) {
if(sOnlyWeatherDB == null) {
sOnlyWeatherDB = new OnlyWeatherDB(context);
}
return sOnlyWeatherDB;
}
// 将 City 实例存储到数据库
|
// Path: app/src/main/java/me/codpoe/onlyweather/model/City.java
// public class City {
// private int id;
// private String cityName;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getCityName() {
// return cityName;
// }
//
// public void setCityName(String cityName) {
// this.cityName = cityName;
// }
// }
// Path: app/src/main/java/me/codpoe/onlyweather/db/OnlyWeatherDB.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import me.codpoe.onlyweather.model.City;
package me.codpoe.onlyweather.db;
/**
* Created by Codpoe on 2016/5/12.
*/
public class OnlyWeatherDB {
// 数据库名
public static final String DB_NAME = "only_weather";
// 数据库版本
public static final int VERSION = 1;
private static OnlyWeatherDB sOnlyWeatherDB;
private SQLiteDatabase mSQLiteDatabase;
// 构造方法私有化
private OnlyWeatherDB(Context context) {
OnlyWeatherOpenHelper dbHelper = new OnlyWeatherOpenHelper(context,
DB_NAME, null, VERSION);
mSQLiteDatabase = dbHelper.getWritableDatabase();
}
/**
* 对外的方法
*/
// 获取 OnlyWeatherDB 的实例
public synchronized static OnlyWeatherDB getInstance(Context context) {
if(sOnlyWeatherDB == null) {
sOnlyWeatherDB = new OnlyWeatherDB(context);
}
return sOnlyWeatherDB;
}
// 将 City 实例存储到数据库
|
public Boolean saveCity(City city) {
|
cm-heclouds/AndroidSDK
|
onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/Trigger.java
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
|
import com.chinamobile.iot.onenet.http.Urls;
import okhttp3.HttpUrl;
|
package com.chinamobile.iot.onenet.module;
public class Trigger {
public static String urlForAdding() {
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/Trigger.java
import com.chinamobile.iot.onenet.http.Urls;
import okhttp3.HttpUrl;
package com.chinamobile.iot.onenet.module;
public class Trigger {
public static String urlForAdding() {
|
return new HttpUrl.Builder().scheme(Urls.sScheme).host(Urls.sHost).addPathSegment("triggers")
|
cm-heclouds/AndroidSDK
|
onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/Command.java
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
|
import com.chinamobile.iot.onenet.http.Urls;
import okhttp3.HttpUrl;
|
package com.chinamobile.iot.onenet.module;
public class Command {
public enum CommandType {
TYPE_CMD_REQ, TYPE_PUSH_DATA
}
public static String urlForSending(String deviceId) {
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/Command.java
import com.chinamobile.iot.onenet.http.Urls;
import okhttp3.HttpUrl;
package com.chinamobile.iot.onenet.module;
public class Command {
public enum CommandType {
TYPE_CMD_REQ, TYPE_PUSH_DATA
}
public static String urlForSending(String deviceId) {
|
return new HttpUrl.Builder().scheme(Urls.sScheme).host(Urls.sHost).addPathSegment("cmds")
|
cm-heclouds/AndroidSDK
|
onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/Mqtt.java
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
|
import com.chinamobile.iot.onenet.http.Urls;
import okhttp3.HttpUrl;
|
package com.chinamobile.iot.onenet.module;
public class Mqtt {
public static String urlForSendingCmdByTopic(String topic) {
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/Mqtt.java
import com.chinamobile.iot.onenet.http.Urls;
import okhttp3.HttpUrl;
package com.chinamobile.iot.onenet.module;
public class Mqtt {
public static String urlForSendingCmdByTopic(String topic) {
|
return new HttpUrl.Builder().scheme(Urls.sScheme).host(Urls.sHost).addPathSegment("mqtt")
|
cm-heclouds/AndroidSDK
|
onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/DataStream.java
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
|
import com.chinamobile.iot.onenet.http.Urls;
import okhttp3.HttpUrl;
|
package com.chinamobile.iot.onenet.module;
public class DataStream {
public static String urlForAdding(String deviceId) {
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/DataStream.java
import com.chinamobile.iot.onenet.http.Urls;
import okhttp3.HttpUrl;
package com.chinamobile.iot.onenet.module;
public class DataStream {
public static String urlForAdding(String deviceId) {
|
return new HttpUrl.Builder().scheme(Urls.sScheme).host(Urls.sHost).addPathSegment("devices")
|
cm-heclouds/AndroidSDK
|
onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/Device.java
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
|
import com.chinamobile.iot.onenet.http.Urls;
import java.util.Iterator;
import java.util.Map;
import okhttp3.HttpUrl;
|
package com.chinamobile.iot.onenet.module;
public class Device {
public static String urlForRegistering(String registerCode) {
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/Device.java
import com.chinamobile.iot.onenet.http.Urls;
import java.util.Iterator;
import java.util.Map;
import okhttp3.HttpUrl;
package com.chinamobile.iot.onenet.module;
public class Device {
public static String urlForRegistering(String registerCode) {
|
return new HttpUrl.Builder().scheme(Urls.sScheme).host(Urls.sHost).addPathSegment("register_de")
|
cm-heclouds/AndroidSDK
|
onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/DataPoint.java
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
|
import com.chinamobile.iot.onenet.http.Urls;
import java.util.Iterator;
import java.util.Map;
import okhttp3.HttpUrl;
|
package com.chinamobile.iot.onenet.module;
public class DataPoint {
public static String urlForAdding(String deviceId, String type) {
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/DataPoint.java
import com.chinamobile.iot.onenet.http.Urls;
import java.util.Iterator;
import java.util.Map;
import okhttp3.HttpUrl;
package com.chinamobile.iot.onenet.module;
public class DataPoint {
public static String urlForAdding(String deviceId, String type) {
|
HttpUrl.Builder builder = new HttpUrl.Builder().scheme(Urls.sScheme).host(Urls.sHost)
|
cm-heclouds/AndroidSDK
|
onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/ApiKey.java
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
|
import com.chinamobile.iot.onenet.http.Urls;
import okhttp3.HttpUrl;
|
package com.chinamobile.iot.onenet.module;
public class ApiKey {
public static String urlForAdding() {
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/ApiKey.java
import com.chinamobile.iot.onenet.http.Urls;
import okhttp3.HttpUrl;
package com.chinamobile.iot.onenet.module;
public class ApiKey {
public static String urlForAdding() {
|
return new HttpUrl.Builder().scheme(Urls.sScheme).host(Urls.sHost).addPathSegment("keys").toString();
|
cm-heclouds/AndroidSDK
|
app/src/main/java/com/chinamobile/iot/onenet/sdksample/utils/DeviceItemDeserializer.java
|
// Path: app/src/main/java/com/chinamobile/iot/onenet/sdksample/model/ActivateCode.java
// public class ActivateCode implements Serializable {
//
// private String mt;
// private String mid;
//
// public String getMt() {
// return mt;
// }
//
// public void setMt(String mt) {
// this.mt = mt;
// }
//
// public String getMid() {
// return mid;
// }
//
// public void setMid(String mid) {
// this.mid = mid;
// }
// }
//
// Path: app/src/main/java/com/chinamobile/iot/onenet/sdksample/model/DeviceItem.java
// public class DeviceItem implements Serializable {
// private String id;
// private String title;
// private String desc;
// @SerializedName("private")
// private boolean isPrivate;
// private String protocol = "HTTP";
// private boolean online;
// private Location location;
// @SerializedName("create_time")
// private String createTime;
// @SerializedName("auth_info")
// private String authInfo;
// @SerializedName("activite_code")
// private ActivateCode activateCode;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public boolean isPrivate() {
// return isPrivate;
// }
//
// public void setPrivate(boolean aPrivate) {
// isPrivate = aPrivate;
// }
//
// public String getProtocol() {
// return protocol;
// }
//
// public void setProtocol(String protocol) {
// this.protocol = protocol;
// }
//
// public boolean isOnline() {
// return online;
// }
//
// public void setOnline(boolean online) {
// this.online = online;
// }
//
// public Location getLocation() {
// return location;
// }
//
// public void setLocation(Location location) {
// this.location = location;
// }
//
// public String getCreateTime() {
// return createTime;
// }
//
// public void setCreateTime(String createTime) {
// this.createTime = createTime;
// }
//
// public String getAuthInfo() {
// return authInfo;
// }
//
// public void setAuthInfo(String authInfo) {
// this.authInfo = authInfo;
// }
//
// public ActivateCode getActivateCode() {
// return activateCode;
// }
//
// public void setActivateCode(ActivateCode activateCode) {
// this.activateCode = activateCode;
// }
// }
//
// Path: app/src/main/java/com/chinamobile/iot/onenet/sdksample/model/Location.java
// public class Location implements Serializable {
//
// private String lon;
// private String lat;
//
// public String getLon() {
// return lon;
// }
//
// public void setLon(String lon) {
// this.lon = lon;
// }
//
// public String getLat() {
// return lat;
// }
//
// public void setLat(String lat) {
// this.lat = lat;
// }
// }
|
import com.chinamobile.iot.onenet.sdksample.model.ActivateCode;
import com.chinamobile.iot.onenet.sdksample.model.DeviceItem;
import com.chinamobile.iot.onenet.sdksample.model.Location;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
|
package com.chinamobile.iot.onenet.sdksample.utils;
public class DeviceItemDeserializer implements JsonDeserializer<DeviceItem> {
@Override
public DeviceItem deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
DeviceItem deviceItem = new DeviceItem();
deviceItem.setId(jsonObject.get("id").getAsString());
deviceItem.setTitle(jsonObject.get("title").getAsString());
JsonElement desc = jsonObject.get("desc");
deviceItem.setDesc(desc != null ? desc.getAsString() : "");
JsonElement isPrivate = jsonObject.get("private");
deviceItem.setPrivate(isPrivate != null ? isPrivate.getAsBoolean() : true);
JsonElement protocol = jsonObject.get("protocol");
deviceItem.setProtocol(protocol != null ? protocol.getAsString() : "HTTP");
deviceItem.setOnline(jsonObject.get("online").getAsBoolean());
JsonElement locationElement = jsonObject.get("location");
if (locationElement != null) {
JsonObject locationObject = locationElement.getAsJsonObject();
if (locationObject != null) {
|
// Path: app/src/main/java/com/chinamobile/iot/onenet/sdksample/model/ActivateCode.java
// public class ActivateCode implements Serializable {
//
// private String mt;
// private String mid;
//
// public String getMt() {
// return mt;
// }
//
// public void setMt(String mt) {
// this.mt = mt;
// }
//
// public String getMid() {
// return mid;
// }
//
// public void setMid(String mid) {
// this.mid = mid;
// }
// }
//
// Path: app/src/main/java/com/chinamobile/iot/onenet/sdksample/model/DeviceItem.java
// public class DeviceItem implements Serializable {
// private String id;
// private String title;
// private String desc;
// @SerializedName("private")
// private boolean isPrivate;
// private String protocol = "HTTP";
// private boolean online;
// private Location location;
// @SerializedName("create_time")
// private String createTime;
// @SerializedName("auth_info")
// private String authInfo;
// @SerializedName("activite_code")
// private ActivateCode activateCode;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public boolean isPrivate() {
// return isPrivate;
// }
//
// public void setPrivate(boolean aPrivate) {
// isPrivate = aPrivate;
// }
//
// public String getProtocol() {
// return protocol;
// }
//
// public void setProtocol(String protocol) {
// this.protocol = protocol;
// }
//
// public boolean isOnline() {
// return online;
// }
//
// public void setOnline(boolean online) {
// this.online = online;
// }
//
// public Location getLocation() {
// return location;
// }
//
// public void setLocation(Location location) {
// this.location = location;
// }
//
// public String getCreateTime() {
// return createTime;
// }
//
// public void setCreateTime(String createTime) {
// this.createTime = createTime;
// }
//
// public String getAuthInfo() {
// return authInfo;
// }
//
// public void setAuthInfo(String authInfo) {
// this.authInfo = authInfo;
// }
//
// public ActivateCode getActivateCode() {
// return activateCode;
// }
//
// public void setActivateCode(ActivateCode activateCode) {
// this.activateCode = activateCode;
// }
// }
//
// Path: app/src/main/java/com/chinamobile/iot/onenet/sdksample/model/Location.java
// public class Location implements Serializable {
//
// private String lon;
// private String lat;
//
// public String getLon() {
// return lon;
// }
//
// public void setLon(String lon) {
// this.lon = lon;
// }
//
// public String getLat() {
// return lat;
// }
//
// public void setLat(String lat) {
// this.lat = lat;
// }
// }
// Path: app/src/main/java/com/chinamobile/iot/onenet/sdksample/utils/DeviceItemDeserializer.java
import com.chinamobile.iot.onenet.sdksample.model.ActivateCode;
import com.chinamobile.iot.onenet.sdksample.model.DeviceItem;
import com.chinamobile.iot.onenet.sdksample.model.Location;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
package com.chinamobile.iot.onenet.sdksample.utils;
public class DeviceItemDeserializer implements JsonDeserializer<DeviceItem> {
@Override
public DeviceItem deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
DeviceItem deviceItem = new DeviceItem();
deviceItem.setId(jsonObject.get("id").getAsString());
deviceItem.setTitle(jsonObject.get("title").getAsString());
JsonElement desc = jsonObject.get("desc");
deviceItem.setDesc(desc != null ? desc.getAsString() : "");
JsonElement isPrivate = jsonObject.get("private");
deviceItem.setPrivate(isPrivate != null ? isPrivate.getAsBoolean() : true);
JsonElement protocol = jsonObject.get("protocol");
deviceItem.setProtocol(protocol != null ? protocol.getAsString() : "HTTP");
deviceItem.setOnline(jsonObject.get("online").getAsBoolean());
JsonElement locationElement = jsonObject.get("location");
if (locationElement != null) {
JsonObject locationObject = locationElement.getAsJsonObject();
if (locationObject != null) {
|
Location location = new Location();
|
cm-heclouds/AndroidSDK
|
app/src/main/java/com/chinamobile/iot/onenet/sdksample/utils/DeviceItemDeserializer.java
|
// Path: app/src/main/java/com/chinamobile/iot/onenet/sdksample/model/ActivateCode.java
// public class ActivateCode implements Serializable {
//
// private String mt;
// private String mid;
//
// public String getMt() {
// return mt;
// }
//
// public void setMt(String mt) {
// this.mt = mt;
// }
//
// public String getMid() {
// return mid;
// }
//
// public void setMid(String mid) {
// this.mid = mid;
// }
// }
//
// Path: app/src/main/java/com/chinamobile/iot/onenet/sdksample/model/DeviceItem.java
// public class DeviceItem implements Serializable {
// private String id;
// private String title;
// private String desc;
// @SerializedName("private")
// private boolean isPrivate;
// private String protocol = "HTTP";
// private boolean online;
// private Location location;
// @SerializedName("create_time")
// private String createTime;
// @SerializedName("auth_info")
// private String authInfo;
// @SerializedName("activite_code")
// private ActivateCode activateCode;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public boolean isPrivate() {
// return isPrivate;
// }
//
// public void setPrivate(boolean aPrivate) {
// isPrivate = aPrivate;
// }
//
// public String getProtocol() {
// return protocol;
// }
//
// public void setProtocol(String protocol) {
// this.protocol = protocol;
// }
//
// public boolean isOnline() {
// return online;
// }
//
// public void setOnline(boolean online) {
// this.online = online;
// }
//
// public Location getLocation() {
// return location;
// }
//
// public void setLocation(Location location) {
// this.location = location;
// }
//
// public String getCreateTime() {
// return createTime;
// }
//
// public void setCreateTime(String createTime) {
// this.createTime = createTime;
// }
//
// public String getAuthInfo() {
// return authInfo;
// }
//
// public void setAuthInfo(String authInfo) {
// this.authInfo = authInfo;
// }
//
// public ActivateCode getActivateCode() {
// return activateCode;
// }
//
// public void setActivateCode(ActivateCode activateCode) {
// this.activateCode = activateCode;
// }
// }
//
// Path: app/src/main/java/com/chinamobile/iot/onenet/sdksample/model/Location.java
// public class Location implements Serializable {
//
// private String lon;
// private String lat;
//
// public String getLon() {
// return lon;
// }
//
// public void setLon(String lon) {
// this.lon = lon;
// }
//
// public String getLat() {
// return lat;
// }
//
// public void setLat(String lat) {
// this.lat = lat;
// }
// }
|
import com.chinamobile.iot.onenet.sdksample.model.ActivateCode;
import com.chinamobile.iot.onenet.sdksample.model.DeviceItem;
import com.chinamobile.iot.onenet.sdksample.model.Location;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
|
JsonElement desc = jsonObject.get("desc");
deviceItem.setDesc(desc != null ? desc.getAsString() : "");
JsonElement isPrivate = jsonObject.get("private");
deviceItem.setPrivate(isPrivate != null ? isPrivate.getAsBoolean() : true);
JsonElement protocol = jsonObject.get("protocol");
deviceItem.setProtocol(protocol != null ? protocol.getAsString() : "HTTP");
deviceItem.setOnline(jsonObject.get("online").getAsBoolean());
JsonElement locationElement = jsonObject.get("location");
if (locationElement != null) {
JsonObject locationObject = locationElement.getAsJsonObject();
if (locationObject != null) {
Location location = new Location();
location.setLat(locationObject.get("lat").getAsString());
location.setLon(locationObject.get("lon").getAsString());
deviceItem.setLocation(location);
}
}
deviceItem.setCreateTime(jsonObject.get("create_time").getAsString());
JsonElement authInfo = jsonObject.get("auth_info");
if (authInfo != null) {
if (authInfo.isJsonObject()) {
deviceItem.setAuthInfo(authInfo.getAsJsonObject().toString());
} else {
deviceItem.setAuthInfo(authInfo.getAsString());
}
}
JsonElement activateCodeElement = jsonObject.get("activate_code");
if (activateCodeElement != null) {
JsonObject activateCodeObject = activateCodeElement.getAsJsonObject();
if (activateCodeObject != null) {
|
// Path: app/src/main/java/com/chinamobile/iot/onenet/sdksample/model/ActivateCode.java
// public class ActivateCode implements Serializable {
//
// private String mt;
// private String mid;
//
// public String getMt() {
// return mt;
// }
//
// public void setMt(String mt) {
// this.mt = mt;
// }
//
// public String getMid() {
// return mid;
// }
//
// public void setMid(String mid) {
// this.mid = mid;
// }
// }
//
// Path: app/src/main/java/com/chinamobile/iot/onenet/sdksample/model/DeviceItem.java
// public class DeviceItem implements Serializable {
// private String id;
// private String title;
// private String desc;
// @SerializedName("private")
// private boolean isPrivate;
// private String protocol = "HTTP";
// private boolean online;
// private Location location;
// @SerializedName("create_time")
// private String createTime;
// @SerializedName("auth_info")
// private String authInfo;
// @SerializedName("activite_code")
// private ActivateCode activateCode;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public boolean isPrivate() {
// return isPrivate;
// }
//
// public void setPrivate(boolean aPrivate) {
// isPrivate = aPrivate;
// }
//
// public String getProtocol() {
// return protocol;
// }
//
// public void setProtocol(String protocol) {
// this.protocol = protocol;
// }
//
// public boolean isOnline() {
// return online;
// }
//
// public void setOnline(boolean online) {
// this.online = online;
// }
//
// public Location getLocation() {
// return location;
// }
//
// public void setLocation(Location location) {
// this.location = location;
// }
//
// public String getCreateTime() {
// return createTime;
// }
//
// public void setCreateTime(String createTime) {
// this.createTime = createTime;
// }
//
// public String getAuthInfo() {
// return authInfo;
// }
//
// public void setAuthInfo(String authInfo) {
// this.authInfo = authInfo;
// }
//
// public ActivateCode getActivateCode() {
// return activateCode;
// }
//
// public void setActivateCode(ActivateCode activateCode) {
// this.activateCode = activateCode;
// }
// }
//
// Path: app/src/main/java/com/chinamobile/iot/onenet/sdksample/model/Location.java
// public class Location implements Serializable {
//
// private String lon;
// private String lat;
//
// public String getLon() {
// return lon;
// }
//
// public void setLon(String lon) {
// this.lon = lon;
// }
//
// public String getLat() {
// return lat;
// }
//
// public void setLat(String lat) {
// this.lat = lat;
// }
// }
// Path: app/src/main/java/com/chinamobile/iot/onenet/sdksample/utils/DeviceItemDeserializer.java
import com.chinamobile.iot.onenet.sdksample.model.ActivateCode;
import com.chinamobile.iot.onenet.sdksample.model.DeviceItem;
import com.chinamobile.iot.onenet.sdksample.model.Location;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
JsonElement desc = jsonObject.get("desc");
deviceItem.setDesc(desc != null ? desc.getAsString() : "");
JsonElement isPrivate = jsonObject.get("private");
deviceItem.setPrivate(isPrivate != null ? isPrivate.getAsBoolean() : true);
JsonElement protocol = jsonObject.get("protocol");
deviceItem.setProtocol(protocol != null ? protocol.getAsString() : "HTTP");
deviceItem.setOnline(jsonObject.get("online").getAsBoolean());
JsonElement locationElement = jsonObject.get("location");
if (locationElement != null) {
JsonObject locationObject = locationElement.getAsJsonObject();
if (locationObject != null) {
Location location = new Location();
location.setLat(locationObject.get("lat").getAsString());
location.setLon(locationObject.get("lon").getAsString());
deviceItem.setLocation(location);
}
}
deviceItem.setCreateTime(jsonObject.get("create_time").getAsString());
JsonElement authInfo = jsonObject.get("auth_info");
if (authInfo != null) {
if (authInfo.isJsonObject()) {
deviceItem.setAuthInfo(authInfo.getAsJsonObject().toString());
} else {
deviceItem.setAuthInfo(authInfo.getAsString());
}
}
JsonElement activateCodeElement = jsonObject.get("activate_code");
if (activateCodeElement != null) {
JsonObject activateCodeObject = activateCodeElement.getAsJsonObject();
if (activateCodeObject != null) {
|
ActivateCode activateCode = new ActivateCode();
|
cm-heclouds/AndroidSDK
|
onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/Binary.java
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
|
import com.chinamobile.iot.onenet.http.Urls;
import okhttp3.HttpUrl;
|
package com.chinamobile.iot.onenet.module;
public class Binary {
public static String urlForAdding(String deviceId, String dataStreamId) {
|
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/http/Urls.java
// public class Urls {
//
// public static String sScheme = "https";
//
// public static String sHost = "api.heclouds.com";
//
// }
// Path: onenet-sdk/src/main/java/com/chinamobile/iot/onenet/module/Binary.java
import com.chinamobile.iot.onenet.http.Urls;
import okhttp3.HttpUrl;
package com.chinamobile.iot.onenet.module;
public class Binary {
public static String urlForAdding(String deviceId, String dataStreamId) {
|
return new HttpUrl.Builder().scheme(Urls.sScheme).host(Urls.sHost).addPathSegment("bindata")
|
ysmintor/Retrofit2RxjavaDemo
|
app/src/main/java/york/com/retrofit2rxjavademo/subscribers/BaseSubscriber.java
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ApiException.java
// public class ApiException extends Exception {
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ApiException(Throwable throwable, int code) {
// super(throwable);
// this.code = code;
// }
// }
|
import rx.Subscriber;
import york.com.retrofit2rxjavademo.http.exception.ApiException;
|
package york.com.retrofit2rxjavademo.subscribers;
/**
* @author YorkYu
* @version V1.0
* @Project: Retrofit2RxjavaDemo
* @Package york.com.retrofit2rxjavademo.subscribers
* @Description:
* @time 2016/8/11 10:48
*/
public abstract class BaseSubscriber<T> extends Subscriber<T> {
@Override
public void onError(Throwable e) {
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ApiException.java
// public class ApiException extends Exception {
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ApiException(Throwable throwable, int code) {
// super(throwable);
// this.code = code;
// }
// }
// Path: app/src/main/java/york/com/retrofit2rxjavademo/subscribers/BaseSubscriber.java
import rx.Subscriber;
import york.com.retrofit2rxjavademo.http.exception.ApiException;
package york.com.retrofit2rxjavademo.subscribers;
/**
* @author YorkYu
* @version V1.0
* @Project: Retrofit2RxjavaDemo
* @Package york.com.retrofit2rxjavademo.subscribers
* @Description:
* @time 2016/8/11 10:48
*/
public abstract class BaseSubscriber<T> extends Subscriber<T> {
@Override
public void onError(Throwable e) {
|
if(e instanceof ApiException){
|
ysmintor/Retrofit2RxjavaDemo
|
app/src/main/java/york/com/retrofit2rxjavademo/MyApplication.java
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/di/module/NetworkModule.java
// @Module
// public class NetworkModule {
// // private String mBaseUrl = "http://rap.taobao.org/mockjsdata/15987/";
// private String mBaseUrl;
// private int DEFAULT_TIMEOUT = 10;
//
// // Constructor needs one parameter to instantiate.
// public NetworkModule(String baseUrl, int default_timeout) {
// this.mBaseUrl = baseUrl;
// this.DEFAULT_TIMEOUT = default_timeout;
// }
//
// // Dagger will only look for methods annotated with @Provides
// @Provides
// @AppScope
// // Application reference must come from AppModule.class
// SharedPreferences providesSharedPreferences(MyApplication application) {
// return PreferenceManager.getDefaultSharedPreferences(application);
// }
//
// @Provides
// @AppScope
// Cache provideOkHttpCache(MyApplication application) {
// int cacheSize = 10 * 1024 * 1024; // 10 MiB
// Cache cache = new Cache(application.getCacheDir(), cacheSize);
// return cache;
// }
//
// @Provides
// @AppScope
// Gson provideGson() {
// GsonBuilder gsonBuilder = new GsonBuilder();
// gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
// return gsonBuilder.create();
// }
//
// @Provides
// @AppScope
// @Named("cached")
// OkHttpClient provideOkHttpClient(Cache cache) {
// OkHttpClient client =
// new OkHttpClient.Builder()
// .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .addNetworkInterceptor(
// new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
// .retryOnConnectionFailure(true)
// .cache(cache)
// .build();
// return client;
// }
//
// @Provides
// @AppScope
// @Named("noncached")
// OkHttpClient provideNonCachedOkHttpClient() {
// OkHttpClient client =
// new OkHttpClient.Builder()
// .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .addNetworkInterceptor(
// new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
// .retryOnConnectionFailure(true)
// .build();
// return client;
// }
//
// @Provides
// @AppScope
// Retrofit provideRetrofit(Gson gson, @Named("cached") OkHttpClient okHttpClient) {
// return new Retrofit.Builder()
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .client(okHttpClient)
// .baseUrl(mBaseUrl)
// .build();
// }
//
//
// /**
// * 使用自定义Converter处理message在错误时返回在data字段
// * @param gson
// * @param okHttpClient
// * @return
// */
// @Provides
// @AppScope
// @Named("custom_converter")
// Retrofit provideCustomConverterRetrofit(Gson gson, @Named("cached") OkHttpClient okHttpClient) {
// return new Retrofit.Builder()
// .addConverterFactory(CustomGsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .client(okHttpClient)
// .baseUrl(mBaseUrl)
// .build();
// }
// }
|
import android.app.Activity;
import android.app.Application;
import javax.inject.Inject;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.HasActivityInjector;
import york.com.retrofit2rxjavademo.di.component.DaggerAppComponent;
import york.com.retrofit2rxjavademo.di.module.NetworkModule;
|
package york.com.retrofit2rxjavademo;
/**
* @author YorkYu
* @version V1.0
* @Project: Retrofit2RxjavaDemo
* @Package york.com.retrofit2rxjavademo
* @Description:
* @time 2016/7/25 17:08
*/
public class MyApplication extends Application implements HasActivityInjector {
@Inject
DispatchingAndroidInjector<Activity> dispatchingActivityInjector;
private static final String sBASE_URL = "http://rap.taobao.org/mockjsdata/15987/";
private static final int sDEFAULT_TIMEOUT = 10;
@Override
public void onCreate() {
super.onCreate();
DaggerAppComponent
.builder()
.application(this)
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/di/module/NetworkModule.java
// @Module
// public class NetworkModule {
// // private String mBaseUrl = "http://rap.taobao.org/mockjsdata/15987/";
// private String mBaseUrl;
// private int DEFAULT_TIMEOUT = 10;
//
// // Constructor needs one parameter to instantiate.
// public NetworkModule(String baseUrl, int default_timeout) {
// this.mBaseUrl = baseUrl;
// this.DEFAULT_TIMEOUT = default_timeout;
// }
//
// // Dagger will only look for methods annotated with @Provides
// @Provides
// @AppScope
// // Application reference must come from AppModule.class
// SharedPreferences providesSharedPreferences(MyApplication application) {
// return PreferenceManager.getDefaultSharedPreferences(application);
// }
//
// @Provides
// @AppScope
// Cache provideOkHttpCache(MyApplication application) {
// int cacheSize = 10 * 1024 * 1024; // 10 MiB
// Cache cache = new Cache(application.getCacheDir(), cacheSize);
// return cache;
// }
//
// @Provides
// @AppScope
// Gson provideGson() {
// GsonBuilder gsonBuilder = new GsonBuilder();
// gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
// return gsonBuilder.create();
// }
//
// @Provides
// @AppScope
// @Named("cached")
// OkHttpClient provideOkHttpClient(Cache cache) {
// OkHttpClient client =
// new OkHttpClient.Builder()
// .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .addNetworkInterceptor(
// new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
// .retryOnConnectionFailure(true)
// .cache(cache)
// .build();
// return client;
// }
//
// @Provides
// @AppScope
// @Named("noncached")
// OkHttpClient provideNonCachedOkHttpClient() {
// OkHttpClient client =
// new OkHttpClient.Builder()
// .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
// .addNetworkInterceptor(
// new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
// .retryOnConnectionFailure(true)
// .build();
// return client;
// }
//
// @Provides
// @AppScope
// Retrofit provideRetrofit(Gson gson, @Named("cached") OkHttpClient okHttpClient) {
// return new Retrofit.Builder()
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .client(okHttpClient)
// .baseUrl(mBaseUrl)
// .build();
// }
//
//
// /**
// * 使用自定义Converter处理message在错误时返回在data字段
// * @param gson
// * @param okHttpClient
// * @return
// */
// @Provides
// @AppScope
// @Named("custom_converter")
// Retrofit provideCustomConverterRetrofit(Gson gson, @Named("cached") OkHttpClient okHttpClient) {
// return new Retrofit.Builder()
// .addConverterFactory(CustomGsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .client(okHttpClient)
// .baseUrl(mBaseUrl)
// .build();
// }
// }
// Path: app/src/main/java/york/com/retrofit2rxjavademo/MyApplication.java
import android.app.Activity;
import android.app.Application;
import javax.inject.Inject;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.HasActivityInjector;
import york.com.retrofit2rxjavademo.di.component.DaggerAppComponent;
import york.com.retrofit2rxjavademo.di.module.NetworkModule;
package york.com.retrofit2rxjavademo;
/**
* @author YorkYu
* @version V1.0
* @Project: Retrofit2RxjavaDemo
* @Package york.com.retrofit2rxjavademo
* @Description:
* @time 2016/7/25 17:08
*/
public class MyApplication extends Application implements HasActivityInjector {
@Inject
DispatchingAndroidInjector<Activity> dispatchingActivityInjector;
private static final String sBASE_URL = "http://rap.taobao.org/mockjsdata/15987/";
private static final int sDEFAULT_TIMEOUT = 10;
@Override
public void onCreate() {
super.onCreate();
DaggerAppComponent
.builder()
.application(this)
|
.network(new NetworkModule(sBASE_URL, sDEFAULT_TIMEOUT))
|
ysmintor/Retrofit2RxjavaDemo
|
app/src/main/java/york/com/retrofit2rxjavademo/di/module/MainModule.java
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/TestBean.java
// public class TestBean {
// String name;
// int age;
//
// public TestBean(String name, int age) {
// this.name = name;
// this.age = age;
// }
//
// @Override
// public String toString() {
// return "TestBean{" +
// "name='" + name + '\'' +
// ", age=" + age +
// '}';
// }
// }
|
import dagger.Module;
import dagger.Provides;
import york.com.retrofit2rxjavademo.di.scope.PerActivityScope;
import york.com.retrofit2rxjavademo.entity.TestBean;
|
package york.com.retrofit2rxjavademo.di.module;
/**
* @author: YorkYu
* @version: V2.0.0
* @project: Retrofit2RxjavaDemo
* @package: york.com.retrofit2rxjavademo.di.module
* @description: description
* @date: 2017/7/11
* @time: 17:45
*/
@Module
public class MainModule {
@Provides
@PerActivityScope
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/TestBean.java
// public class TestBean {
// String name;
// int age;
//
// public TestBean(String name, int age) {
// this.name = name;
// this.age = age;
// }
//
// @Override
// public String toString() {
// return "TestBean{" +
// "name='" + name + '\'' +
// ", age=" + age +
// '}';
// }
// }
// Path: app/src/main/java/york/com/retrofit2rxjavademo/di/module/MainModule.java
import dagger.Module;
import dagger.Provides;
import york.com.retrofit2rxjavademo.di.scope.PerActivityScope;
import york.com.retrofit2rxjavademo.entity.TestBean;
package york.com.retrofit2rxjavademo.di.module;
/**
* @author: YorkYu
* @version: V2.0.0
* @project: Retrofit2RxjavaDemo
* @package: york.com.retrofit2rxjavademo.di.module
* @description: description
* @date: 2017/7/11
* @time: 17:45
*/
@Module
public class MainModule {
@Provides
@PerActivityScope
|
TestBean provideTestBean() {
|
ysmintor/Retrofit2RxjavaDemo
|
app/src/main/java/york/com/retrofit2rxjavademo/http/ExceptionEngine.java
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ApiException.java
// public class ApiException extends Exception {
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ApiException(Throwable throwable, int code) {
// super(throwable);
// this.code = code;
// }
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ErrorType.java
// public interface ErrorType {
// /**
// * 正常
// */
// int SUCCESS = 0;
// /**
// * 未知错误
// */
// int UNKNOWN = 1000;
// /**
// * 解析错误
// */
// int PARSE_ERROR = 1001;
// /**
// * 网络错误
// */
// int NETWORD_ERROR = 1002;
// /**
// * 协议出错
// */
// int HTTP_ERROR = 1003;
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ServerException.java
// public class ServerException extends RuntimeException{
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ServerException(String message, int code) {
// super(message);
// this.code = code;
// this.message = message;
// }
// }
|
import android.net.ParseException;
import com.google.gson.JsonParseException;
import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import retrofit2.adapter.rxjava.HttpException;
import york.com.retrofit2rxjavademo.http.exception.ApiException;
import york.com.retrofit2rxjavademo.http.exception.ErrorType;
import york.com.retrofit2rxjavademo.http.exception.ServerException;
|
package york.com.retrofit2rxjavademo.http;
public class ExceptionEngine {
//对应HTTP的状态码
private static final int UNAUTHORIZED = 401;
private static final int FORBIDDEN = 403;
private static final int NOT_FOUND = 404;
private static final int REQUEST_TIMEOUT = 408;
private static final int INTERNAL_SERVER_ERROR = 500;
private static final int BAD_GATEWAY = 502;
private static final int SERVICE_UNAVAILABLE = 503;
private static final int GATEWAY_TIMEOUT = 504;
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ApiException.java
// public class ApiException extends Exception {
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ApiException(Throwable throwable, int code) {
// super(throwable);
// this.code = code;
// }
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ErrorType.java
// public interface ErrorType {
// /**
// * 正常
// */
// int SUCCESS = 0;
// /**
// * 未知错误
// */
// int UNKNOWN = 1000;
// /**
// * 解析错误
// */
// int PARSE_ERROR = 1001;
// /**
// * 网络错误
// */
// int NETWORD_ERROR = 1002;
// /**
// * 协议出错
// */
// int HTTP_ERROR = 1003;
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ServerException.java
// public class ServerException extends RuntimeException{
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ServerException(String message, int code) {
// super(message);
// this.code = code;
// this.message = message;
// }
// }
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/ExceptionEngine.java
import android.net.ParseException;
import com.google.gson.JsonParseException;
import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import retrofit2.adapter.rxjava.HttpException;
import york.com.retrofit2rxjavademo.http.exception.ApiException;
import york.com.retrofit2rxjavademo.http.exception.ErrorType;
import york.com.retrofit2rxjavademo.http.exception.ServerException;
package york.com.retrofit2rxjavademo.http;
public class ExceptionEngine {
//对应HTTP的状态码
private static final int UNAUTHORIZED = 401;
private static final int FORBIDDEN = 403;
private static final int NOT_FOUND = 404;
private static final int REQUEST_TIMEOUT = 408;
private static final int INTERNAL_SERVER_ERROR = 500;
private static final int BAD_GATEWAY = 502;
private static final int SERVICE_UNAVAILABLE = 503;
private static final int GATEWAY_TIMEOUT = 504;
|
public static ApiException handleException(Throwable e){
|
ysmintor/Retrofit2RxjavaDemo
|
app/src/main/java/york/com/retrofit2rxjavademo/http/ExceptionEngine.java
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ApiException.java
// public class ApiException extends Exception {
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ApiException(Throwable throwable, int code) {
// super(throwable);
// this.code = code;
// }
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ErrorType.java
// public interface ErrorType {
// /**
// * 正常
// */
// int SUCCESS = 0;
// /**
// * 未知错误
// */
// int UNKNOWN = 1000;
// /**
// * 解析错误
// */
// int PARSE_ERROR = 1001;
// /**
// * 网络错误
// */
// int NETWORD_ERROR = 1002;
// /**
// * 协议出错
// */
// int HTTP_ERROR = 1003;
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ServerException.java
// public class ServerException extends RuntimeException{
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ServerException(String message, int code) {
// super(message);
// this.code = code;
// this.message = message;
// }
// }
|
import android.net.ParseException;
import com.google.gson.JsonParseException;
import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import retrofit2.adapter.rxjava.HttpException;
import york.com.retrofit2rxjavademo.http.exception.ApiException;
import york.com.retrofit2rxjavademo.http.exception.ErrorType;
import york.com.retrofit2rxjavademo.http.exception.ServerException;
|
package york.com.retrofit2rxjavademo.http;
public class ExceptionEngine {
//对应HTTP的状态码
private static final int UNAUTHORIZED = 401;
private static final int FORBIDDEN = 403;
private static final int NOT_FOUND = 404;
private static final int REQUEST_TIMEOUT = 408;
private static final int INTERNAL_SERVER_ERROR = 500;
private static final int BAD_GATEWAY = 502;
private static final int SERVICE_UNAVAILABLE = 503;
private static final int GATEWAY_TIMEOUT = 504;
public static ApiException handleException(Throwable e){
ApiException ex;
if (e instanceof HttpException){ //HTTP错误
HttpException httpException = (HttpException) e;
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ApiException.java
// public class ApiException extends Exception {
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ApiException(Throwable throwable, int code) {
// super(throwable);
// this.code = code;
// }
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ErrorType.java
// public interface ErrorType {
// /**
// * 正常
// */
// int SUCCESS = 0;
// /**
// * 未知错误
// */
// int UNKNOWN = 1000;
// /**
// * 解析错误
// */
// int PARSE_ERROR = 1001;
// /**
// * 网络错误
// */
// int NETWORD_ERROR = 1002;
// /**
// * 协议出错
// */
// int HTTP_ERROR = 1003;
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ServerException.java
// public class ServerException extends RuntimeException{
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ServerException(String message, int code) {
// super(message);
// this.code = code;
// this.message = message;
// }
// }
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/ExceptionEngine.java
import android.net.ParseException;
import com.google.gson.JsonParseException;
import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import retrofit2.adapter.rxjava.HttpException;
import york.com.retrofit2rxjavademo.http.exception.ApiException;
import york.com.retrofit2rxjavademo.http.exception.ErrorType;
import york.com.retrofit2rxjavademo.http.exception.ServerException;
package york.com.retrofit2rxjavademo.http;
public class ExceptionEngine {
//对应HTTP的状态码
private static final int UNAUTHORIZED = 401;
private static final int FORBIDDEN = 403;
private static final int NOT_FOUND = 404;
private static final int REQUEST_TIMEOUT = 408;
private static final int INTERNAL_SERVER_ERROR = 500;
private static final int BAD_GATEWAY = 502;
private static final int SERVICE_UNAVAILABLE = 503;
private static final int GATEWAY_TIMEOUT = 504;
public static ApiException handleException(Throwable e){
ApiException ex;
if (e instanceof HttpException){ //HTTP错误
HttpException httpException = (HttpException) e;
|
ex = new ApiException(e, ErrorType.HTTP_ERROR);
|
ysmintor/Retrofit2RxjavaDemo
|
app/src/main/java/york/com/retrofit2rxjavademo/http/ExceptionEngine.java
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ApiException.java
// public class ApiException extends Exception {
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ApiException(Throwable throwable, int code) {
// super(throwable);
// this.code = code;
// }
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ErrorType.java
// public interface ErrorType {
// /**
// * 正常
// */
// int SUCCESS = 0;
// /**
// * 未知错误
// */
// int UNKNOWN = 1000;
// /**
// * 解析错误
// */
// int PARSE_ERROR = 1001;
// /**
// * 网络错误
// */
// int NETWORD_ERROR = 1002;
// /**
// * 协议出错
// */
// int HTTP_ERROR = 1003;
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ServerException.java
// public class ServerException extends RuntimeException{
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ServerException(String message, int code) {
// super(message);
// this.code = code;
// this.message = message;
// }
// }
|
import android.net.ParseException;
import com.google.gson.JsonParseException;
import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import retrofit2.adapter.rxjava.HttpException;
import york.com.retrofit2rxjavademo.http.exception.ApiException;
import york.com.retrofit2rxjavademo.http.exception.ErrorType;
import york.com.retrofit2rxjavademo.http.exception.ServerException;
|
switch(httpException.code()){
case UNAUTHORIZED:
ex.message = "当前请求需要用户验证";
break;
case FORBIDDEN:
ex.message = "服务器已经理解请求,但是拒绝执行它";
break;
case NOT_FOUND:
ex.message = "服务器异常,请稍后再试";
break;
case REQUEST_TIMEOUT:
ex.message = "请求超时";
break;
case GATEWAY_TIMEOUT:
ex.message = "作为网关或者代理工作的服务器尝试执行请求时,未能及时从上游服务器(URI标识出的服务器,例如HTTP、FTP、LDAP)或者辅助服务器(例如DNS)收到响应";
break;
case INTERNAL_SERVER_ERROR:
ex.message = "服务器遇到了一个未曾预料的状况,导致了它无法完成对请求的处理";
break;
case BAD_GATEWAY:
ex.message = "作为网关或者代理工作的服务器尝试执行请求时,从上游服务器接收到无效的响应";
break;
case SERVICE_UNAVAILABLE:
ex.message = "由于临时的服务器维护或者过载,服务器当前无法处理请求";
break;
default:
ex.message = "网络错误"; //其它均视为网络错误
break;
}
return ex;
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ApiException.java
// public class ApiException extends Exception {
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ApiException(Throwable throwable, int code) {
// super(throwable);
// this.code = code;
// }
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ErrorType.java
// public interface ErrorType {
// /**
// * 正常
// */
// int SUCCESS = 0;
// /**
// * 未知错误
// */
// int UNKNOWN = 1000;
// /**
// * 解析错误
// */
// int PARSE_ERROR = 1001;
// /**
// * 网络错误
// */
// int NETWORD_ERROR = 1002;
// /**
// * 协议出错
// */
// int HTTP_ERROR = 1003;
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ServerException.java
// public class ServerException extends RuntimeException{
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ServerException(String message, int code) {
// super(message);
// this.code = code;
// this.message = message;
// }
// }
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/ExceptionEngine.java
import android.net.ParseException;
import com.google.gson.JsonParseException;
import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import retrofit2.adapter.rxjava.HttpException;
import york.com.retrofit2rxjavademo.http.exception.ApiException;
import york.com.retrofit2rxjavademo.http.exception.ErrorType;
import york.com.retrofit2rxjavademo.http.exception.ServerException;
switch(httpException.code()){
case UNAUTHORIZED:
ex.message = "当前请求需要用户验证";
break;
case FORBIDDEN:
ex.message = "服务器已经理解请求,但是拒绝执行它";
break;
case NOT_FOUND:
ex.message = "服务器异常,请稍后再试";
break;
case REQUEST_TIMEOUT:
ex.message = "请求超时";
break;
case GATEWAY_TIMEOUT:
ex.message = "作为网关或者代理工作的服务器尝试执行请求时,未能及时从上游服务器(URI标识出的服务器,例如HTTP、FTP、LDAP)或者辅助服务器(例如DNS)收到响应";
break;
case INTERNAL_SERVER_ERROR:
ex.message = "服务器遇到了一个未曾预料的状况,导致了它无法完成对请求的处理";
break;
case BAD_GATEWAY:
ex.message = "作为网关或者代理工作的服务器尝试执行请求时,从上游服务器接收到无效的响应";
break;
case SERVICE_UNAVAILABLE:
ex.message = "由于临时的服务器维护或者过载,服务器当前无法处理请求";
break;
default:
ex.message = "网络错误"; //其它均视为网络错误
break;
}
return ex;
|
} else if (e instanceof ServerException){ //服务器返回的错误
|
ysmintor/Retrofit2RxjavaDemo
|
app/src/main/java/york/com/retrofit2rxjavademo/di/module/AppModule.java
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/MyApplication.java
// public class MyApplication extends Application implements HasActivityInjector {
// @Inject
// DispatchingAndroidInjector<Activity> dispatchingActivityInjector;
//
// private static final String sBASE_URL = "http://rap.taobao.org/mockjsdata/15987/";
// private static final int sDEFAULT_TIMEOUT = 10;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// DaggerAppComponent
// .builder()
// .application(this)
// .network(new NetworkModule(sBASE_URL, sDEFAULT_TIMEOUT))
// .build()
// .inject(this);
// }
//
//
// @Override
// public AndroidInjector<Activity> activityInjector() {
// return dispatchingActivityInjector;
// }
// }
|
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import york.com.retrofit2rxjavademo.MyApplication;
import york.com.retrofit2rxjavademo.di.scope.AppScope;
|
package york.com.retrofit2rxjavademo.di.module;
/**
* @author: YorkYu
* @version: V2.0.0
* @project: Retrofit2RxjavaDemo
* @package: york.com.retrofit2rxjavademo.di.module
* @description: description
* @date: 2017/7/7
* @time: 17:31
*/
@Module
public class AppModule {
@Provides
@AppScope
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/MyApplication.java
// public class MyApplication extends Application implements HasActivityInjector {
// @Inject
// DispatchingAndroidInjector<Activity> dispatchingActivityInjector;
//
// private static final String sBASE_URL = "http://rap.taobao.org/mockjsdata/15987/";
// private static final int sDEFAULT_TIMEOUT = 10;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// DaggerAppComponent
// .builder()
// .application(this)
// .network(new NetworkModule(sBASE_URL, sDEFAULT_TIMEOUT))
// .build()
// .inject(this);
// }
//
//
// @Override
// public AndroidInjector<Activity> activityInjector() {
// return dispatchingActivityInjector;
// }
// }
// Path: app/src/main/java/york/com/retrofit2rxjavademo/di/module/AppModule.java
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import york.com.retrofit2rxjavademo.MyApplication;
import york.com.retrofit2rxjavademo.di.scope.AppScope;
package york.com.retrofit2rxjavademo.di.module;
/**
* @author: YorkYu
* @version: V2.0.0
* @project: Retrofit2RxjavaDemo
* @package: york.com.retrofit2rxjavademo.di.module
* @description: description
* @date: 2017/7/7
* @time: 17:31
*/
@Module
public class AppModule {
@Provides
@AppScope
|
Context provideContext(MyApplication application) {
|
ysmintor/Retrofit2RxjavaDemo
|
app/src/main/java/york/com/retrofit2rxjavademo/http/MovieService.java
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/ContentBean.java
// public class ContentBean {
//
// private String id;
// private String alt;
// private String year;
// private String title;
// private String original_title;
// private List<String> genres;
// private List<Cast> casts;
// private List<Cast> directors;
// private Avatars images;
//
// @Override
// public String toString() {
// return "ContentBean.id=" + id
// + " ContentBean.title=" + title
// + " ContentBean.year=" + year
// + " ContentBean.originalTitle=" + original_title + casts.toString() + directors.toString() + " | ";
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getAlt() {
// return alt;
// }
//
// public void setAlt(String alt) {
// this.alt = alt;
// }
//
// public String getYear() {
// return year;
// }
//
// public void setYear(String year) {
// this.year = year;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getOriginal_title() {
// return original_title;
// }
//
// public void setOriginal_title(String original_title) {
// this.original_title = original_title;
// }
//
// public List<String> getGenres() {
// return genres;
// }
//
// public void setGenres(List<String> genres) {
// this.genres = genres;
// }
//
// public List<Cast> getCasts() {
// return casts;
// }
//
// public void setCasts(List<Cast> casts) {
// this.casts = casts;
// }
//
// public List<Cast> getDirectors() {
// return directors;
// }
//
// public void setDirectors(List<Cast> directors) {
// this.directors = directors;
// }
//
// public Avatars getImages() {
// return images;
// }
//
// public void setImages(Avatars images) {
// this.images = images;
// }
//
// private class Cast{
// private String id;
// private String name;
// private String alt;
// private Avatars avatars;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getAlt() {
// return alt;
// }
//
// public void setAlt(String alt) {
// this.alt = alt;
// }
//
// public Avatars getAvatars() {
// return avatars;
// }
//
// public void setAvatars(Avatars avatars) {
// this.avatars = avatars;
// }
//
// @Override
// public String toString() {
// return "cast.id=" + id + " cast.name=" + name + " | ";
// }
// }
//
// private class Avatars{
// private String small;
// private String medium;
// private String large;
//
// public String getSmall() {
// return small;
// }
//
// public void setSmall(String small) {
// this.small = small;
// }
//
// public String getMedium() {
// return medium;
// }
//
// public void setMedium(String medium) {
// this.medium = medium;
// }
//
// public String getLarge() {
// return large;
// }
//
// public void setLarge(String large) {
// this.large = large;
// }
// }
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/HttpResult.java
// public class HttpResult<T> {
//
// // code 为返回的状态码, message 为返回的消息, 演示的没有这两个字段,考虑到真实的环境中基本包含就在这里写定值
// private int code;
// // this will receive message or status, msg as message field
// @SerializedName(value = "message", alternate = {"status", "msg"})
// private String message;
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
//
// //用来模仿Data
// @SerializedName(value = "data", alternate = {"subjects", "result"})
// private T data;
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
//
// }
|
import java.util.List;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;
import york.com.retrofit2rxjavademo.entity.ContentBean;
import york.com.retrofit2rxjavademo.entity.HttpResult;
|
package york.com.retrofit2rxjavademo.http;
/**
* Created by liukun on 16/3/9.
*/
public interface MovieService {
// @GET("top250")
// Call<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);
// @GET("top250")
// Observable<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);
// @GET("top250")
// Observable<HttpResult<List<ContentBean>>> getTopMovie(@Query("start") int start, @Query("count") int count);
@GET("top250")
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/ContentBean.java
// public class ContentBean {
//
// private String id;
// private String alt;
// private String year;
// private String title;
// private String original_title;
// private List<String> genres;
// private List<Cast> casts;
// private List<Cast> directors;
// private Avatars images;
//
// @Override
// public String toString() {
// return "ContentBean.id=" + id
// + " ContentBean.title=" + title
// + " ContentBean.year=" + year
// + " ContentBean.originalTitle=" + original_title + casts.toString() + directors.toString() + " | ";
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getAlt() {
// return alt;
// }
//
// public void setAlt(String alt) {
// this.alt = alt;
// }
//
// public String getYear() {
// return year;
// }
//
// public void setYear(String year) {
// this.year = year;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getOriginal_title() {
// return original_title;
// }
//
// public void setOriginal_title(String original_title) {
// this.original_title = original_title;
// }
//
// public List<String> getGenres() {
// return genres;
// }
//
// public void setGenres(List<String> genres) {
// this.genres = genres;
// }
//
// public List<Cast> getCasts() {
// return casts;
// }
//
// public void setCasts(List<Cast> casts) {
// this.casts = casts;
// }
//
// public List<Cast> getDirectors() {
// return directors;
// }
//
// public void setDirectors(List<Cast> directors) {
// this.directors = directors;
// }
//
// public Avatars getImages() {
// return images;
// }
//
// public void setImages(Avatars images) {
// this.images = images;
// }
//
// private class Cast{
// private String id;
// private String name;
// private String alt;
// private Avatars avatars;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getAlt() {
// return alt;
// }
//
// public void setAlt(String alt) {
// this.alt = alt;
// }
//
// public Avatars getAvatars() {
// return avatars;
// }
//
// public void setAvatars(Avatars avatars) {
// this.avatars = avatars;
// }
//
// @Override
// public String toString() {
// return "cast.id=" + id + " cast.name=" + name + " | ";
// }
// }
//
// private class Avatars{
// private String small;
// private String medium;
// private String large;
//
// public String getSmall() {
// return small;
// }
//
// public void setSmall(String small) {
// this.small = small;
// }
//
// public String getMedium() {
// return medium;
// }
//
// public void setMedium(String medium) {
// this.medium = medium;
// }
//
// public String getLarge() {
// return large;
// }
//
// public void setLarge(String large) {
// this.large = large;
// }
// }
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/HttpResult.java
// public class HttpResult<T> {
//
// // code 为返回的状态码, message 为返回的消息, 演示的没有这两个字段,考虑到真实的环境中基本包含就在这里写定值
// private int code;
// // this will receive message or status, msg as message field
// @SerializedName(value = "message", alternate = {"status", "msg"})
// private String message;
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
//
// //用来模仿Data
// @SerializedName(value = "data", alternate = {"subjects", "result"})
// private T data;
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
//
// }
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/MovieService.java
import java.util.List;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;
import york.com.retrofit2rxjavademo.entity.ContentBean;
import york.com.retrofit2rxjavademo.entity.HttpResult;
package york.com.retrofit2rxjavademo.http;
/**
* Created by liukun on 16/3/9.
*/
public interface MovieService {
// @GET("top250")
// Call<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);
// @GET("top250")
// Observable<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);
// @GET("top250")
// Observable<HttpResult<List<ContentBean>>> getTopMovie(@Query("start") int start, @Query("count") int count);
@GET("top250")
|
Observable<HttpResult<List<ContentBean>>> getTopMovie(@Query("start") int start, @Query("count") int count);
|
ysmintor/Retrofit2RxjavaDemo
|
app/src/main/java/york/com/retrofit2rxjavademo/http/MovieService.java
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/ContentBean.java
// public class ContentBean {
//
// private String id;
// private String alt;
// private String year;
// private String title;
// private String original_title;
// private List<String> genres;
// private List<Cast> casts;
// private List<Cast> directors;
// private Avatars images;
//
// @Override
// public String toString() {
// return "ContentBean.id=" + id
// + " ContentBean.title=" + title
// + " ContentBean.year=" + year
// + " ContentBean.originalTitle=" + original_title + casts.toString() + directors.toString() + " | ";
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getAlt() {
// return alt;
// }
//
// public void setAlt(String alt) {
// this.alt = alt;
// }
//
// public String getYear() {
// return year;
// }
//
// public void setYear(String year) {
// this.year = year;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getOriginal_title() {
// return original_title;
// }
//
// public void setOriginal_title(String original_title) {
// this.original_title = original_title;
// }
//
// public List<String> getGenres() {
// return genres;
// }
//
// public void setGenres(List<String> genres) {
// this.genres = genres;
// }
//
// public List<Cast> getCasts() {
// return casts;
// }
//
// public void setCasts(List<Cast> casts) {
// this.casts = casts;
// }
//
// public List<Cast> getDirectors() {
// return directors;
// }
//
// public void setDirectors(List<Cast> directors) {
// this.directors = directors;
// }
//
// public Avatars getImages() {
// return images;
// }
//
// public void setImages(Avatars images) {
// this.images = images;
// }
//
// private class Cast{
// private String id;
// private String name;
// private String alt;
// private Avatars avatars;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getAlt() {
// return alt;
// }
//
// public void setAlt(String alt) {
// this.alt = alt;
// }
//
// public Avatars getAvatars() {
// return avatars;
// }
//
// public void setAvatars(Avatars avatars) {
// this.avatars = avatars;
// }
//
// @Override
// public String toString() {
// return "cast.id=" + id + " cast.name=" + name + " | ";
// }
// }
//
// private class Avatars{
// private String small;
// private String medium;
// private String large;
//
// public String getSmall() {
// return small;
// }
//
// public void setSmall(String small) {
// this.small = small;
// }
//
// public String getMedium() {
// return medium;
// }
//
// public void setMedium(String medium) {
// this.medium = medium;
// }
//
// public String getLarge() {
// return large;
// }
//
// public void setLarge(String large) {
// this.large = large;
// }
// }
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/HttpResult.java
// public class HttpResult<T> {
//
// // code 为返回的状态码, message 为返回的消息, 演示的没有这两个字段,考虑到真实的环境中基本包含就在这里写定值
// private int code;
// // this will receive message or status, msg as message field
// @SerializedName(value = "message", alternate = {"status", "msg"})
// private String message;
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
//
// //用来模仿Data
// @SerializedName(value = "data", alternate = {"subjects", "result"})
// private T data;
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
//
// }
|
import java.util.List;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;
import york.com.retrofit2rxjavademo.entity.ContentBean;
import york.com.retrofit2rxjavademo.entity.HttpResult;
|
package york.com.retrofit2rxjavademo.http;
/**
* Created by liukun on 16/3/9.
*/
public interface MovieService {
// @GET("top250")
// Call<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);
// @GET("top250")
// Observable<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);
// @GET("top250")
// Observable<HttpResult<List<ContentBean>>> getTopMovie(@Query("start") int start, @Query("count") int count);
@GET("top250")
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/ContentBean.java
// public class ContentBean {
//
// private String id;
// private String alt;
// private String year;
// private String title;
// private String original_title;
// private List<String> genres;
// private List<Cast> casts;
// private List<Cast> directors;
// private Avatars images;
//
// @Override
// public String toString() {
// return "ContentBean.id=" + id
// + " ContentBean.title=" + title
// + " ContentBean.year=" + year
// + " ContentBean.originalTitle=" + original_title + casts.toString() + directors.toString() + " | ";
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getAlt() {
// return alt;
// }
//
// public void setAlt(String alt) {
// this.alt = alt;
// }
//
// public String getYear() {
// return year;
// }
//
// public void setYear(String year) {
// this.year = year;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getOriginal_title() {
// return original_title;
// }
//
// public void setOriginal_title(String original_title) {
// this.original_title = original_title;
// }
//
// public List<String> getGenres() {
// return genres;
// }
//
// public void setGenres(List<String> genres) {
// this.genres = genres;
// }
//
// public List<Cast> getCasts() {
// return casts;
// }
//
// public void setCasts(List<Cast> casts) {
// this.casts = casts;
// }
//
// public List<Cast> getDirectors() {
// return directors;
// }
//
// public void setDirectors(List<Cast> directors) {
// this.directors = directors;
// }
//
// public Avatars getImages() {
// return images;
// }
//
// public void setImages(Avatars images) {
// this.images = images;
// }
//
// private class Cast{
// private String id;
// private String name;
// private String alt;
// private Avatars avatars;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getAlt() {
// return alt;
// }
//
// public void setAlt(String alt) {
// this.alt = alt;
// }
//
// public Avatars getAvatars() {
// return avatars;
// }
//
// public void setAvatars(Avatars avatars) {
// this.avatars = avatars;
// }
//
// @Override
// public String toString() {
// return "cast.id=" + id + " cast.name=" + name + " | ";
// }
// }
//
// private class Avatars{
// private String small;
// private String medium;
// private String large;
//
// public String getSmall() {
// return small;
// }
//
// public void setSmall(String small) {
// this.small = small;
// }
//
// public String getMedium() {
// return medium;
// }
//
// public void setMedium(String medium) {
// this.medium = medium;
// }
//
// public String getLarge() {
// return large;
// }
//
// public void setLarge(String large) {
// this.large = large;
// }
// }
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/HttpResult.java
// public class HttpResult<T> {
//
// // code 为返回的状态码, message 为返回的消息, 演示的没有这两个字段,考虑到真实的环境中基本包含就在这里写定值
// private int code;
// // this will receive message or status, msg as message field
// @SerializedName(value = "message", alternate = {"status", "msg"})
// private String message;
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
//
// //用来模仿Data
// @SerializedName(value = "data", alternate = {"subjects", "result"})
// private T data;
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
//
// }
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/MovieService.java
import java.util.List;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;
import york.com.retrofit2rxjavademo.entity.ContentBean;
import york.com.retrofit2rxjavademo.entity.HttpResult;
package york.com.retrofit2rxjavademo.http;
/**
* Created by liukun on 16/3/9.
*/
public interface MovieService {
// @GET("top250")
// Call<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);
// @GET("top250")
// Observable<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);
// @GET("top250")
// Observable<HttpResult<List<ContentBean>>> getTopMovie(@Query("start") int start, @Query("count") int count);
@GET("top250")
|
Observable<HttpResult<List<ContentBean>>> getTopMovie(@Query("start") int start, @Query("count") int count);
|
ysmintor/Retrofit2RxjavaDemo
|
app/src/main/java/york/com/retrofit2rxjavademo/http/MockApi.java
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/HttpResult.java
// public class HttpResult<T> {
//
// // code 为返回的状态码, message 为返回的消息, 演示的没有这两个字段,考虑到真实的环境中基本包含就在这里写定值
// private int code;
// // this will receive message or status, msg as message field
// @SerializedName(value = "message", alternate = {"status", "msg"})
// private String message;
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
//
// //用来模仿Data
// @SerializedName(value = "data", alternate = {"subjects", "result"})
// private T data;
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
//
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/MockBean.java
// public class MockBean {
// /**
// * address : 北京市海淀区清华大学
// * website : www.tsinghua.edu.cn
// * email : [email protected]
// * parent : 教育部
// * type : 211 985
// * phone : 010-62770334;010-62782051
// * info : 院士:68人 博士点:198个 硕士点:181个
// * city : 北京
// * name : 清华大学
// * profile : 清华简历清华简历清华简历清华简历
// * img : http://img.jidichong.com/school/3.png
// * zipcode : 01022
// */
//
// private String address;
// private String website;
// private String email;
// private String parent;
// private String type;
// private String phone;
// private String info;
// private String city;
// private String name;
// private String profile;
// private String img;
// private String zipcode;
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public void setWebsite(String website) {
// this.website = website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getParent() {
// return parent;
// }
//
// public void setParent(String parent) {
// this.parent = parent;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getInfo() {
// return info;
// }
//
// public void setInfo(String info) {
// this.info = info;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getProfile() {
// return profile;
// }
//
// public void setProfile(String profile) {
// this.profile = profile;
// }
//
// public String getImg() {
// return img;
// }
//
// public void setImg(String img) {
// this.img = img;
// }
//
// public String getZipcode() {
// return zipcode;
// }
//
// public void setZipcode(String zipcode) {
// this.zipcode = zipcode;
// }
//
// @Override
// public String toString() {
// return "MockBean{" +
// "address='" + address + '\'' +
// ", website='" + website + '\'' +
// ", email='" + email + '\'' +
// ", parent='" + parent + '\'' +
// ", type='" + type + '\'' +
// ", phone='" + phone + '\'' +
// ", info='" + info + '\'' +
// ", city='" + city + '\'' +
// ", name='" + name + '\'' +
// ", profile='" + profile + '\'' +
// ", img='" + img + '\'' +
// ", zipcode='" + zipcode + '\'' +
// '}';
// }
// }
|
import java.util.List;
import retrofit2.http.GET;
import rx.Observable;
import york.com.retrofit2rxjavademo.entity.HttpResult;
import york.com.retrofit2rxjavademo.entity.MockBean;
|
package york.com.retrofit2rxjavademo.http;
/**
* @author YorkYu
* @version V1.0
* @Project: Retrofit2RxjavaDemo
* @Package york.com.retrofit2rxjavademo.http
* @Description:
* @time 2017/3/7 15:38
*/
public interface MockApi {
@GET("mock3")
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/HttpResult.java
// public class HttpResult<T> {
//
// // code 为返回的状态码, message 为返回的消息, 演示的没有这两个字段,考虑到真实的环境中基本包含就在这里写定值
// private int code;
// // this will receive message or status, msg as message field
// @SerializedName(value = "message", alternate = {"status", "msg"})
// private String message;
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
//
// //用来模仿Data
// @SerializedName(value = "data", alternate = {"subjects", "result"})
// private T data;
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
//
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/MockBean.java
// public class MockBean {
// /**
// * address : 北京市海淀区清华大学
// * website : www.tsinghua.edu.cn
// * email : [email protected]
// * parent : 教育部
// * type : 211 985
// * phone : 010-62770334;010-62782051
// * info : 院士:68人 博士点:198个 硕士点:181个
// * city : 北京
// * name : 清华大学
// * profile : 清华简历清华简历清华简历清华简历
// * img : http://img.jidichong.com/school/3.png
// * zipcode : 01022
// */
//
// private String address;
// private String website;
// private String email;
// private String parent;
// private String type;
// private String phone;
// private String info;
// private String city;
// private String name;
// private String profile;
// private String img;
// private String zipcode;
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public void setWebsite(String website) {
// this.website = website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getParent() {
// return parent;
// }
//
// public void setParent(String parent) {
// this.parent = parent;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getInfo() {
// return info;
// }
//
// public void setInfo(String info) {
// this.info = info;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getProfile() {
// return profile;
// }
//
// public void setProfile(String profile) {
// this.profile = profile;
// }
//
// public String getImg() {
// return img;
// }
//
// public void setImg(String img) {
// this.img = img;
// }
//
// public String getZipcode() {
// return zipcode;
// }
//
// public void setZipcode(String zipcode) {
// this.zipcode = zipcode;
// }
//
// @Override
// public String toString() {
// return "MockBean{" +
// "address='" + address + '\'' +
// ", website='" + website + '\'' +
// ", email='" + email + '\'' +
// ", parent='" + parent + '\'' +
// ", type='" + type + '\'' +
// ", phone='" + phone + '\'' +
// ", info='" + info + '\'' +
// ", city='" + city + '\'' +
// ", name='" + name + '\'' +
// ", profile='" + profile + '\'' +
// ", img='" + img + '\'' +
// ", zipcode='" + zipcode + '\'' +
// '}';
// }
// }
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/MockApi.java
import java.util.List;
import retrofit2.http.GET;
import rx.Observable;
import york.com.retrofit2rxjavademo.entity.HttpResult;
import york.com.retrofit2rxjavademo.entity.MockBean;
package york.com.retrofit2rxjavademo.http;
/**
* @author YorkYu
* @version V1.0
* @Project: Retrofit2RxjavaDemo
* @Package york.com.retrofit2rxjavademo.http
* @Description:
* @time 2017/3/7 15:38
*/
public interface MockApi {
@GET("mock3")
|
Observable<HttpResult<MockBean>> getMock3();
|
ysmintor/Retrofit2RxjavaDemo
|
app/src/main/java/york/com/retrofit2rxjavademo/http/MockApi.java
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/HttpResult.java
// public class HttpResult<T> {
//
// // code 为返回的状态码, message 为返回的消息, 演示的没有这两个字段,考虑到真实的环境中基本包含就在这里写定值
// private int code;
// // this will receive message or status, msg as message field
// @SerializedName(value = "message", alternate = {"status", "msg"})
// private String message;
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
//
// //用来模仿Data
// @SerializedName(value = "data", alternate = {"subjects", "result"})
// private T data;
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
//
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/MockBean.java
// public class MockBean {
// /**
// * address : 北京市海淀区清华大学
// * website : www.tsinghua.edu.cn
// * email : [email protected]
// * parent : 教育部
// * type : 211 985
// * phone : 010-62770334;010-62782051
// * info : 院士:68人 博士点:198个 硕士点:181个
// * city : 北京
// * name : 清华大学
// * profile : 清华简历清华简历清华简历清华简历
// * img : http://img.jidichong.com/school/3.png
// * zipcode : 01022
// */
//
// private String address;
// private String website;
// private String email;
// private String parent;
// private String type;
// private String phone;
// private String info;
// private String city;
// private String name;
// private String profile;
// private String img;
// private String zipcode;
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public void setWebsite(String website) {
// this.website = website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getParent() {
// return parent;
// }
//
// public void setParent(String parent) {
// this.parent = parent;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getInfo() {
// return info;
// }
//
// public void setInfo(String info) {
// this.info = info;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getProfile() {
// return profile;
// }
//
// public void setProfile(String profile) {
// this.profile = profile;
// }
//
// public String getImg() {
// return img;
// }
//
// public void setImg(String img) {
// this.img = img;
// }
//
// public String getZipcode() {
// return zipcode;
// }
//
// public void setZipcode(String zipcode) {
// this.zipcode = zipcode;
// }
//
// @Override
// public String toString() {
// return "MockBean{" +
// "address='" + address + '\'' +
// ", website='" + website + '\'' +
// ", email='" + email + '\'' +
// ", parent='" + parent + '\'' +
// ", type='" + type + '\'' +
// ", phone='" + phone + '\'' +
// ", info='" + info + '\'' +
// ", city='" + city + '\'' +
// ", name='" + name + '\'' +
// ", profile='" + profile + '\'' +
// ", img='" + img + '\'' +
// ", zipcode='" + zipcode + '\'' +
// '}';
// }
// }
|
import java.util.List;
import retrofit2.http.GET;
import rx.Observable;
import york.com.retrofit2rxjavademo.entity.HttpResult;
import york.com.retrofit2rxjavademo.entity.MockBean;
|
package york.com.retrofit2rxjavademo.http;
/**
* @author YorkYu
* @version V1.0
* @Project: Retrofit2RxjavaDemo
* @Package york.com.retrofit2rxjavademo.http
* @Description:
* @time 2017/3/7 15:38
*/
public interface MockApi {
@GET("mock3")
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/HttpResult.java
// public class HttpResult<T> {
//
// // code 为返回的状态码, message 为返回的消息, 演示的没有这两个字段,考虑到真实的环境中基本包含就在这里写定值
// private int code;
// // this will receive message or status, msg as message field
// @SerializedName(value = "message", alternate = {"status", "msg"})
// private String message;
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
//
// //用来模仿Data
// @SerializedName(value = "data", alternate = {"subjects", "result"})
// private T data;
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
//
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/entity/MockBean.java
// public class MockBean {
// /**
// * address : 北京市海淀区清华大学
// * website : www.tsinghua.edu.cn
// * email : [email protected]
// * parent : 教育部
// * type : 211 985
// * phone : 010-62770334;010-62782051
// * info : 院士:68人 博士点:198个 硕士点:181个
// * city : 北京
// * name : 清华大学
// * profile : 清华简历清华简历清华简历清华简历
// * img : http://img.jidichong.com/school/3.png
// * zipcode : 01022
// */
//
// private String address;
// private String website;
// private String email;
// private String parent;
// private String type;
// private String phone;
// private String info;
// private String city;
// private String name;
// private String profile;
// private String img;
// private String zipcode;
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public void setWebsite(String website) {
// this.website = website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getParent() {
// return parent;
// }
//
// public void setParent(String parent) {
// this.parent = parent;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getInfo() {
// return info;
// }
//
// public void setInfo(String info) {
// this.info = info;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getProfile() {
// return profile;
// }
//
// public void setProfile(String profile) {
// this.profile = profile;
// }
//
// public String getImg() {
// return img;
// }
//
// public void setImg(String img) {
// this.img = img;
// }
//
// public String getZipcode() {
// return zipcode;
// }
//
// public void setZipcode(String zipcode) {
// this.zipcode = zipcode;
// }
//
// @Override
// public String toString() {
// return "MockBean{" +
// "address='" + address + '\'' +
// ", website='" + website + '\'' +
// ", email='" + email + '\'' +
// ", parent='" + parent + '\'' +
// ", type='" + type + '\'' +
// ", phone='" + phone + '\'' +
// ", info='" + info + '\'' +
// ", city='" + city + '\'' +
// ", name='" + name + '\'' +
// ", profile='" + profile + '\'' +
// ", img='" + img + '\'' +
// ", zipcode='" + zipcode + '\'' +
// '}';
// }
// }
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/MockApi.java
import java.util.List;
import retrofit2.http.GET;
import rx.Observable;
import york.com.retrofit2rxjavademo.entity.HttpResult;
import york.com.retrofit2rxjavademo.entity.MockBean;
package york.com.retrofit2rxjavademo.http;
/**
* @author YorkYu
* @version V1.0
* @Project: Retrofit2RxjavaDemo
* @Package york.com.retrofit2rxjavademo.http
* @Description:
* @time 2017/3/7 15:38
*/
public interface MockApi {
@GET("mock3")
|
Observable<HttpResult<MockBean>> getMock3();
|
ysmintor/Retrofit2RxjavaDemo
|
app/src/main/java/york/com/retrofit2rxjavademo/gsonconverter/CustomGsonResponseBodyConverter.java
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ErrorType.java
// public interface ErrorType {
// /**
// * 正常
// */
// int SUCCESS = 0;
// /**
// * 未知错误
// */
// int UNKNOWN = 1000;
// /**
// * 解析错误
// */
// int PARSE_ERROR = 1001;
// /**
// * 网络错误
// */
// int NETWORD_ERROR = 1002;
// /**
// * 协议出错
// */
// int HTTP_ERROR = 1003;
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ServerException.java
// public class ServerException extends RuntimeException{
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ServerException(String message, int code) {
// super(message);
// this.code = code;
// this.message = message;
// }
// }
|
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import york.com.retrofit2rxjavademo.http.exception.ErrorType;
import york.com.retrofit2rxjavademo.http.exception.ServerException;
import static okhttp3.internal.Util.UTF_8;
|
package york.com.retrofit2rxjavademo.gsonconverter;
/**
* @author YorkYu
* @version V1.0
* @Description:
* @time 2017/3/7 10:30
*/
final class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final TypeAdapter<T> adapter;
private final JsonParser jsonParser;
CustomGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
jsonParser = new JsonParser();
}
@Override
public T convert(ResponseBody value) throws IOException {
String response = value.string();
JsonElement jsonElement = jsonParser.parse(response);
int parseCode = jsonElement.getAsJsonObject().get("code").getAsInt();
//
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ErrorType.java
// public interface ErrorType {
// /**
// * 正常
// */
// int SUCCESS = 0;
// /**
// * 未知错误
// */
// int UNKNOWN = 1000;
// /**
// * 解析错误
// */
// int PARSE_ERROR = 1001;
// /**
// * 网络错误
// */
// int NETWORD_ERROR = 1002;
// /**
// * 协议出错
// */
// int HTTP_ERROR = 1003;
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ServerException.java
// public class ServerException extends RuntimeException{
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ServerException(String message, int code) {
// super(message);
// this.code = code;
// this.message = message;
// }
// }
// Path: app/src/main/java/york/com/retrofit2rxjavademo/gsonconverter/CustomGsonResponseBodyConverter.java
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import york.com.retrofit2rxjavademo.http.exception.ErrorType;
import york.com.retrofit2rxjavademo.http.exception.ServerException;
import static okhttp3.internal.Util.UTF_8;
package york.com.retrofit2rxjavademo.gsonconverter;
/**
* @author YorkYu
* @version V1.0
* @Description:
* @time 2017/3/7 10:30
*/
final class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final TypeAdapter<T> adapter;
private final JsonParser jsonParser;
CustomGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
jsonParser = new JsonParser();
}
@Override
public T convert(ResponseBody value) throws IOException {
String response = value.string();
JsonElement jsonElement = jsonParser.parse(response);
int parseCode = jsonElement.getAsJsonObject().get("code").getAsInt();
//
|
if (parseCode != ErrorType.SUCCESS) {
|
ysmintor/Retrofit2RxjavaDemo
|
app/src/main/java/york/com/retrofit2rxjavademo/gsonconverter/CustomGsonResponseBodyConverter.java
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ErrorType.java
// public interface ErrorType {
// /**
// * 正常
// */
// int SUCCESS = 0;
// /**
// * 未知错误
// */
// int UNKNOWN = 1000;
// /**
// * 解析错误
// */
// int PARSE_ERROR = 1001;
// /**
// * 网络错误
// */
// int NETWORD_ERROR = 1002;
// /**
// * 协议出错
// */
// int HTTP_ERROR = 1003;
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ServerException.java
// public class ServerException extends RuntimeException{
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ServerException(String message, int code) {
// super(message);
// this.code = code;
// this.message = message;
// }
// }
|
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import york.com.retrofit2rxjavademo.http.exception.ErrorType;
import york.com.retrofit2rxjavademo.http.exception.ServerException;
import static okhttp3.internal.Util.UTF_8;
|
package york.com.retrofit2rxjavademo.gsonconverter;
/**
* @author YorkYu
* @version V1.0
* @Description:
* @time 2017/3/7 10:30
*/
final class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final TypeAdapter<T> adapter;
private final JsonParser jsonParser;
CustomGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
jsonParser = new JsonParser();
}
@Override
public T convert(ResponseBody value) throws IOException {
String response = value.string();
JsonElement jsonElement = jsonParser.parse(response);
int parseCode = jsonElement.getAsJsonObject().get("code").getAsInt();
//
if (parseCode != ErrorType.SUCCESS) {
value.close();
String msg = jsonElement.getAsJsonObject().get("data").getAsString();
|
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ErrorType.java
// public interface ErrorType {
// /**
// * 正常
// */
// int SUCCESS = 0;
// /**
// * 未知错误
// */
// int UNKNOWN = 1000;
// /**
// * 解析错误
// */
// int PARSE_ERROR = 1001;
// /**
// * 网络错误
// */
// int NETWORD_ERROR = 1002;
// /**
// * 协议出错
// */
// int HTTP_ERROR = 1003;
// }
//
// Path: app/src/main/java/york/com/retrofit2rxjavademo/http/exception/ServerException.java
// public class ServerException extends RuntimeException{
// // 异常处理,为速度,不必要设置getter和setter
// public int code;
// public String message;
//
// public ServerException(String message, int code) {
// super(message);
// this.code = code;
// this.message = message;
// }
// }
// Path: app/src/main/java/york/com/retrofit2rxjavademo/gsonconverter/CustomGsonResponseBodyConverter.java
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import york.com.retrofit2rxjavademo.http.exception.ErrorType;
import york.com.retrofit2rxjavademo.http.exception.ServerException;
import static okhttp3.internal.Util.UTF_8;
package york.com.retrofit2rxjavademo.gsonconverter;
/**
* @author YorkYu
* @version V1.0
* @Description:
* @time 2017/3/7 10:30
*/
final class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final TypeAdapter<T> adapter;
private final JsonParser jsonParser;
CustomGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
jsonParser = new JsonParser();
}
@Override
public T convert(ResponseBody value) throws IOException {
String response = value.string();
JsonElement jsonElement = jsonParser.parse(response);
int parseCode = jsonElement.getAsJsonObject().get("code").getAsInt();
//
if (parseCode != ErrorType.SUCCESS) {
value.close();
String msg = jsonElement.getAsJsonObject().get("data").getAsString();
|
throw new ServerException(msg, parseCode);
|
it114/OneFramework
|
src/com/it114/android/oneframework/core/util/NetUtil.java
|
// Path: src/com/it114/android/oneframework/core/OneApplication.java
// public class OneApplication extends Application {
// static OneApplication INSTANCE;
// @Override
// public void onCreate() {
// super.onCreate();
// Config.debug = true;
// INSTANCE = this;
// initImageLoader();
// }
//
// public static OneApplication getInstance(){
// return INSTANCE;
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// @Override
// public void onLowMemory() {
// super.onLowMemory();
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// }
//
//
// private void initImageLoader() {
// DisplayImageOptions options = new DisplayImageOptions.Builder()
// .bitmapConfig(Bitmap.Config.RGB_565)
// .imageScaleType(ImageScaleType.EXACTLY)
// .cacheOnDisc(true)
// .displayer(new FadeInBitmapDisplayer(200))
// .build();
// File cacheDir = new File(FileUtil.getCacheDir().getAbsolutePath() + "/" + Constants.IMAGE_CACHE_DIR);
// ImageLoaderConfiguration.Builder configBuilder = null;
// try {
// configBuilder = new ImageLoaderConfiguration.Builder(getApplicationContext())
// .memoryCache(new WeakMemoryCache())
// .diskCache(new LruDiskCache(cacheDir,new Md5FileNameGenerator(),500))
// .denyCacheImageMultipleSizesInMemory()
// .threadPoolSize(3)//线程池内加载的数量
// .threadPriority(Thread.NORM_PRIORITY - 2)
// .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现
// .memoryCacheSize(2 * 1024 * 1024)
// .discCacheSize(50 * 1024 * 1024)
// .discCacheFileNameGenerator(new Md5FileNameGenerator())//将保存的时候的URI名称用MD5 加密
// .tasksProcessingOrder(QueueProcessingType.LIFO)
// .discCacheFileCount(100) //缓存的文件数量
// //.discCache(new UnlimitedDiscCache(cacheDir))
// .defaultDisplayImageOptions(options);
// } catch (IOException e) {
// e.printStackTrace();
// }
// if (BuildConfig.DEBUG) {
// configBuilder.writeDebugLogs();
// }
// ImageLoader.getInstance().init(configBuilder.build());
// }
//
// public void setDebugModel(boolean debugModel){
// if(debugModel) {
// Config.debug = true;
// } else {
// Config.debug = false;
// }
// }
// }
|
import android.content.Context;
import android.net.ConnectivityManager;
import com.it114.android.oneframework.core.OneApplication;
|
package com.it114.android.oneframework.core.util;
/**
* Created by andy on 10/12/2015.
*/
public class NetUtil {
public static boolean isOpenNetwork() {
|
// Path: src/com/it114/android/oneframework/core/OneApplication.java
// public class OneApplication extends Application {
// static OneApplication INSTANCE;
// @Override
// public void onCreate() {
// super.onCreate();
// Config.debug = true;
// INSTANCE = this;
// initImageLoader();
// }
//
// public static OneApplication getInstance(){
// return INSTANCE;
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// @Override
// public void onLowMemory() {
// super.onLowMemory();
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// }
//
//
// private void initImageLoader() {
// DisplayImageOptions options = new DisplayImageOptions.Builder()
// .bitmapConfig(Bitmap.Config.RGB_565)
// .imageScaleType(ImageScaleType.EXACTLY)
// .cacheOnDisc(true)
// .displayer(new FadeInBitmapDisplayer(200))
// .build();
// File cacheDir = new File(FileUtil.getCacheDir().getAbsolutePath() + "/" + Constants.IMAGE_CACHE_DIR);
// ImageLoaderConfiguration.Builder configBuilder = null;
// try {
// configBuilder = new ImageLoaderConfiguration.Builder(getApplicationContext())
// .memoryCache(new WeakMemoryCache())
// .diskCache(new LruDiskCache(cacheDir,new Md5FileNameGenerator(),500))
// .denyCacheImageMultipleSizesInMemory()
// .threadPoolSize(3)//线程池内加载的数量
// .threadPriority(Thread.NORM_PRIORITY - 2)
// .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现
// .memoryCacheSize(2 * 1024 * 1024)
// .discCacheSize(50 * 1024 * 1024)
// .discCacheFileNameGenerator(new Md5FileNameGenerator())//将保存的时候的URI名称用MD5 加密
// .tasksProcessingOrder(QueueProcessingType.LIFO)
// .discCacheFileCount(100) //缓存的文件数量
// //.discCache(new UnlimitedDiscCache(cacheDir))
// .defaultDisplayImageOptions(options);
// } catch (IOException e) {
// e.printStackTrace();
// }
// if (BuildConfig.DEBUG) {
// configBuilder.writeDebugLogs();
// }
// ImageLoader.getInstance().init(configBuilder.build());
// }
//
// public void setDebugModel(boolean debugModel){
// if(debugModel) {
// Config.debug = true;
// } else {
// Config.debug = false;
// }
// }
// }
// Path: src/com/it114/android/oneframework/core/util/NetUtil.java
import android.content.Context;
import android.net.ConnectivityManager;
import com.it114.android.oneframework.core.OneApplication;
package com.it114.android.oneframework.core.util;
/**
* Created by andy on 10/12/2015.
*/
public class NetUtil {
public static boolean isOpenNetwork() {
|
ConnectivityManager connManager = (ConnectivityManager) OneApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
|
it114/OneFramework
|
src/com/it114/android/oneframework/core/util/FileUtil.java
|
// Path: src/com/it114/android/oneframework/core/OneApplication.java
// public class OneApplication extends Application {
// static OneApplication INSTANCE;
// @Override
// public void onCreate() {
// super.onCreate();
// Config.debug = true;
// INSTANCE = this;
// initImageLoader();
// }
//
// public static OneApplication getInstance(){
// return INSTANCE;
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// @Override
// public void onLowMemory() {
// super.onLowMemory();
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// }
//
//
// private void initImageLoader() {
// DisplayImageOptions options = new DisplayImageOptions.Builder()
// .bitmapConfig(Bitmap.Config.RGB_565)
// .imageScaleType(ImageScaleType.EXACTLY)
// .cacheOnDisc(true)
// .displayer(new FadeInBitmapDisplayer(200))
// .build();
// File cacheDir = new File(FileUtil.getCacheDir().getAbsolutePath() + "/" + Constants.IMAGE_CACHE_DIR);
// ImageLoaderConfiguration.Builder configBuilder = null;
// try {
// configBuilder = new ImageLoaderConfiguration.Builder(getApplicationContext())
// .memoryCache(new WeakMemoryCache())
// .diskCache(new LruDiskCache(cacheDir,new Md5FileNameGenerator(),500))
// .denyCacheImageMultipleSizesInMemory()
// .threadPoolSize(3)//线程池内加载的数量
// .threadPriority(Thread.NORM_PRIORITY - 2)
// .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现
// .memoryCacheSize(2 * 1024 * 1024)
// .discCacheSize(50 * 1024 * 1024)
// .discCacheFileNameGenerator(new Md5FileNameGenerator())//将保存的时候的URI名称用MD5 加密
// .tasksProcessingOrder(QueueProcessingType.LIFO)
// .discCacheFileCount(100) //缓存的文件数量
// //.discCache(new UnlimitedDiscCache(cacheDir))
// .defaultDisplayImageOptions(options);
// } catch (IOException e) {
// e.printStackTrace();
// }
// if (BuildConfig.DEBUG) {
// configBuilder.writeDebugLogs();
// }
// ImageLoader.getInstance().init(configBuilder.build());
// }
//
// public void setDebugModel(boolean debugModel){
// if(debugModel) {
// Config.debug = true;
// } else {
// Config.debug = false;
// }
// }
// }
|
import android.os.Environment;
import com.it114.android.oneframework.core.OneApplication;
import java.io.File;
|
package com.it114.android.oneframework.core.util;
/**
* Created by andy on 10/10/2015.
*/
public class FileUtil {
/**
* 得到app缓存文件夹,优先使用外部存储设备
* @return
*/
public static File getCacheDir(){
|
// Path: src/com/it114/android/oneframework/core/OneApplication.java
// public class OneApplication extends Application {
// static OneApplication INSTANCE;
// @Override
// public void onCreate() {
// super.onCreate();
// Config.debug = true;
// INSTANCE = this;
// initImageLoader();
// }
//
// public static OneApplication getInstance(){
// return INSTANCE;
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// @Override
// public void onLowMemory() {
// super.onLowMemory();
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// }
//
//
// private void initImageLoader() {
// DisplayImageOptions options = new DisplayImageOptions.Builder()
// .bitmapConfig(Bitmap.Config.RGB_565)
// .imageScaleType(ImageScaleType.EXACTLY)
// .cacheOnDisc(true)
// .displayer(new FadeInBitmapDisplayer(200))
// .build();
// File cacheDir = new File(FileUtil.getCacheDir().getAbsolutePath() + "/" + Constants.IMAGE_CACHE_DIR);
// ImageLoaderConfiguration.Builder configBuilder = null;
// try {
// configBuilder = new ImageLoaderConfiguration.Builder(getApplicationContext())
// .memoryCache(new WeakMemoryCache())
// .diskCache(new LruDiskCache(cacheDir,new Md5FileNameGenerator(),500))
// .denyCacheImageMultipleSizesInMemory()
// .threadPoolSize(3)//线程池内加载的数量
// .threadPriority(Thread.NORM_PRIORITY - 2)
// .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现
// .memoryCacheSize(2 * 1024 * 1024)
// .discCacheSize(50 * 1024 * 1024)
// .discCacheFileNameGenerator(new Md5FileNameGenerator())//将保存的时候的URI名称用MD5 加密
// .tasksProcessingOrder(QueueProcessingType.LIFO)
// .discCacheFileCount(100) //缓存的文件数量
// //.discCache(new UnlimitedDiscCache(cacheDir))
// .defaultDisplayImageOptions(options);
// } catch (IOException e) {
// e.printStackTrace();
// }
// if (BuildConfig.DEBUG) {
// configBuilder.writeDebugLogs();
// }
// ImageLoader.getInstance().init(configBuilder.build());
// }
//
// public void setDebugModel(boolean debugModel){
// if(debugModel) {
// Config.debug = true;
// } else {
// Config.debug = false;
// }
// }
// }
// Path: src/com/it114/android/oneframework/core/util/FileUtil.java
import android.os.Environment;
import com.it114.android.oneframework.core.OneApplication;
import java.io.File;
package com.it114.android.oneframework.core.util;
/**
* Created by andy on 10/10/2015.
*/
public class FileUtil {
/**
* 得到app缓存文件夹,优先使用外部存储设备
* @return
*/
public static File getCacheDir(){
|
File cacheDir = OneApplication.getInstance().getCacheDir();
|
it114/OneFramework
|
src/com/it114/android/oneframework/core/util/LogUtil.java
|
// Path: src/com/it114/android/oneframework/core/data/Config.java
// public class Config {
// public static final String VERSION = "1.0.0";// framework version
// public static boolean debug = true;
// public static String API_HOST_DEBUG = "";
// public static String API_HOST_RELEASE = "";
//
//
// }
|
import com.it114.android.oneframework.core.data.Config;
|
package com.it114.android.oneframework.core.util;
public class LogUtil {
private final static String TAG = "oneapi";
private static String checkTag(String tag){
return (tag == null)?TAG:tag;
}
public static void v(String tag, String msg) {
|
// Path: src/com/it114/android/oneframework/core/data/Config.java
// public class Config {
// public static final String VERSION = "1.0.0";// framework version
// public static boolean debug = true;
// public static String API_HOST_DEBUG = "";
// public static String API_HOST_RELEASE = "";
//
//
// }
// Path: src/com/it114/android/oneframework/core/util/LogUtil.java
import com.it114.android.oneframework.core.data.Config;
package com.it114.android.oneframework.core.util;
public class LogUtil {
private final static String TAG = "oneapi";
private static String checkTag(String tag){
return (tag == null)?TAG:tag;
}
public static void v(String tag, String msg) {
|
if (Config.debug)
|
it114/OneFramework
|
src/com/it114/android/oneframework/core/data/db/HttpCacheTable.java
|
// Path: src/com/it114/android/oneframework/core/OneApplication.java
// public class OneApplication extends Application {
// static OneApplication INSTANCE;
// @Override
// public void onCreate() {
// super.onCreate();
// Config.debug = true;
// INSTANCE = this;
// initImageLoader();
// }
//
// public static OneApplication getInstance(){
// return INSTANCE;
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// @Override
// public void onLowMemory() {
// super.onLowMemory();
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// }
//
//
// private void initImageLoader() {
// DisplayImageOptions options = new DisplayImageOptions.Builder()
// .bitmapConfig(Bitmap.Config.RGB_565)
// .imageScaleType(ImageScaleType.EXACTLY)
// .cacheOnDisc(true)
// .displayer(new FadeInBitmapDisplayer(200))
// .build();
// File cacheDir = new File(FileUtil.getCacheDir().getAbsolutePath() + "/" + Constants.IMAGE_CACHE_DIR);
// ImageLoaderConfiguration.Builder configBuilder = null;
// try {
// configBuilder = new ImageLoaderConfiguration.Builder(getApplicationContext())
// .memoryCache(new WeakMemoryCache())
// .diskCache(new LruDiskCache(cacheDir,new Md5FileNameGenerator(),500))
// .denyCacheImageMultipleSizesInMemory()
// .threadPoolSize(3)//线程池内加载的数量
// .threadPriority(Thread.NORM_PRIORITY - 2)
// .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现
// .memoryCacheSize(2 * 1024 * 1024)
// .discCacheSize(50 * 1024 * 1024)
// .discCacheFileNameGenerator(new Md5FileNameGenerator())//将保存的时候的URI名称用MD5 加密
// .tasksProcessingOrder(QueueProcessingType.LIFO)
// .discCacheFileCount(100) //缓存的文件数量
// //.discCache(new UnlimitedDiscCache(cacheDir))
// .defaultDisplayImageOptions(options);
// } catch (IOException e) {
// e.printStackTrace();
// }
// if (BuildConfig.DEBUG) {
// configBuilder.writeDebugLogs();
// }
// ImageLoader.getInstance().init(configBuilder.build());
// }
//
// public void setDebugModel(boolean debugModel){
// if(debugModel) {
// Config.debug = true;
// } else {
// Config.debug = false;
// }
// }
// }
//
// Path: src/com/it114/android/oneframework/core/bean/BaseBean.java
// public class BaseBean implements Serializable {
// private static final long serialVersionUID = 2015082101L;
// public String msg="";
// public int code;
// }
//
// Path: src/com/it114/android/oneframework/core/bean/HttpCache.java
// public class HttpCache extends BaseBean {
// public Integer id;
// public String key;//请求地址和请求参数的md5
// public String url;//请求地址
// public String params;//请求参数
// public String content;//服务器返回数据
// public Long updateTime;//更新时间
// }
|
import android.content.ContentValues;
import android.database.Cursor;
import com.it114.android.oneframework.core.OneApplication;
import com.it114.android.oneframework.core.bean.BaseBean;
import com.it114.android.oneframework.core.bean.HttpCache;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
|
package com.it114.android.oneframework.core.data.db;
public class HttpCacheTable extends Datatable {
public static final String TABLE_NAME = "httpCache";
public static final String COLOMN_KEY = "key";
public static final String COLOMN_URL = "url";
public static final String COLOMN_PARAMS = "params";
public static final String COLOMN_CONTENT = "content";
public static final String COLOMN_UPDATETIME = "updateTime";
private static final Map<String, String> mColumnMap = new HashMap<String, String>();
static {
mColumnMap.put(_ID, "integer primary key autoincrement");
mColumnMap.put(COLOMN_KEY, "varchar(350) UNIQUE");
mColumnMap.put(COLOMN_URL, "text");
mColumnMap.put(COLOMN_PARAMS, "text");
mColumnMap.put(COLOMN_CONTENT, "text");
mColumnMap.put(COLOMN_UPDATETIME, "integer");
}
@Override
public String getTableName() {
return TABLE_NAME;
}
@Override
protected Map<String, String> getTableMap() {
return mColumnMap;
}
|
// Path: src/com/it114/android/oneframework/core/OneApplication.java
// public class OneApplication extends Application {
// static OneApplication INSTANCE;
// @Override
// public void onCreate() {
// super.onCreate();
// Config.debug = true;
// INSTANCE = this;
// initImageLoader();
// }
//
// public static OneApplication getInstance(){
// return INSTANCE;
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// @Override
// public void onLowMemory() {
// super.onLowMemory();
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// }
//
//
// private void initImageLoader() {
// DisplayImageOptions options = new DisplayImageOptions.Builder()
// .bitmapConfig(Bitmap.Config.RGB_565)
// .imageScaleType(ImageScaleType.EXACTLY)
// .cacheOnDisc(true)
// .displayer(new FadeInBitmapDisplayer(200))
// .build();
// File cacheDir = new File(FileUtil.getCacheDir().getAbsolutePath() + "/" + Constants.IMAGE_CACHE_DIR);
// ImageLoaderConfiguration.Builder configBuilder = null;
// try {
// configBuilder = new ImageLoaderConfiguration.Builder(getApplicationContext())
// .memoryCache(new WeakMemoryCache())
// .diskCache(new LruDiskCache(cacheDir,new Md5FileNameGenerator(),500))
// .denyCacheImageMultipleSizesInMemory()
// .threadPoolSize(3)//线程池内加载的数量
// .threadPriority(Thread.NORM_PRIORITY - 2)
// .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现
// .memoryCacheSize(2 * 1024 * 1024)
// .discCacheSize(50 * 1024 * 1024)
// .discCacheFileNameGenerator(new Md5FileNameGenerator())//将保存的时候的URI名称用MD5 加密
// .tasksProcessingOrder(QueueProcessingType.LIFO)
// .discCacheFileCount(100) //缓存的文件数量
// //.discCache(new UnlimitedDiscCache(cacheDir))
// .defaultDisplayImageOptions(options);
// } catch (IOException e) {
// e.printStackTrace();
// }
// if (BuildConfig.DEBUG) {
// configBuilder.writeDebugLogs();
// }
// ImageLoader.getInstance().init(configBuilder.build());
// }
//
// public void setDebugModel(boolean debugModel){
// if(debugModel) {
// Config.debug = true;
// } else {
// Config.debug = false;
// }
// }
// }
//
// Path: src/com/it114/android/oneframework/core/bean/BaseBean.java
// public class BaseBean implements Serializable {
// private static final long serialVersionUID = 2015082101L;
// public String msg="";
// public int code;
// }
//
// Path: src/com/it114/android/oneframework/core/bean/HttpCache.java
// public class HttpCache extends BaseBean {
// public Integer id;
// public String key;//请求地址和请求参数的md5
// public String url;//请求地址
// public String params;//请求参数
// public String content;//服务器返回数据
// public Long updateTime;//更新时间
// }
// Path: src/com/it114/android/oneframework/core/data/db/HttpCacheTable.java
import android.content.ContentValues;
import android.database.Cursor;
import com.it114.android.oneframework.core.OneApplication;
import com.it114.android.oneframework.core.bean.BaseBean;
import com.it114.android.oneframework.core.bean.HttpCache;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
package com.it114.android.oneframework.core.data.db;
public class HttpCacheTable extends Datatable {
public static final String TABLE_NAME = "httpCache";
public static final String COLOMN_KEY = "key";
public static final String COLOMN_URL = "url";
public static final String COLOMN_PARAMS = "params";
public static final String COLOMN_CONTENT = "content";
public static final String COLOMN_UPDATETIME = "updateTime";
private static final Map<String, String> mColumnMap = new HashMap<String, String>();
static {
mColumnMap.put(_ID, "integer primary key autoincrement");
mColumnMap.put(COLOMN_KEY, "varchar(350) UNIQUE");
mColumnMap.put(COLOMN_URL, "text");
mColumnMap.put(COLOMN_PARAMS, "text");
mColumnMap.put(COLOMN_CONTENT, "text");
mColumnMap.put(COLOMN_UPDATETIME, "integer");
}
@Override
public String getTableName() {
return TABLE_NAME;
}
@Override
protected Map<String, String> getTableMap() {
return mColumnMap;
}
|
public static ContentValues toContentValues(BaseBean model) {
|
it114/OneFramework
|
src/com/it114/android/oneframework/core/data/db/HttpCacheTable.java
|
// Path: src/com/it114/android/oneframework/core/OneApplication.java
// public class OneApplication extends Application {
// static OneApplication INSTANCE;
// @Override
// public void onCreate() {
// super.onCreate();
// Config.debug = true;
// INSTANCE = this;
// initImageLoader();
// }
//
// public static OneApplication getInstance(){
// return INSTANCE;
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// @Override
// public void onLowMemory() {
// super.onLowMemory();
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// }
//
//
// private void initImageLoader() {
// DisplayImageOptions options = new DisplayImageOptions.Builder()
// .bitmapConfig(Bitmap.Config.RGB_565)
// .imageScaleType(ImageScaleType.EXACTLY)
// .cacheOnDisc(true)
// .displayer(new FadeInBitmapDisplayer(200))
// .build();
// File cacheDir = new File(FileUtil.getCacheDir().getAbsolutePath() + "/" + Constants.IMAGE_CACHE_DIR);
// ImageLoaderConfiguration.Builder configBuilder = null;
// try {
// configBuilder = new ImageLoaderConfiguration.Builder(getApplicationContext())
// .memoryCache(new WeakMemoryCache())
// .diskCache(new LruDiskCache(cacheDir,new Md5FileNameGenerator(),500))
// .denyCacheImageMultipleSizesInMemory()
// .threadPoolSize(3)//线程池内加载的数量
// .threadPriority(Thread.NORM_PRIORITY - 2)
// .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现
// .memoryCacheSize(2 * 1024 * 1024)
// .discCacheSize(50 * 1024 * 1024)
// .discCacheFileNameGenerator(new Md5FileNameGenerator())//将保存的时候的URI名称用MD5 加密
// .tasksProcessingOrder(QueueProcessingType.LIFO)
// .discCacheFileCount(100) //缓存的文件数量
// //.discCache(new UnlimitedDiscCache(cacheDir))
// .defaultDisplayImageOptions(options);
// } catch (IOException e) {
// e.printStackTrace();
// }
// if (BuildConfig.DEBUG) {
// configBuilder.writeDebugLogs();
// }
// ImageLoader.getInstance().init(configBuilder.build());
// }
//
// public void setDebugModel(boolean debugModel){
// if(debugModel) {
// Config.debug = true;
// } else {
// Config.debug = false;
// }
// }
// }
//
// Path: src/com/it114/android/oneframework/core/bean/BaseBean.java
// public class BaseBean implements Serializable {
// private static final long serialVersionUID = 2015082101L;
// public String msg="";
// public int code;
// }
//
// Path: src/com/it114/android/oneframework/core/bean/HttpCache.java
// public class HttpCache extends BaseBean {
// public Integer id;
// public String key;//请求地址和请求参数的md5
// public String url;//请求地址
// public String params;//请求参数
// public String content;//服务器返回数据
// public Long updateTime;//更新时间
// }
|
import android.content.ContentValues;
import android.database.Cursor;
import com.it114.android.oneframework.core.OneApplication;
import com.it114.android.oneframework.core.bean.BaseBean;
import com.it114.android.oneframework.core.bean.HttpCache;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
|
package com.it114.android.oneframework.core.data.db;
public class HttpCacheTable extends Datatable {
public static final String TABLE_NAME = "httpCache";
public static final String COLOMN_KEY = "key";
public static final String COLOMN_URL = "url";
public static final String COLOMN_PARAMS = "params";
public static final String COLOMN_CONTENT = "content";
public static final String COLOMN_UPDATETIME = "updateTime";
private static final Map<String, String> mColumnMap = new HashMap<String, String>();
static {
mColumnMap.put(_ID, "integer primary key autoincrement");
mColumnMap.put(COLOMN_KEY, "varchar(350) UNIQUE");
mColumnMap.put(COLOMN_URL, "text");
mColumnMap.put(COLOMN_PARAMS, "text");
mColumnMap.put(COLOMN_CONTENT, "text");
mColumnMap.put(COLOMN_UPDATETIME, "integer");
}
@Override
public String getTableName() {
return TABLE_NAME;
}
@Override
protected Map<String, String> getTableMap() {
return mColumnMap;
}
public static ContentValues toContentValues(BaseBean model) {
|
// Path: src/com/it114/android/oneframework/core/OneApplication.java
// public class OneApplication extends Application {
// static OneApplication INSTANCE;
// @Override
// public void onCreate() {
// super.onCreate();
// Config.debug = true;
// INSTANCE = this;
// initImageLoader();
// }
//
// public static OneApplication getInstance(){
// return INSTANCE;
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// @Override
// public void onLowMemory() {
// super.onLowMemory();
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// }
//
//
// private void initImageLoader() {
// DisplayImageOptions options = new DisplayImageOptions.Builder()
// .bitmapConfig(Bitmap.Config.RGB_565)
// .imageScaleType(ImageScaleType.EXACTLY)
// .cacheOnDisc(true)
// .displayer(new FadeInBitmapDisplayer(200))
// .build();
// File cacheDir = new File(FileUtil.getCacheDir().getAbsolutePath() + "/" + Constants.IMAGE_CACHE_DIR);
// ImageLoaderConfiguration.Builder configBuilder = null;
// try {
// configBuilder = new ImageLoaderConfiguration.Builder(getApplicationContext())
// .memoryCache(new WeakMemoryCache())
// .diskCache(new LruDiskCache(cacheDir,new Md5FileNameGenerator(),500))
// .denyCacheImageMultipleSizesInMemory()
// .threadPoolSize(3)//线程池内加载的数量
// .threadPriority(Thread.NORM_PRIORITY - 2)
// .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现
// .memoryCacheSize(2 * 1024 * 1024)
// .discCacheSize(50 * 1024 * 1024)
// .discCacheFileNameGenerator(new Md5FileNameGenerator())//将保存的时候的URI名称用MD5 加密
// .tasksProcessingOrder(QueueProcessingType.LIFO)
// .discCacheFileCount(100) //缓存的文件数量
// //.discCache(new UnlimitedDiscCache(cacheDir))
// .defaultDisplayImageOptions(options);
// } catch (IOException e) {
// e.printStackTrace();
// }
// if (BuildConfig.DEBUG) {
// configBuilder.writeDebugLogs();
// }
// ImageLoader.getInstance().init(configBuilder.build());
// }
//
// public void setDebugModel(boolean debugModel){
// if(debugModel) {
// Config.debug = true;
// } else {
// Config.debug = false;
// }
// }
// }
//
// Path: src/com/it114/android/oneframework/core/bean/BaseBean.java
// public class BaseBean implements Serializable {
// private static final long serialVersionUID = 2015082101L;
// public String msg="";
// public int code;
// }
//
// Path: src/com/it114/android/oneframework/core/bean/HttpCache.java
// public class HttpCache extends BaseBean {
// public Integer id;
// public String key;//请求地址和请求参数的md5
// public String url;//请求地址
// public String params;//请求参数
// public String content;//服务器返回数据
// public Long updateTime;//更新时间
// }
// Path: src/com/it114/android/oneframework/core/data/db/HttpCacheTable.java
import android.content.ContentValues;
import android.database.Cursor;
import com.it114.android.oneframework.core.OneApplication;
import com.it114.android.oneframework.core.bean.BaseBean;
import com.it114.android.oneframework.core.bean.HttpCache;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
package com.it114.android.oneframework.core.data.db;
public class HttpCacheTable extends Datatable {
public static final String TABLE_NAME = "httpCache";
public static final String COLOMN_KEY = "key";
public static final String COLOMN_URL = "url";
public static final String COLOMN_PARAMS = "params";
public static final String COLOMN_CONTENT = "content";
public static final String COLOMN_UPDATETIME = "updateTime";
private static final Map<String, String> mColumnMap = new HashMap<String, String>();
static {
mColumnMap.put(_ID, "integer primary key autoincrement");
mColumnMap.put(COLOMN_KEY, "varchar(350) UNIQUE");
mColumnMap.put(COLOMN_URL, "text");
mColumnMap.put(COLOMN_PARAMS, "text");
mColumnMap.put(COLOMN_CONTENT, "text");
mColumnMap.put(COLOMN_UPDATETIME, "integer");
}
@Override
public String getTableName() {
return TABLE_NAME;
}
@Override
protected Map<String, String> getTableMap() {
return mColumnMap;
}
public static ContentValues toContentValues(BaseBean model) {
|
HttpCache httpCache = (HttpCache) model;
|
it114/OneFramework
|
src/com/it114/android/oneframework/core/data/db/HttpCacheTable.java
|
// Path: src/com/it114/android/oneframework/core/OneApplication.java
// public class OneApplication extends Application {
// static OneApplication INSTANCE;
// @Override
// public void onCreate() {
// super.onCreate();
// Config.debug = true;
// INSTANCE = this;
// initImageLoader();
// }
//
// public static OneApplication getInstance(){
// return INSTANCE;
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// @Override
// public void onLowMemory() {
// super.onLowMemory();
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// }
//
//
// private void initImageLoader() {
// DisplayImageOptions options = new DisplayImageOptions.Builder()
// .bitmapConfig(Bitmap.Config.RGB_565)
// .imageScaleType(ImageScaleType.EXACTLY)
// .cacheOnDisc(true)
// .displayer(new FadeInBitmapDisplayer(200))
// .build();
// File cacheDir = new File(FileUtil.getCacheDir().getAbsolutePath() + "/" + Constants.IMAGE_CACHE_DIR);
// ImageLoaderConfiguration.Builder configBuilder = null;
// try {
// configBuilder = new ImageLoaderConfiguration.Builder(getApplicationContext())
// .memoryCache(new WeakMemoryCache())
// .diskCache(new LruDiskCache(cacheDir,new Md5FileNameGenerator(),500))
// .denyCacheImageMultipleSizesInMemory()
// .threadPoolSize(3)//线程池内加载的数量
// .threadPriority(Thread.NORM_PRIORITY - 2)
// .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现
// .memoryCacheSize(2 * 1024 * 1024)
// .discCacheSize(50 * 1024 * 1024)
// .discCacheFileNameGenerator(new Md5FileNameGenerator())//将保存的时候的URI名称用MD5 加密
// .tasksProcessingOrder(QueueProcessingType.LIFO)
// .discCacheFileCount(100) //缓存的文件数量
// //.discCache(new UnlimitedDiscCache(cacheDir))
// .defaultDisplayImageOptions(options);
// } catch (IOException e) {
// e.printStackTrace();
// }
// if (BuildConfig.DEBUG) {
// configBuilder.writeDebugLogs();
// }
// ImageLoader.getInstance().init(configBuilder.build());
// }
//
// public void setDebugModel(boolean debugModel){
// if(debugModel) {
// Config.debug = true;
// } else {
// Config.debug = false;
// }
// }
// }
//
// Path: src/com/it114/android/oneframework/core/bean/BaseBean.java
// public class BaseBean implements Serializable {
// private static final long serialVersionUID = 2015082101L;
// public String msg="";
// public int code;
// }
//
// Path: src/com/it114/android/oneframework/core/bean/HttpCache.java
// public class HttpCache extends BaseBean {
// public Integer id;
// public String key;//请求地址和请求参数的md5
// public String url;//请求地址
// public String params;//请求参数
// public String content;//服务器返回数据
// public Long updateTime;//更新时间
// }
|
import android.content.ContentValues;
import android.database.Cursor;
import com.it114.android.oneframework.core.OneApplication;
import com.it114.android.oneframework.core.bean.BaseBean;
import com.it114.android.oneframework.core.bean.HttpCache;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
|
mColumnMap.put(COLOMN_KEY, "varchar(350) UNIQUE");
mColumnMap.put(COLOMN_URL, "text");
mColumnMap.put(COLOMN_PARAMS, "text");
mColumnMap.put(COLOMN_CONTENT, "text");
mColumnMap.put(COLOMN_UPDATETIME, "integer");
}
@Override
public String getTableName() {
return TABLE_NAME;
}
@Override
protected Map<String, String> getTableMap() {
return mColumnMap;
}
public static ContentValues toContentValues(BaseBean model) {
HttpCache httpCache = (HttpCache) model;
ContentValues values = new ContentValues();
values.put(COLOMN_KEY,httpCache.key);
values.put(COLOMN_CONTENT,httpCache.content);
values.put(COLOMN_URL,httpCache.url);
values.put(COLOMN_PARAMS,httpCache.params);
values.put(COLOMN_UPDATETIME,httpCache.updateTime);
return values;
}
public static void insert(HttpCache cache){
ContentValues values = toContentValues(cache);
|
// Path: src/com/it114/android/oneframework/core/OneApplication.java
// public class OneApplication extends Application {
// static OneApplication INSTANCE;
// @Override
// public void onCreate() {
// super.onCreate();
// Config.debug = true;
// INSTANCE = this;
// initImageLoader();
// }
//
// public static OneApplication getInstance(){
// return INSTANCE;
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// @Override
// public void onLowMemory() {
// super.onLowMemory();
// }
//
// @Override
// public void onTrimMemory(int level) {
// super.onTrimMemory(level);
// }
//
//
// private void initImageLoader() {
// DisplayImageOptions options = new DisplayImageOptions.Builder()
// .bitmapConfig(Bitmap.Config.RGB_565)
// .imageScaleType(ImageScaleType.EXACTLY)
// .cacheOnDisc(true)
// .displayer(new FadeInBitmapDisplayer(200))
// .build();
// File cacheDir = new File(FileUtil.getCacheDir().getAbsolutePath() + "/" + Constants.IMAGE_CACHE_DIR);
// ImageLoaderConfiguration.Builder configBuilder = null;
// try {
// configBuilder = new ImageLoaderConfiguration.Builder(getApplicationContext())
// .memoryCache(new WeakMemoryCache())
// .diskCache(new LruDiskCache(cacheDir,new Md5FileNameGenerator(),500))
// .denyCacheImageMultipleSizesInMemory()
// .threadPoolSize(3)//线程池内加载的数量
// .threadPriority(Thread.NORM_PRIORITY - 2)
// .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现
// .memoryCacheSize(2 * 1024 * 1024)
// .discCacheSize(50 * 1024 * 1024)
// .discCacheFileNameGenerator(new Md5FileNameGenerator())//将保存的时候的URI名称用MD5 加密
// .tasksProcessingOrder(QueueProcessingType.LIFO)
// .discCacheFileCount(100) //缓存的文件数量
// //.discCache(new UnlimitedDiscCache(cacheDir))
// .defaultDisplayImageOptions(options);
// } catch (IOException e) {
// e.printStackTrace();
// }
// if (BuildConfig.DEBUG) {
// configBuilder.writeDebugLogs();
// }
// ImageLoader.getInstance().init(configBuilder.build());
// }
//
// public void setDebugModel(boolean debugModel){
// if(debugModel) {
// Config.debug = true;
// } else {
// Config.debug = false;
// }
// }
// }
//
// Path: src/com/it114/android/oneframework/core/bean/BaseBean.java
// public class BaseBean implements Serializable {
// private static final long serialVersionUID = 2015082101L;
// public String msg="";
// public int code;
// }
//
// Path: src/com/it114/android/oneframework/core/bean/HttpCache.java
// public class HttpCache extends BaseBean {
// public Integer id;
// public String key;//请求地址和请求参数的md5
// public String url;//请求地址
// public String params;//请求参数
// public String content;//服务器返回数据
// public Long updateTime;//更新时间
// }
// Path: src/com/it114/android/oneframework/core/data/db/HttpCacheTable.java
import android.content.ContentValues;
import android.database.Cursor;
import com.it114.android.oneframework.core.OneApplication;
import com.it114.android.oneframework.core.bean.BaseBean;
import com.it114.android.oneframework.core.bean.HttpCache;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
mColumnMap.put(COLOMN_KEY, "varchar(350) UNIQUE");
mColumnMap.put(COLOMN_URL, "text");
mColumnMap.put(COLOMN_PARAMS, "text");
mColumnMap.put(COLOMN_CONTENT, "text");
mColumnMap.put(COLOMN_UPDATETIME, "integer");
}
@Override
public String getTableName() {
return TABLE_NAME;
}
@Override
protected Map<String, String> getTableMap() {
return mColumnMap;
}
public static ContentValues toContentValues(BaseBean model) {
HttpCache httpCache = (HttpCache) model;
ContentValues values = new ContentValues();
values.put(COLOMN_KEY,httpCache.key);
values.put(COLOMN_CONTENT,httpCache.content);
values.put(COLOMN_URL,httpCache.url);
values.put(COLOMN_PARAMS,httpCache.params);
values.put(COLOMN_UPDATETIME,httpCache.updateTime);
return values;
}
public static void insert(HttpCache cache){
ContentValues values = toContentValues(cache);
|
DBHelper.getInstance(OneApplication.getInstance()).insert(TABLE_NAME, values);
|
it114/OneFramework
|
Sample1/src/com/it114/android/oneframework/sample1/demo/adapter/AdapterActivity.java
|
// Path: src/com/it114/android/oneframework/core/ui/activity/BaseActivity.java
// public abstract class BaseActivity extends Activity{
// protected final static String TAG = BaseFragmentActivity.class.getName();
// public ActivityCommon activityState = new ActivityCommonImpl();
// protected ViewFinder mViewFinder;
// protected View titleBar;
// protected TitleBarViewImpl titleBarView;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(getLayoutId());
// ButterKnife.bind(this);
// activityState.create(savedInstanceState);
// init(savedInstanceState);
// }
//
// public void initTitleBar(int titleBarLayoutId,TitleBarListener listener){
// if(titleBarLayoutId>0){
// if(this.titleBar == null)
// this.titleBar = findViewByIdWithFinder(titleBarLayoutId);
// this.titleBarView = new TitleBarViewImpl(this,titleBar);
// if(listener!=null){
// this.titleBarView.setTitleBarListener(listener);
// }
// } else {
// LogUtil.w(TAG, "invalid titleBarLayoutId");
// }
// }
//
//
// @Override
// public void setContentView(int layoutResID) {
// super.setContentView(layoutResID);
// mViewFinder = new ViewFinder(getWindow().getDecorView());
// }
//
// @Override
// public void setContentView(View view) {
// super.setContentView(view);
// mViewFinder = new ViewFinder(view);
// }
//
// @Override
// public void setContentView(View view, ViewGroup.LayoutParams params) {
// super.setContentView(view, params);
// mViewFinder = new ViewFinder(view);
// }
//
// public <T extends View> T findViewByIdWithFinder(int id) {
// return mViewFinder.findViewById(id);
// }
//
// protected abstract void init(Bundle savedInstanceState);
//
// protected abstract int getLayoutId();
//
// @Override
// public void onStart() {
// super.onStart();
// activityState.start();
//
// }
//
// @Override
// public void onStop() {
// super.onStop();
// activityState.stop();
//
// }
//
// @Override
// protected void onRestart() {
// super.onRestart();
// activityState.restart();
//
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// activityState.resume();
//
// }
//
// @Override
// protected void onPause() {
// super.onPause();
// activityState.pause();
//
// }
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// activityState.destroy();
// }
//
//
//
//
// }
//
// Path: Sample1/src/com/it114/android/oneframework/sample1/bean/TestBean.java
// public class TestBean {
//
// public String username;
// public String password;
// public int age;
// public String signature;//签名
// public String icoImageUrl;//头像
//
// public static ArrayList<TestBean> createDataList(int size){
// ArrayList<TestBean> beans = new ArrayList<>();
// for(int i=0;i<size;i++){
// beans.add(create(i));
// }
// return beans;
// }
//
// public static TestBean create(int index){
// TestBean bean = new TestBean();
// bean.username = "Test00"+index;
// bean.password = "password-"+index;
// bean.age = getAge();
// bean.signature = "码农很拽的,你别不信...";
// bean.icoImageUrl = "http://tb1.bdstatic.com/tb/cms/ngmis/adsense/file_1445137409672.jpg";
// return bean;
// }
//
// private static int getAge(){
// Random random = new Random();
// return random.nextInt(150);
// }
// }
|
import android.os.Bundle;
import android.widget.ListView;
import butterknife.Bind;
import com.it114.android.oneframework.core.ui.activity.BaseActivity;
import com.it114.android.oneframework.sample1.R;
import com.it114.android.oneframework.sample1.bean.TestBean;
|
package com.it114.android.oneframework.sample1.demo.adapter;
/**
* Created by andy on 10/18/2015.
*/
public class AdapterActivity extends BaseActivity {
@Bind(R.id.listview)
ListView listView;
private MyAdapter myAdapter ;
@Override
protected void init(Bundle savedInstanceState) {
|
// Path: src/com/it114/android/oneframework/core/ui/activity/BaseActivity.java
// public abstract class BaseActivity extends Activity{
// protected final static String TAG = BaseFragmentActivity.class.getName();
// public ActivityCommon activityState = new ActivityCommonImpl();
// protected ViewFinder mViewFinder;
// protected View titleBar;
// protected TitleBarViewImpl titleBarView;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(getLayoutId());
// ButterKnife.bind(this);
// activityState.create(savedInstanceState);
// init(savedInstanceState);
// }
//
// public void initTitleBar(int titleBarLayoutId,TitleBarListener listener){
// if(titleBarLayoutId>0){
// if(this.titleBar == null)
// this.titleBar = findViewByIdWithFinder(titleBarLayoutId);
// this.titleBarView = new TitleBarViewImpl(this,titleBar);
// if(listener!=null){
// this.titleBarView.setTitleBarListener(listener);
// }
// } else {
// LogUtil.w(TAG, "invalid titleBarLayoutId");
// }
// }
//
//
// @Override
// public void setContentView(int layoutResID) {
// super.setContentView(layoutResID);
// mViewFinder = new ViewFinder(getWindow().getDecorView());
// }
//
// @Override
// public void setContentView(View view) {
// super.setContentView(view);
// mViewFinder = new ViewFinder(view);
// }
//
// @Override
// public void setContentView(View view, ViewGroup.LayoutParams params) {
// super.setContentView(view, params);
// mViewFinder = new ViewFinder(view);
// }
//
// public <T extends View> T findViewByIdWithFinder(int id) {
// return mViewFinder.findViewById(id);
// }
//
// protected abstract void init(Bundle savedInstanceState);
//
// protected abstract int getLayoutId();
//
// @Override
// public void onStart() {
// super.onStart();
// activityState.start();
//
// }
//
// @Override
// public void onStop() {
// super.onStop();
// activityState.stop();
//
// }
//
// @Override
// protected void onRestart() {
// super.onRestart();
// activityState.restart();
//
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// activityState.resume();
//
// }
//
// @Override
// protected void onPause() {
// super.onPause();
// activityState.pause();
//
// }
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// activityState.destroy();
// }
//
//
//
//
// }
//
// Path: Sample1/src/com/it114/android/oneframework/sample1/bean/TestBean.java
// public class TestBean {
//
// public String username;
// public String password;
// public int age;
// public String signature;//签名
// public String icoImageUrl;//头像
//
// public static ArrayList<TestBean> createDataList(int size){
// ArrayList<TestBean> beans = new ArrayList<>();
// for(int i=0;i<size;i++){
// beans.add(create(i));
// }
// return beans;
// }
//
// public static TestBean create(int index){
// TestBean bean = new TestBean();
// bean.username = "Test00"+index;
// bean.password = "password-"+index;
// bean.age = getAge();
// bean.signature = "码农很拽的,你别不信...";
// bean.icoImageUrl = "http://tb1.bdstatic.com/tb/cms/ngmis/adsense/file_1445137409672.jpg";
// return bean;
// }
//
// private static int getAge(){
// Random random = new Random();
// return random.nextInt(150);
// }
// }
// Path: Sample1/src/com/it114/android/oneframework/sample1/demo/adapter/AdapterActivity.java
import android.os.Bundle;
import android.widget.ListView;
import butterknife.Bind;
import com.it114.android.oneframework.core.ui.activity.BaseActivity;
import com.it114.android.oneframework.sample1.R;
import com.it114.android.oneframework.sample1.bean.TestBean;
package com.it114.android.oneframework.sample1.demo.adapter;
/**
* Created by andy on 10/18/2015.
*/
public class AdapterActivity extends BaseActivity {
@Bind(R.id.listview)
ListView listView;
private MyAdapter myAdapter ;
@Override
protected void init(Bundle savedInstanceState) {
|
myAdapter = new MyAdapter(listView, TestBean.createDataList(20),R.layout.adapter_item_layout);
|
it114/OneFramework
|
src/com/it114/android/oneframework/core/ui/fragment/SupportFragment.java
|
// Path: src/com/it114/android/oneframework/core/ui/presenter/BaseFragmentPresenter.java
// public abstract class BaseFragmentPresenter extends Presenter{
//
// protected Context mContext;
// public void attach(Context context) {
// mContext = context;
// init();
// }
//
// public void detach() {
// mContext = null;
// destroy();
// }
//
// protected ActivityCommon.ACTIVITY_STATE getActivityState() {
// if (mContext instanceof BaseActivity) {
// BaseActivity activity = (BaseActivity) mContext;
// return activity.activityState.getActivityState();
// } else if(mContext instanceof BaseFragmentActivity ) {
// BaseFragmentActivity activity = (BaseFragmentActivity) mContext;
// return activity.activityState.getActivityState();
// }
// return ActivityCommon.ACTIVITY_STATE.NOT_ACTIVITY;
// }
//
//
// }
|
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import butterknife.ButterKnife;
import com.it114.android.oneframework.core.ui.presenter.BaseFragmentPresenter;
|
package com.it114.android.oneframework.core.ui.fragment;
/**
* Created by andy on 10/15/2015.
*/
public abstract class SupportFragment extends Fragment {
protected LayoutInflater mLayoutInflater;
protected View mRootView;
|
// Path: src/com/it114/android/oneframework/core/ui/presenter/BaseFragmentPresenter.java
// public abstract class BaseFragmentPresenter extends Presenter{
//
// protected Context mContext;
// public void attach(Context context) {
// mContext = context;
// init();
// }
//
// public void detach() {
// mContext = null;
// destroy();
// }
//
// protected ActivityCommon.ACTIVITY_STATE getActivityState() {
// if (mContext instanceof BaseActivity) {
// BaseActivity activity = (BaseActivity) mContext;
// return activity.activityState.getActivityState();
// } else if(mContext instanceof BaseFragmentActivity ) {
// BaseFragmentActivity activity = (BaseFragmentActivity) mContext;
// return activity.activityState.getActivityState();
// }
// return ActivityCommon.ACTIVITY_STATE.NOT_ACTIVITY;
// }
//
//
// }
// Path: src/com/it114/android/oneframework/core/ui/fragment/SupportFragment.java
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import butterknife.ButterKnife;
import com.it114.android.oneframework.core.ui.presenter.BaseFragmentPresenter;
package com.it114.android.oneframework.core.ui.fragment;
/**
* Created by andy on 10/15/2015.
*/
public abstract class SupportFragment extends Fragment {
protected LayoutInflater mLayoutInflater;
protected View mRootView;
|
protected BaseFragmentPresenter mPresenter;
|
it114/OneFramework
|
src/com/it114/android/oneframework/core/OneApplication.java
|
// Path: src/com/it114/android/oneframework/core/data/Config.java
// public class Config {
// public static final String VERSION = "1.0.0";// framework version
// public static boolean debug = true;
// public static String API_HOST_DEBUG = "";
// public static String API_HOST_RELEASE = "";
//
//
// }
//
// Path: src/com/it114/android/oneframework/core/data/Constants.java
// public class Constants {
//
// public final static String IMAGE_CACHE_DIR = "_images";
// }
//
// Path: src/com/it114/android/oneframework/core/util/FileUtil.java
// public class FileUtil {
//
// /**
// * 得到app缓存文件夹,优先使用外部存储设备
// * @return
// */
// public static File getCacheDir(){
// File cacheDir = OneApplication.getInstance().getCacheDir();
// if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
// cacheDir = OneApplication.getInstance().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
// }
// return cacheDir;
// }
// }
|
import android.app.Application;
import android.graphics.Bitmap;
import android.os.Environment;
import com.it114.android.oneframework.core.BuildConfig;
import com.it114.android.oneframework.core.data.Config;
import com.it114.android.oneframework.core.data.Constants;
import com.it114.android.oneframework.core.util.FileUtil;
import com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import java.io.File;
import java.io.IOException;
|
package com.it114.android.oneframework.core;
/**
* Created by andy on 10/9/2015.
*/
public class OneApplication extends Application {
static OneApplication INSTANCE;
@Override
public void onCreate() {
super.onCreate();
|
// Path: src/com/it114/android/oneframework/core/data/Config.java
// public class Config {
// public static final String VERSION = "1.0.0";// framework version
// public static boolean debug = true;
// public static String API_HOST_DEBUG = "";
// public static String API_HOST_RELEASE = "";
//
//
// }
//
// Path: src/com/it114/android/oneframework/core/data/Constants.java
// public class Constants {
//
// public final static String IMAGE_CACHE_DIR = "_images";
// }
//
// Path: src/com/it114/android/oneframework/core/util/FileUtil.java
// public class FileUtil {
//
// /**
// * 得到app缓存文件夹,优先使用外部存储设备
// * @return
// */
// public static File getCacheDir(){
// File cacheDir = OneApplication.getInstance().getCacheDir();
// if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
// cacheDir = OneApplication.getInstance().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
// }
// return cacheDir;
// }
// }
// Path: src/com/it114/android/oneframework/core/OneApplication.java
import android.app.Application;
import android.graphics.Bitmap;
import android.os.Environment;
import com.it114.android.oneframework.core.BuildConfig;
import com.it114.android.oneframework.core.data.Config;
import com.it114.android.oneframework.core.data.Constants;
import com.it114.android.oneframework.core.util.FileUtil;
import com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import java.io.File;
import java.io.IOException;
package com.it114.android.oneframework.core;
/**
* Created by andy on 10/9/2015.
*/
public class OneApplication extends Application {
static OneApplication INSTANCE;
@Override
public void onCreate() {
super.onCreate();
|
Config.debug = true;
|
it114/OneFramework
|
src/com/it114/android/oneframework/core/OneApplication.java
|
// Path: src/com/it114/android/oneframework/core/data/Config.java
// public class Config {
// public static final String VERSION = "1.0.0";// framework version
// public static boolean debug = true;
// public static String API_HOST_DEBUG = "";
// public static String API_HOST_RELEASE = "";
//
//
// }
//
// Path: src/com/it114/android/oneframework/core/data/Constants.java
// public class Constants {
//
// public final static String IMAGE_CACHE_DIR = "_images";
// }
//
// Path: src/com/it114/android/oneframework/core/util/FileUtil.java
// public class FileUtil {
//
// /**
// * 得到app缓存文件夹,优先使用外部存储设备
// * @return
// */
// public static File getCacheDir(){
// File cacheDir = OneApplication.getInstance().getCacheDir();
// if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
// cacheDir = OneApplication.getInstance().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
// }
// return cacheDir;
// }
// }
|
import android.app.Application;
import android.graphics.Bitmap;
import android.os.Environment;
import com.it114.android.oneframework.core.BuildConfig;
import com.it114.android.oneframework.core.data.Config;
import com.it114.android.oneframework.core.data.Constants;
import com.it114.android.oneframework.core.util.FileUtil;
import com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import java.io.File;
import java.io.IOException;
|
initImageLoader();
}
public static OneApplication getInstance(){
return INSTANCE;
}
@Override
public void onTerminate() {
super.onTerminate();
}
@Override
public void onLowMemory() {
super.onLowMemory();
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
}
private void initImageLoader() {
DisplayImageOptions options = new DisplayImageOptions.Builder()
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.EXACTLY)
.cacheOnDisc(true)
.displayer(new FadeInBitmapDisplayer(200))
.build();
|
// Path: src/com/it114/android/oneframework/core/data/Config.java
// public class Config {
// public static final String VERSION = "1.0.0";// framework version
// public static boolean debug = true;
// public static String API_HOST_DEBUG = "";
// public static String API_HOST_RELEASE = "";
//
//
// }
//
// Path: src/com/it114/android/oneframework/core/data/Constants.java
// public class Constants {
//
// public final static String IMAGE_CACHE_DIR = "_images";
// }
//
// Path: src/com/it114/android/oneframework/core/util/FileUtil.java
// public class FileUtil {
//
// /**
// * 得到app缓存文件夹,优先使用外部存储设备
// * @return
// */
// public static File getCacheDir(){
// File cacheDir = OneApplication.getInstance().getCacheDir();
// if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
// cacheDir = OneApplication.getInstance().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
// }
// return cacheDir;
// }
// }
// Path: src/com/it114/android/oneframework/core/OneApplication.java
import android.app.Application;
import android.graphics.Bitmap;
import android.os.Environment;
import com.it114.android.oneframework.core.BuildConfig;
import com.it114.android.oneframework.core.data.Config;
import com.it114.android.oneframework.core.data.Constants;
import com.it114.android.oneframework.core.util.FileUtil;
import com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import java.io.File;
import java.io.IOException;
initImageLoader();
}
public static OneApplication getInstance(){
return INSTANCE;
}
@Override
public void onTerminate() {
super.onTerminate();
}
@Override
public void onLowMemory() {
super.onLowMemory();
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
}
private void initImageLoader() {
DisplayImageOptions options = new DisplayImageOptions.Builder()
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.EXACTLY)
.cacheOnDisc(true)
.displayer(new FadeInBitmapDisplayer(200))
.build();
|
File cacheDir = new File(FileUtil.getCacheDir().getAbsolutePath() + "/" + Constants.IMAGE_CACHE_DIR);
|
it114/OneFramework
|
src/com/it114/android/oneframework/core/OneApplication.java
|
// Path: src/com/it114/android/oneframework/core/data/Config.java
// public class Config {
// public static final String VERSION = "1.0.0";// framework version
// public static boolean debug = true;
// public static String API_HOST_DEBUG = "";
// public static String API_HOST_RELEASE = "";
//
//
// }
//
// Path: src/com/it114/android/oneframework/core/data/Constants.java
// public class Constants {
//
// public final static String IMAGE_CACHE_DIR = "_images";
// }
//
// Path: src/com/it114/android/oneframework/core/util/FileUtil.java
// public class FileUtil {
//
// /**
// * 得到app缓存文件夹,优先使用外部存储设备
// * @return
// */
// public static File getCacheDir(){
// File cacheDir = OneApplication.getInstance().getCacheDir();
// if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
// cacheDir = OneApplication.getInstance().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
// }
// return cacheDir;
// }
// }
|
import android.app.Application;
import android.graphics.Bitmap;
import android.os.Environment;
import com.it114.android.oneframework.core.BuildConfig;
import com.it114.android.oneframework.core.data.Config;
import com.it114.android.oneframework.core.data.Constants;
import com.it114.android.oneframework.core.util.FileUtil;
import com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import java.io.File;
import java.io.IOException;
|
initImageLoader();
}
public static OneApplication getInstance(){
return INSTANCE;
}
@Override
public void onTerminate() {
super.onTerminate();
}
@Override
public void onLowMemory() {
super.onLowMemory();
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
}
private void initImageLoader() {
DisplayImageOptions options = new DisplayImageOptions.Builder()
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.EXACTLY)
.cacheOnDisc(true)
.displayer(new FadeInBitmapDisplayer(200))
.build();
|
// Path: src/com/it114/android/oneframework/core/data/Config.java
// public class Config {
// public static final String VERSION = "1.0.0";// framework version
// public static boolean debug = true;
// public static String API_HOST_DEBUG = "";
// public static String API_HOST_RELEASE = "";
//
//
// }
//
// Path: src/com/it114/android/oneframework/core/data/Constants.java
// public class Constants {
//
// public final static String IMAGE_CACHE_DIR = "_images";
// }
//
// Path: src/com/it114/android/oneframework/core/util/FileUtil.java
// public class FileUtil {
//
// /**
// * 得到app缓存文件夹,优先使用外部存储设备
// * @return
// */
// public static File getCacheDir(){
// File cacheDir = OneApplication.getInstance().getCacheDir();
// if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
// cacheDir = OneApplication.getInstance().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
// }
// return cacheDir;
// }
// }
// Path: src/com/it114/android/oneframework/core/OneApplication.java
import android.app.Application;
import android.graphics.Bitmap;
import android.os.Environment;
import com.it114.android.oneframework.core.BuildConfig;
import com.it114.android.oneframework.core.data.Config;
import com.it114.android.oneframework.core.data.Constants;
import com.it114.android.oneframework.core.util.FileUtil;
import com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import java.io.File;
import java.io.IOException;
initImageLoader();
}
public static OneApplication getInstance(){
return INSTANCE;
}
@Override
public void onTerminate() {
super.onTerminate();
}
@Override
public void onLowMemory() {
super.onLowMemory();
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
}
private void initImageLoader() {
DisplayImageOptions options = new DisplayImageOptions.Builder()
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.EXACTLY)
.cacheOnDisc(true)
.displayer(new FadeInBitmapDisplayer(200))
.build();
|
File cacheDir = new File(FileUtil.getCacheDir().getAbsolutePath() + "/" + Constants.IMAGE_CACHE_DIR);
|
waynell/VideoListPlayer
|
app/src/main/java/com/waynell/videolist/demo/util/ItemUtils.java
|
// Path: app/src/main/java/com/waynell/videolist/demo/model/BaseItem.java
// public abstract class BaseItem {
//
// public static final int VIEW_TYPE_TEXT = 0;
// public static final int VIEW_TYPE_PICTURE = 1;
// public static final int VIEW_TYPE_VIDEO = 2;
//
// private final int mViewType;
//
// public BaseItem(int viewType) {
// mViewType = viewType;
// }
//
// public int getViewType() {
// return mViewType;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/PicItem.java
// public class PicItem extends BaseItem {
//
// private String mCoverUrl;
//
// public PicItem(String coverUrl) {
// super(BaseItem.VIEW_TYPE_PICTURE);
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/TextItem.java
// public class TextItem extends BaseItem {
//
// private String mText;
//
// public TextItem(String text) {
// super(BaseItem.VIEW_TYPE_TEXT);
// mText = text;
// }
//
// public String getText() {
// return mText;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/VideoItem.java
// public class VideoItem extends BaseItem {
// private String mVideoUrl;
// private String mCoverUrl;
//
// public VideoItem(String videoUrl, String coverUrl) {
// super(BaseItem.VIEW_TYPE_VIDEO);
// mVideoUrl = videoUrl;
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
//
// public String getVideoUrl() {
// return mVideoUrl;
// }
// }
|
import com.waynell.videolist.demo.model.BaseItem;
import com.waynell.videolist.demo.model.PicItem;
import com.waynell.videolist.demo.model.TextItem;
import com.waynell.videolist.demo.model.VideoItem;
import java.util.ArrayList;
import java.util.List;
|
package com.waynell.videolist.demo.util;
/**
* @author Wayne
*/
public class ItemUtils {
private static final String VIDEO_URL1 = "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4";
private static final String VIDEO_URL2 = "http://techslides.com/demos/sample-videos/small.mp4";
private static final String VIDEO_URL3 = "http://download.wavetlan.com/SVV/Media/HTTP/H264/Other_Media/H264_test7_voiceclip_mp4_480x360.mp4";
private static final String VIDEO_URL4 = "http://download.wavetlan.com/SVV/Media/HTTP/MP4/ConvertedFiles/Media-Convert/Unsupported/test7.mp4";
private static final String PIC_URL1 = "http://img10.3lian.com/sc6/show02/67/27/03.jpg";
private static final String PIC_URL2 = "http://img10.3lian.com/sc6/show02/67/27/04.jpg";
private static final String PIC_URL3 = "http://img10.3lian.com/sc6/show02/67/27/01.jpg";
private static final String PIC_URL4 = "http://img10.3lian.com/sc6/show02/67/27/02.jpg";
|
// Path: app/src/main/java/com/waynell/videolist/demo/model/BaseItem.java
// public abstract class BaseItem {
//
// public static final int VIEW_TYPE_TEXT = 0;
// public static final int VIEW_TYPE_PICTURE = 1;
// public static final int VIEW_TYPE_VIDEO = 2;
//
// private final int mViewType;
//
// public BaseItem(int viewType) {
// mViewType = viewType;
// }
//
// public int getViewType() {
// return mViewType;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/PicItem.java
// public class PicItem extends BaseItem {
//
// private String mCoverUrl;
//
// public PicItem(String coverUrl) {
// super(BaseItem.VIEW_TYPE_PICTURE);
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/TextItem.java
// public class TextItem extends BaseItem {
//
// private String mText;
//
// public TextItem(String text) {
// super(BaseItem.VIEW_TYPE_TEXT);
// mText = text;
// }
//
// public String getText() {
// return mText;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/VideoItem.java
// public class VideoItem extends BaseItem {
// private String mVideoUrl;
// private String mCoverUrl;
//
// public VideoItem(String videoUrl, String coverUrl) {
// super(BaseItem.VIEW_TYPE_VIDEO);
// mVideoUrl = videoUrl;
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
//
// public String getVideoUrl() {
// return mVideoUrl;
// }
// }
// Path: app/src/main/java/com/waynell/videolist/demo/util/ItemUtils.java
import com.waynell.videolist.demo.model.BaseItem;
import com.waynell.videolist.demo.model.PicItem;
import com.waynell.videolist.demo.model.TextItem;
import com.waynell.videolist.demo.model.VideoItem;
import java.util.ArrayList;
import java.util.List;
package com.waynell.videolist.demo.util;
/**
* @author Wayne
*/
public class ItemUtils {
private static final String VIDEO_URL1 = "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4";
private static final String VIDEO_URL2 = "http://techslides.com/demos/sample-videos/small.mp4";
private static final String VIDEO_URL3 = "http://download.wavetlan.com/SVV/Media/HTTP/H264/Other_Media/H264_test7_voiceclip_mp4_480x360.mp4";
private static final String VIDEO_URL4 = "http://download.wavetlan.com/SVV/Media/HTTP/MP4/ConvertedFiles/Media-Convert/Unsupported/test7.mp4";
private static final String PIC_URL1 = "http://img10.3lian.com/sc6/show02/67/27/03.jpg";
private static final String PIC_URL2 = "http://img10.3lian.com/sc6/show02/67/27/04.jpg";
private static final String PIC_URL3 = "http://img10.3lian.com/sc6/show02/67/27/01.jpg";
private static final String PIC_URL4 = "http://img10.3lian.com/sc6/show02/67/27/02.jpg";
|
public static List<BaseItem> generateMockData() {
|
waynell/VideoListPlayer
|
app/src/main/java/com/waynell/videolist/demo/util/ItemUtils.java
|
// Path: app/src/main/java/com/waynell/videolist/demo/model/BaseItem.java
// public abstract class BaseItem {
//
// public static final int VIEW_TYPE_TEXT = 0;
// public static final int VIEW_TYPE_PICTURE = 1;
// public static final int VIEW_TYPE_VIDEO = 2;
//
// private final int mViewType;
//
// public BaseItem(int viewType) {
// mViewType = viewType;
// }
//
// public int getViewType() {
// return mViewType;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/PicItem.java
// public class PicItem extends BaseItem {
//
// private String mCoverUrl;
//
// public PicItem(String coverUrl) {
// super(BaseItem.VIEW_TYPE_PICTURE);
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/TextItem.java
// public class TextItem extends BaseItem {
//
// private String mText;
//
// public TextItem(String text) {
// super(BaseItem.VIEW_TYPE_TEXT);
// mText = text;
// }
//
// public String getText() {
// return mText;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/VideoItem.java
// public class VideoItem extends BaseItem {
// private String mVideoUrl;
// private String mCoverUrl;
//
// public VideoItem(String videoUrl, String coverUrl) {
// super(BaseItem.VIEW_TYPE_VIDEO);
// mVideoUrl = videoUrl;
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
//
// public String getVideoUrl() {
// return mVideoUrl;
// }
// }
|
import com.waynell.videolist.demo.model.BaseItem;
import com.waynell.videolist.demo.model.PicItem;
import com.waynell.videolist.demo.model.TextItem;
import com.waynell.videolist.demo.model.VideoItem;
import java.util.ArrayList;
import java.util.List;
|
package com.waynell.videolist.demo.util;
/**
* @author Wayne
*/
public class ItemUtils {
private static final String VIDEO_URL1 = "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4";
private static final String VIDEO_URL2 = "http://techslides.com/demos/sample-videos/small.mp4";
private static final String VIDEO_URL3 = "http://download.wavetlan.com/SVV/Media/HTTP/H264/Other_Media/H264_test7_voiceclip_mp4_480x360.mp4";
private static final String VIDEO_URL4 = "http://download.wavetlan.com/SVV/Media/HTTP/MP4/ConvertedFiles/Media-Convert/Unsupported/test7.mp4";
private static final String PIC_URL1 = "http://img10.3lian.com/sc6/show02/67/27/03.jpg";
private static final String PIC_URL2 = "http://img10.3lian.com/sc6/show02/67/27/04.jpg";
private static final String PIC_URL3 = "http://img10.3lian.com/sc6/show02/67/27/01.jpg";
private static final String PIC_URL4 = "http://img10.3lian.com/sc6/show02/67/27/02.jpg";
public static List<BaseItem> generateMockData() {
List<BaseItem> list = new ArrayList<>();
|
// Path: app/src/main/java/com/waynell/videolist/demo/model/BaseItem.java
// public abstract class BaseItem {
//
// public static final int VIEW_TYPE_TEXT = 0;
// public static final int VIEW_TYPE_PICTURE = 1;
// public static final int VIEW_TYPE_VIDEO = 2;
//
// private final int mViewType;
//
// public BaseItem(int viewType) {
// mViewType = viewType;
// }
//
// public int getViewType() {
// return mViewType;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/PicItem.java
// public class PicItem extends BaseItem {
//
// private String mCoverUrl;
//
// public PicItem(String coverUrl) {
// super(BaseItem.VIEW_TYPE_PICTURE);
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/TextItem.java
// public class TextItem extends BaseItem {
//
// private String mText;
//
// public TextItem(String text) {
// super(BaseItem.VIEW_TYPE_TEXT);
// mText = text;
// }
//
// public String getText() {
// return mText;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/VideoItem.java
// public class VideoItem extends BaseItem {
// private String mVideoUrl;
// private String mCoverUrl;
//
// public VideoItem(String videoUrl, String coverUrl) {
// super(BaseItem.VIEW_TYPE_VIDEO);
// mVideoUrl = videoUrl;
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
//
// public String getVideoUrl() {
// return mVideoUrl;
// }
// }
// Path: app/src/main/java/com/waynell/videolist/demo/util/ItemUtils.java
import com.waynell.videolist.demo.model.BaseItem;
import com.waynell.videolist.demo.model.PicItem;
import com.waynell.videolist.demo.model.TextItem;
import com.waynell.videolist.demo.model.VideoItem;
import java.util.ArrayList;
import java.util.List;
package com.waynell.videolist.demo.util;
/**
* @author Wayne
*/
public class ItemUtils {
private static final String VIDEO_URL1 = "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4";
private static final String VIDEO_URL2 = "http://techslides.com/demos/sample-videos/small.mp4";
private static final String VIDEO_URL3 = "http://download.wavetlan.com/SVV/Media/HTTP/H264/Other_Media/H264_test7_voiceclip_mp4_480x360.mp4";
private static final String VIDEO_URL4 = "http://download.wavetlan.com/SVV/Media/HTTP/MP4/ConvertedFiles/Media-Convert/Unsupported/test7.mp4";
private static final String PIC_URL1 = "http://img10.3lian.com/sc6/show02/67/27/03.jpg";
private static final String PIC_URL2 = "http://img10.3lian.com/sc6/show02/67/27/04.jpg";
private static final String PIC_URL3 = "http://img10.3lian.com/sc6/show02/67/27/01.jpg";
private static final String PIC_URL4 = "http://img10.3lian.com/sc6/show02/67/27/02.jpg";
public static List<BaseItem> generateMockData() {
List<BaseItem> list = new ArrayList<>();
|
list.add(new TextItem("TextItem"));
|
waynell/VideoListPlayer
|
app/src/main/java/com/waynell/videolist/demo/util/ItemUtils.java
|
// Path: app/src/main/java/com/waynell/videolist/demo/model/BaseItem.java
// public abstract class BaseItem {
//
// public static final int VIEW_TYPE_TEXT = 0;
// public static final int VIEW_TYPE_PICTURE = 1;
// public static final int VIEW_TYPE_VIDEO = 2;
//
// private final int mViewType;
//
// public BaseItem(int viewType) {
// mViewType = viewType;
// }
//
// public int getViewType() {
// return mViewType;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/PicItem.java
// public class PicItem extends BaseItem {
//
// private String mCoverUrl;
//
// public PicItem(String coverUrl) {
// super(BaseItem.VIEW_TYPE_PICTURE);
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/TextItem.java
// public class TextItem extends BaseItem {
//
// private String mText;
//
// public TextItem(String text) {
// super(BaseItem.VIEW_TYPE_TEXT);
// mText = text;
// }
//
// public String getText() {
// return mText;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/VideoItem.java
// public class VideoItem extends BaseItem {
// private String mVideoUrl;
// private String mCoverUrl;
//
// public VideoItem(String videoUrl, String coverUrl) {
// super(BaseItem.VIEW_TYPE_VIDEO);
// mVideoUrl = videoUrl;
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
//
// public String getVideoUrl() {
// return mVideoUrl;
// }
// }
|
import com.waynell.videolist.demo.model.BaseItem;
import com.waynell.videolist.demo.model.PicItem;
import com.waynell.videolist.demo.model.TextItem;
import com.waynell.videolist.demo.model.VideoItem;
import java.util.ArrayList;
import java.util.List;
|
package com.waynell.videolist.demo.util;
/**
* @author Wayne
*/
public class ItemUtils {
private static final String VIDEO_URL1 = "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4";
private static final String VIDEO_URL2 = "http://techslides.com/demos/sample-videos/small.mp4";
private static final String VIDEO_URL3 = "http://download.wavetlan.com/SVV/Media/HTTP/H264/Other_Media/H264_test7_voiceclip_mp4_480x360.mp4";
private static final String VIDEO_URL4 = "http://download.wavetlan.com/SVV/Media/HTTP/MP4/ConvertedFiles/Media-Convert/Unsupported/test7.mp4";
private static final String PIC_URL1 = "http://img10.3lian.com/sc6/show02/67/27/03.jpg";
private static final String PIC_URL2 = "http://img10.3lian.com/sc6/show02/67/27/04.jpg";
private static final String PIC_URL3 = "http://img10.3lian.com/sc6/show02/67/27/01.jpg";
private static final String PIC_URL4 = "http://img10.3lian.com/sc6/show02/67/27/02.jpg";
public static List<BaseItem> generateMockData() {
List<BaseItem> list = new ArrayList<>();
list.add(new TextItem("TextItem"));
|
// Path: app/src/main/java/com/waynell/videolist/demo/model/BaseItem.java
// public abstract class BaseItem {
//
// public static final int VIEW_TYPE_TEXT = 0;
// public static final int VIEW_TYPE_PICTURE = 1;
// public static final int VIEW_TYPE_VIDEO = 2;
//
// private final int mViewType;
//
// public BaseItem(int viewType) {
// mViewType = viewType;
// }
//
// public int getViewType() {
// return mViewType;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/PicItem.java
// public class PicItem extends BaseItem {
//
// private String mCoverUrl;
//
// public PicItem(String coverUrl) {
// super(BaseItem.VIEW_TYPE_PICTURE);
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/TextItem.java
// public class TextItem extends BaseItem {
//
// private String mText;
//
// public TextItem(String text) {
// super(BaseItem.VIEW_TYPE_TEXT);
// mText = text;
// }
//
// public String getText() {
// return mText;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/VideoItem.java
// public class VideoItem extends BaseItem {
// private String mVideoUrl;
// private String mCoverUrl;
//
// public VideoItem(String videoUrl, String coverUrl) {
// super(BaseItem.VIEW_TYPE_VIDEO);
// mVideoUrl = videoUrl;
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
//
// public String getVideoUrl() {
// return mVideoUrl;
// }
// }
// Path: app/src/main/java/com/waynell/videolist/demo/util/ItemUtils.java
import com.waynell.videolist.demo.model.BaseItem;
import com.waynell.videolist.demo.model.PicItem;
import com.waynell.videolist.demo.model.TextItem;
import com.waynell.videolist.demo.model.VideoItem;
import java.util.ArrayList;
import java.util.List;
package com.waynell.videolist.demo.util;
/**
* @author Wayne
*/
public class ItemUtils {
private static final String VIDEO_URL1 = "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4";
private static final String VIDEO_URL2 = "http://techslides.com/demos/sample-videos/small.mp4";
private static final String VIDEO_URL3 = "http://download.wavetlan.com/SVV/Media/HTTP/H264/Other_Media/H264_test7_voiceclip_mp4_480x360.mp4";
private static final String VIDEO_URL4 = "http://download.wavetlan.com/SVV/Media/HTTP/MP4/ConvertedFiles/Media-Convert/Unsupported/test7.mp4";
private static final String PIC_URL1 = "http://img10.3lian.com/sc6/show02/67/27/03.jpg";
private static final String PIC_URL2 = "http://img10.3lian.com/sc6/show02/67/27/04.jpg";
private static final String PIC_URL3 = "http://img10.3lian.com/sc6/show02/67/27/01.jpg";
private static final String PIC_URL4 = "http://img10.3lian.com/sc6/show02/67/27/02.jpg";
public static List<BaseItem> generateMockData() {
List<BaseItem> list = new ArrayList<>();
list.add(new TextItem("TextItem"));
|
list.add(new PicItem(PIC_URL1));
|
waynell/VideoListPlayer
|
app/src/main/java/com/waynell/videolist/demo/util/ItemUtils.java
|
// Path: app/src/main/java/com/waynell/videolist/demo/model/BaseItem.java
// public abstract class BaseItem {
//
// public static final int VIEW_TYPE_TEXT = 0;
// public static final int VIEW_TYPE_PICTURE = 1;
// public static final int VIEW_TYPE_VIDEO = 2;
//
// private final int mViewType;
//
// public BaseItem(int viewType) {
// mViewType = viewType;
// }
//
// public int getViewType() {
// return mViewType;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/PicItem.java
// public class PicItem extends BaseItem {
//
// private String mCoverUrl;
//
// public PicItem(String coverUrl) {
// super(BaseItem.VIEW_TYPE_PICTURE);
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/TextItem.java
// public class TextItem extends BaseItem {
//
// private String mText;
//
// public TextItem(String text) {
// super(BaseItem.VIEW_TYPE_TEXT);
// mText = text;
// }
//
// public String getText() {
// return mText;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/VideoItem.java
// public class VideoItem extends BaseItem {
// private String mVideoUrl;
// private String mCoverUrl;
//
// public VideoItem(String videoUrl, String coverUrl) {
// super(BaseItem.VIEW_TYPE_VIDEO);
// mVideoUrl = videoUrl;
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
//
// public String getVideoUrl() {
// return mVideoUrl;
// }
// }
|
import com.waynell.videolist.demo.model.BaseItem;
import com.waynell.videolist.demo.model.PicItem;
import com.waynell.videolist.demo.model.TextItem;
import com.waynell.videolist.demo.model.VideoItem;
import java.util.ArrayList;
import java.util.List;
|
package com.waynell.videolist.demo.util;
/**
* @author Wayne
*/
public class ItemUtils {
private static final String VIDEO_URL1 = "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4";
private static final String VIDEO_URL2 = "http://techslides.com/demos/sample-videos/small.mp4";
private static final String VIDEO_URL3 = "http://download.wavetlan.com/SVV/Media/HTTP/H264/Other_Media/H264_test7_voiceclip_mp4_480x360.mp4";
private static final String VIDEO_URL4 = "http://download.wavetlan.com/SVV/Media/HTTP/MP4/ConvertedFiles/Media-Convert/Unsupported/test7.mp4";
private static final String PIC_URL1 = "http://img10.3lian.com/sc6/show02/67/27/03.jpg";
private static final String PIC_URL2 = "http://img10.3lian.com/sc6/show02/67/27/04.jpg";
private static final String PIC_URL3 = "http://img10.3lian.com/sc6/show02/67/27/01.jpg";
private static final String PIC_URL4 = "http://img10.3lian.com/sc6/show02/67/27/02.jpg";
public static List<BaseItem> generateMockData() {
List<BaseItem> list = new ArrayList<>();
list.add(new TextItem("TextItem"));
list.add(new PicItem(PIC_URL1));
|
// Path: app/src/main/java/com/waynell/videolist/demo/model/BaseItem.java
// public abstract class BaseItem {
//
// public static final int VIEW_TYPE_TEXT = 0;
// public static final int VIEW_TYPE_PICTURE = 1;
// public static final int VIEW_TYPE_VIDEO = 2;
//
// private final int mViewType;
//
// public BaseItem(int viewType) {
// mViewType = viewType;
// }
//
// public int getViewType() {
// return mViewType;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/PicItem.java
// public class PicItem extends BaseItem {
//
// private String mCoverUrl;
//
// public PicItem(String coverUrl) {
// super(BaseItem.VIEW_TYPE_PICTURE);
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/TextItem.java
// public class TextItem extends BaseItem {
//
// private String mText;
//
// public TextItem(String text) {
// super(BaseItem.VIEW_TYPE_TEXT);
// mText = text;
// }
//
// public String getText() {
// return mText;
// }
// }
//
// Path: app/src/main/java/com/waynell/videolist/demo/model/VideoItem.java
// public class VideoItem extends BaseItem {
// private String mVideoUrl;
// private String mCoverUrl;
//
// public VideoItem(String videoUrl, String coverUrl) {
// super(BaseItem.VIEW_TYPE_VIDEO);
// mVideoUrl = videoUrl;
// mCoverUrl = coverUrl;
// }
//
// public String getCoverUrl() {
// return mCoverUrl;
// }
//
// public String getVideoUrl() {
// return mVideoUrl;
// }
// }
// Path: app/src/main/java/com/waynell/videolist/demo/util/ItemUtils.java
import com.waynell.videolist.demo.model.BaseItem;
import com.waynell.videolist.demo.model.PicItem;
import com.waynell.videolist.demo.model.TextItem;
import com.waynell.videolist.demo.model.VideoItem;
import java.util.ArrayList;
import java.util.List;
package com.waynell.videolist.demo.util;
/**
* @author Wayne
*/
public class ItemUtils {
private static final String VIDEO_URL1 = "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4";
private static final String VIDEO_URL2 = "http://techslides.com/demos/sample-videos/small.mp4";
private static final String VIDEO_URL3 = "http://download.wavetlan.com/SVV/Media/HTTP/H264/Other_Media/H264_test7_voiceclip_mp4_480x360.mp4";
private static final String VIDEO_URL4 = "http://download.wavetlan.com/SVV/Media/HTTP/MP4/ConvertedFiles/Media-Convert/Unsupported/test7.mp4";
private static final String PIC_URL1 = "http://img10.3lian.com/sc6/show02/67/27/03.jpg";
private static final String PIC_URL2 = "http://img10.3lian.com/sc6/show02/67/27/04.jpg";
private static final String PIC_URL3 = "http://img10.3lian.com/sc6/show02/67/27/01.jpg";
private static final String PIC_URL4 = "http://img10.3lian.com/sc6/show02/67/27/02.jpg";
public static List<BaseItem> generateMockData() {
List<BaseItem> list = new ArrayList<>();
list.add(new TextItem("TextItem"));
list.add(new PicItem(PIC_URL1));
|
list.add(new VideoItem(VIDEO_URL4, PIC_URL4));
|
waynell/VideoListPlayer
|
video-list-player/src/main/java/com/waynell/videolist/visibility/calculator/SingleListViewItemActiveCalculator.java
|
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItem.java
// public interface ListItem {
//
// /**
// * When view visibility become bigger than "current active" view visibility then the new view becomes active.
// * This method is called
// */
// void setActive(View newActiveView, int newActiveViewPosition);
//
// /**
// * There might be a case when not only new view becomes active, but also when no view is active.
// * When view should stop being active this method is called
// */
// void deactivate(View currentView, int position);
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItemData.java
// public class ListItemData {
//
// private Integer mIndexInAdapter;
// private View mView;
// private ListItem mListItem;
//
// private boolean mIsVisibleItemChanged;
//
// public int getIndex() {
// return mIndexInAdapter;
// }
//
// public View getView() {
// return mView;
// }
//
// public ListItem getListItem() {
// return mListItem;
// }
//
// public ListItemData fillWithData(int indexInAdapter, View view, ListItem item) {
// mIndexInAdapter = indexInAdapter;
// mView = view;
// mListItem = item;
// return this;
// }
//
// public boolean isIndexValid() {
// return mIndexInAdapter != null;
// }
//
// public boolean isAvailable() {
// return mIndexInAdapter != null && mView != null && mListItem != null;
// }
//
// public void setVisibleItemChanged(boolean isDataChanged) {
// mIsVisibleItemChanged = isDataChanged;
// }
//
// public boolean isVisibleItemChanged() {
// return mIsVisibleItemChanged;
// }
//
// @Override
// public String toString() {
// return "ListItemData{" +
// "mIndexInAdapter=" + mIndexInAdapter +
// ", mView=" + mView +
// ", mListItem=" + mListItem +
// ", mIsVisibleItemChanged=" + mIsVisibleItemChanged +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ListItemData that = (ListItemData) o;
//
// return (mIndexInAdapter != null ? mIndexInAdapter.equals(that.mIndexInAdapter) : that.mIndexInAdapter == null)
// && (mView != null ? mView.equals(that.mView) : that.mView == null);
//
// }
//
// @Override
// public int hashCode() {
// int result = mIndexInAdapter != null ? mIndexInAdapter.hashCode() : 0;
// result = 31 * result + (mView != null ? mView.hashCode() : 0);
// return result;
// }
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsPositionGetter.java
// public interface ItemsPositionGetter {
// View getChildAt(int position);
//
// int indexOfChild(View view);
//
// int getChildCount();
//
// int getLastVisiblePosition();
//
// int getFirstVisiblePosition();
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsProvider.java
// public interface ItemsProvider {
//
// ListItem getListItem(int position);
//
// int listItemSize();
//
// }
|
import android.util.Log;
import android.view.View;
import com.waynell.videolist.visibility.items.ListItem;
import com.waynell.videolist.visibility.items.ListItemData;
import com.waynell.videolist.visibility.scroll.ItemsPositionGetter;
import com.waynell.videolist.visibility.scroll.ItemsProvider;
|
package com.waynell.videolist.visibility.calculator;
/**
* A utility that tracks current {@link ListItem} visibility.
* Current ListItem is an item defined by calling {@link #setCurrentItem(ListItemData)}.
* Or it might be mock current item created in method {@link #getMockCurrentItem}
*
* The logic is following: when current view is going out of screen (up or down) by {@link #INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS} or more then neighbour item become "active" by calling {@link Callback#activateNewCurrentItem}
* "Going out of screen" is calculated when {@link #onStateTouchScroll} is called from super class {@link BaseItemsVisibilityCalculator}
*
* Method {@link ListItemsVisibilityCalculator#onScrollStateIdle} should be called only when scroll state become idle. // TODO: test it
* When it's called we look for new current item that eventually will be set as "active" by calling {@link #setCurrentItem(ListItemData)}
* Regarding the {@link #mScrollDirection} new current item is calculated from top to bottom (if DOWN) or from bottom to top (if UP).
* The first(or last) visible item is set to current. It's visibility percentage is calculated. Then we are going though all visible items and find the one that is the most visible.
*
* Method {@link #onStateLost} is calling {@link Callback#deactivateCurrentItem}
*
* @author Wayne
*/
public class SingleListViewItemActiveCalculator extends BaseItemsVisibilityCalculator {
private static final String TAG = "ListViewItemActiveCal";
private static final boolean SHOW_LOGS = false;
private static final int INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS = 70;
|
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItem.java
// public interface ListItem {
//
// /**
// * When view visibility become bigger than "current active" view visibility then the new view becomes active.
// * This method is called
// */
// void setActive(View newActiveView, int newActiveViewPosition);
//
// /**
// * There might be a case when not only new view becomes active, but also when no view is active.
// * When view should stop being active this method is called
// */
// void deactivate(View currentView, int position);
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItemData.java
// public class ListItemData {
//
// private Integer mIndexInAdapter;
// private View mView;
// private ListItem mListItem;
//
// private boolean mIsVisibleItemChanged;
//
// public int getIndex() {
// return mIndexInAdapter;
// }
//
// public View getView() {
// return mView;
// }
//
// public ListItem getListItem() {
// return mListItem;
// }
//
// public ListItemData fillWithData(int indexInAdapter, View view, ListItem item) {
// mIndexInAdapter = indexInAdapter;
// mView = view;
// mListItem = item;
// return this;
// }
//
// public boolean isIndexValid() {
// return mIndexInAdapter != null;
// }
//
// public boolean isAvailable() {
// return mIndexInAdapter != null && mView != null && mListItem != null;
// }
//
// public void setVisibleItemChanged(boolean isDataChanged) {
// mIsVisibleItemChanged = isDataChanged;
// }
//
// public boolean isVisibleItemChanged() {
// return mIsVisibleItemChanged;
// }
//
// @Override
// public String toString() {
// return "ListItemData{" +
// "mIndexInAdapter=" + mIndexInAdapter +
// ", mView=" + mView +
// ", mListItem=" + mListItem +
// ", mIsVisibleItemChanged=" + mIsVisibleItemChanged +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ListItemData that = (ListItemData) o;
//
// return (mIndexInAdapter != null ? mIndexInAdapter.equals(that.mIndexInAdapter) : that.mIndexInAdapter == null)
// && (mView != null ? mView.equals(that.mView) : that.mView == null);
//
// }
//
// @Override
// public int hashCode() {
// int result = mIndexInAdapter != null ? mIndexInAdapter.hashCode() : 0;
// result = 31 * result + (mView != null ? mView.hashCode() : 0);
// return result;
// }
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsPositionGetter.java
// public interface ItemsPositionGetter {
// View getChildAt(int position);
//
// int indexOfChild(View view);
//
// int getChildCount();
//
// int getLastVisiblePosition();
//
// int getFirstVisiblePosition();
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsProvider.java
// public interface ItemsProvider {
//
// ListItem getListItem(int position);
//
// int listItemSize();
//
// }
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/calculator/SingleListViewItemActiveCalculator.java
import android.util.Log;
import android.view.View;
import com.waynell.videolist.visibility.items.ListItem;
import com.waynell.videolist.visibility.items.ListItemData;
import com.waynell.videolist.visibility.scroll.ItemsPositionGetter;
import com.waynell.videolist.visibility.scroll.ItemsProvider;
package com.waynell.videolist.visibility.calculator;
/**
* A utility that tracks current {@link ListItem} visibility.
* Current ListItem is an item defined by calling {@link #setCurrentItem(ListItemData)}.
* Or it might be mock current item created in method {@link #getMockCurrentItem}
*
* The logic is following: when current view is going out of screen (up or down) by {@link #INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS} or more then neighbour item become "active" by calling {@link Callback#activateNewCurrentItem}
* "Going out of screen" is calculated when {@link #onStateTouchScroll} is called from super class {@link BaseItemsVisibilityCalculator}
*
* Method {@link ListItemsVisibilityCalculator#onScrollStateIdle} should be called only when scroll state become idle. // TODO: test it
* When it's called we look for new current item that eventually will be set as "active" by calling {@link #setCurrentItem(ListItemData)}
* Regarding the {@link #mScrollDirection} new current item is calculated from top to bottom (if DOWN) or from bottom to top (if UP).
* The first(or last) visible item is set to current. It's visibility percentage is calculated. Then we are going though all visible items and find the one that is the most visible.
*
* Method {@link #onStateLost} is calling {@link Callback#deactivateCurrentItem}
*
* @author Wayne
*/
public class SingleListViewItemActiveCalculator extends BaseItemsVisibilityCalculator {
private static final String TAG = "ListViewItemActiveCal";
private static final boolean SHOW_LOGS = false;
private static final int INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS = 70;
|
private final Callback<ListItem> mCallback;
|
waynell/VideoListPlayer
|
video-list-player/src/main/java/com/waynell/videolist/visibility/calculator/SingleListViewItemActiveCalculator.java
|
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItem.java
// public interface ListItem {
//
// /**
// * When view visibility become bigger than "current active" view visibility then the new view becomes active.
// * This method is called
// */
// void setActive(View newActiveView, int newActiveViewPosition);
//
// /**
// * There might be a case when not only new view becomes active, but also when no view is active.
// * When view should stop being active this method is called
// */
// void deactivate(View currentView, int position);
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItemData.java
// public class ListItemData {
//
// private Integer mIndexInAdapter;
// private View mView;
// private ListItem mListItem;
//
// private boolean mIsVisibleItemChanged;
//
// public int getIndex() {
// return mIndexInAdapter;
// }
//
// public View getView() {
// return mView;
// }
//
// public ListItem getListItem() {
// return mListItem;
// }
//
// public ListItemData fillWithData(int indexInAdapter, View view, ListItem item) {
// mIndexInAdapter = indexInAdapter;
// mView = view;
// mListItem = item;
// return this;
// }
//
// public boolean isIndexValid() {
// return mIndexInAdapter != null;
// }
//
// public boolean isAvailable() {
// return mIndexInAdapter != null && mView != null && mListItem != null;
// }
//
// public void setVisibleItemChanged(boolean isDataChanged) {
// mIsVisibleItemChanged = isDataChanged;
// }
//
// public boolean isVisibleItemChanged() {
// return mIsVisibleItemChanged;
// }
//
// @Override
// public String toString() {
// return "ListItemData{" +
// "mIndexInAdapter=" + mIndexInAdapter +
// ", mView=" + mView +
// ", mListItem=" + mListItem +
// ", mIsVisibleItemChanged=" + mIsVisibleItemChanged +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ListItemData that = (ListItemData) o;
//
// return (mIndexInAdapter != null ? mIndexInAdapter.equals(that.mIndexInAdapter) : that.mIndexInAdapter == null)
// && (mView != null ? mView.equals(that.mView) : that.mView == null);
//
// }
//
// @Override
// public int hashCode() {
// int result = mIndexInAdapter != null ? mIndexInAdapter.hashCode() : 0;
// result = 31 * result + (mView != null ? mView.hashCode() : 0);
// return result;
// }
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsPositionGetter.java
// public interface ItemsPositionGetter {
// View getChildAt(int position);
//
// int indexOfChild(View view);
//
// int getChildCount();
//
// int getLastVisiblePosition();
//
// int getFirstVisiblePosition();
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsProvider.java
// public interface ItemsProvider {
//
// ListItem getListItem(int position);
//
// int listItemSize();
//
// }
|
import android.util.Log;
import android.view.View;
import com.waynell.videolist.visibility.items.ListItem;
import com.waynell.videolist.visibility.items.ListItemData;
import com.waynell.videolist.visibility.scroll.ItemsPositionGetter;
import com.waynell.videolist.visibility.scroll.ItemsProvider;
|
package com.waynell.videolist.visibility.calculator;
/**
* A utility that tracks current {@link ListItem} visibility.
* Current ListItem is an item defined by calling {@link #setCurrentItem(ListItemData)}.
* Or it might be mock current item created in method {@link #getMockCurrentItem}
*
* The logic is following: when current view is going out of screen (up or down) by {@link #INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS} or more then neighbour item become "active" by calling {@link Callback#activateNewCurrentItem}
* "Going out of screen" is calculated when {@link #onStateTouchScroll} is called from super class {@link BaseItemsVisibilityCalculator}
*
* Method {@link ListItemsVisibilityCalculator#onScrollStateIdle} should be called only when scroll state become idle. // TODO: test it
* When it's called we look for new current item that eventually will be set as "active" by calling {@link #setCurrentItem(ListItemData)}
* Regarding the {@link #mScrollDirection} new current item is calculated from top to bottom (if DOWN) or from bottom to top (if UP).
* The first(or last) visible item is set to current. It's visibility percentage is calculated. Then we are going though all visible items and find the one that is the most visible.
*
* Method {@link #onStateLost} is calling {@link Callback#deactivateCurrentItem}
*
* @author Wayne
*/
public class SingleListViewItemActiveCalculator extends BaseItemsVisibilityCalculator {
private static final String TAG = "ListViewItemActiveCal";
private static final boolean SHOW_LOGS = false;
private static final int INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS = 70;
private final Callback<ListItem> mCallback;
|
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItem.java
// public interface ListItem {
//
// /**
// * When view visibility become bigger than "current active" view visibility then the new view becomes active.
// * This method is called
// */
// void setActive(View newActiveView, int newActiveViewPosition);
//
// /**
// * There might be a case when not only new view becomes active, but also when no view is active.
// * When view should stop being active this method is called
// */
// void deactivate(View currentView, int position);
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItemData.java
// public class ListItemData {
//
// private Integer mIndexInAdapter;
// private View mView;
// private ListItem mListItem;
//
// private boolean mIsVisibleItemChanged;
//
// public int getIndex() {
// return mIndexInAdapter;
// }
//
// public View getView() {
// return mView;
// }
//
// public ListItem getListItem() {
// return mListItem;
// }
//
// public ListItemData fillWithData(int indexInAdapter, View view, ListItem item) {
// mIndexInAdapter = indexInAdapter;
// mView = view;
// mListItem = item;
// return this;
// }
//
// public boolean isIndexValid() {
// return mIndexInAdapter != null;
// }
//
// public boolean isAvailable() {
// return mIndexInAdapter != null && mView != null && mListItem != null;
// }
//
// public void setVisibleItemChanged(boolean isDataChanged) {
// mIsVisibleItemChanged = isDataChanged;
// }
//
// public boolean isVisibleItemChanged() {
// return mIsVisibleItemChanged;
// }
//
// @Override
// public String toString() {
// return "ListItemData{" +
// "mIndexInAdapter=" + mIndexInAdapter +
// ", mView=" + mView +
// ", mListItem=" + mListItem +
// ", mIsVisibleItemChanged=" + mIsVisibleItemChanged +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ListItemData that = (ListItemData) o;
//
// return (mIndexInAdapter != null ? mIndexInAdapter.equals(that.mIndexInAdapter) : that.mIndexInAdapter == null)
// && (mView != null ? mView.equals(that.mView) : that.mView == null);
//
// }
//
// @Override
// public int hashCode() {
// int result = mIndexInAdapter != null ? mIndexInAdapter.hashCode() : 0;
// result = 31 * result + (mView != null ? mView.hashCode() : 0);
// return result;
// }
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsPositionGetter.java
// public interface ItemsPositionGetter {
// View getChildAt(int position);
//
// int indexOfChild(View view);
//
// int getChildCount();
//
// int getLastVisiblePosition();
//
// int getFirstVisiblePosition();
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsProvider.java
// public interface ItemsProvider {
//
// ListItem getListItem(int position);
//
// int listItemSize();
//
// }
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/calculator/SingleListViewItemActiveCalculator.java
import android.util.Log;
import android.view.View;
import com.waynell.videolist.visibility.items.ListItem;
import com.waynell.videolist.visibility.items.ListItemData;
import com.waynell.videolist.visibility.scroll.ItemsPositionGetter;
import com.waynell.videolist.visibility.scroll.ItemsProvider;
package com.waynell.videolist.visibility.calculator;
/**
* A utility that tracks current {@link ListItem} visibility.
* Current ListItem is an item defined by calling {@link #setCurrentItem(ListItemData)}.
* Or it might be mock current item created in method {@link #getMockCurrentItem}
*
* The logic is following: when current view is going out of screen (up or down) by {@link #INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS} or more then neighbour item become "active" by calling {@link Callback#activateNewCurrentItem}
* "Going out of screen" is calculated when {@link #onStateTouchScroll} is called from super class {@link BaseItemsVisibilityCalculator}
*
* Method {@link ListItemsVisibilityCalculator#onScrollStateIdle} should be called only when scroll state become idle. // TODO: test it
* When it's called we look for new current item that eventually will be set as "active" by calling {@link #setCurrentItem(ListItemData)}
* Regarding the {@link #mScrollDirection} new current item is calculated from top to bottom (if DOWN) or from bottom to top (if UP).
* The first(or last) visible item is set to current. It's visibility percentage is calculated. Then we are going though all visible items and find the one that is the most visible.
*
* Method {@link #onStateLost} is calling {@link Callback#deactivateCurrentItem}
*
* @author Wayne
*/
public class SingleListViewItemActiveCalculator extends BaseItemsVisibilityCalculator {
private static final String TAG = "ListViewItemActiveCal";
private static final boolean SHOW_LOGS = false;
private static final int INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS = 70;
private final Callback<ListItem> mCallback;
|
private final ItemsProvider mItemsProvider;
|
waynell/VideoListPlayer
|
video-list-player/src/main/java/com/waynell/videolist/visibility/calculator/SingleListViewItemActiveCalculator.java
|
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItem.java
// public interface ListItem {
//
// /**
// * When view visibility become bigger than "current active" view visibility then the new view becomes active.
// * This method is called
// */
// void setActive(View newActiveView, int newActiveViewPosition);
//
// /**
// * There might be a case when not only new view becomes active, but also when no view is active.
// * When view should stop being active this method is called
// */
// void deactivate(View currentView, int position);
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItemData.java
// public class ListItemData {
//
// private Integer mIndexInAdapter;
// private View mView;
// private ListItem mListItem;
//
// private boolean mIsVisibleItemChanged;
//
// public int getIndex() {
// return mIndexInAdapter;
// }
//
// public View getView() {
// return mView;
// }
//
// public ListItem getListItem() {
// return mListItem;
// }
//
// public ListItemData fillWithData(int indexInAdapter, View view, ListItem item) {
// mIndexInAdapter = indexInAdapter;
// mView = view;
// mListItem = item;
// return this;
// }
//
// public boolean isIndexValid() {
// return mIndexInAdapter != null;
// }
//
// public boolean isAvailable() {
// return mIndexInAdapter != null && mView != null && mListItem != null;
// }
//
// public void setVisibleItemChanged(boolean isDataChanged) {
// mIsVisibleItemChanged = isDataChanged;
// }
//
// public boolean isVisibleItemChanged() {
// return mIsVisibleItemChanged;
// }
//
// @Override
// public String toString() {
// return "ListItemData{" +
// "mIndexInAdapter=" + mIndexInAdapter +
// ", mView=" + mView +
// ", mListItem=" + mListItem +
// ", mIsVisibleItemChanged=" + mIsVisibleItemChanged +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ListItemData that = (ListItemData) o;
//
// return (mIndexInAdapter != null ? mIndexInAdapter.equals(that.mIndexInAdapter) : that.mIndexInAdapter == null)
// && (mView != null ? mView.equals(that.mView) : that.mView == null);
//
// }
//
// @Override
// public int hashCode() {
// int result = mIndexInAdapter != null ? mIndexInAdapter.hashCode() : 0;
// result = 31 * result + (mView != null ? mView.hashCode() : 0);
// return result;
// }
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsPositionGetter.java
// public interface ItemsPositionGetter {
// View getChildAt(int position);
//
// int indexOfChild(View view);
//
// int getChildCount();
//
// int getLastVisiblePosition();
//
// int getFirstVisiblePosition();
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsProvider.java
// public interface ItemsProvider {
//
// ListItem getListItem(int position);
//
// int listItemSize();
//
// }
|
import android.util.Log;
import android.view.View;
import com.waynell.videolist.visibility.items.ListItem;
import com.waynell.videolist.visibility.items.ListItemData;
import com.waynell.videolist.visibility.scroll.ItemsPositionGetter;
import com.waynell.videolist.visibility.scroll.ItemsProvider;
|
package com.waynell.videolist.visibility.calculator;
/**
* A utility that tracks current {@link ListItem} visibility.
* Current ListItem is an item defined by calling {@link #setCurrentItem(ListItemData)}.
* Or it might be mock current item created in method {@link #getMockCurrentItem}
*
* The logic is following: when current view is going out of screen (up or down) by {@link #INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS} or more then neighbour item become "active" by calling {@link Callback#activateNewCurrentItem}
* "Going out of screen" is calculated when {@link #onStateTouchScroll} is called from super class {@link BaseItemsVisibilityCalculator}
*
* Method {@link ListItemsVisibilityCalculator#onScrollStateIdle} should be called only when scroll state become idle. // TODO: test it
* When it's called we look for new current item that eventually will be set as "active" by calling {@link #setCurrentItem(ListItemData)}
* Regarding the {@link #mScrollDirection} new current item is calculated from top to bottom (if DOWN) or from bottom to top (if UP).
* The first(or last) visible item is set to current. It's visibility percentage is calculated. Then we are going though all visible items and find the one that is the most visible.
*
* Method {@link #onStateLost} is calling {@link Callback#deactivateCurrentItem}
*
* @author Wayne
*/
public class SingleListViewItemActiveCalculator extends BaseItemsVisibilityCalculator {
private static final String TAG = "ListViewItemActiveCal";
private static final boolean SHOW_LOGS = false;
private static final int INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS = 70;
private final Callback<ListItem> mCallback;
private final ItemsProvider mItemsProvider;
/**
* The data of this member will be changing all the time
*/
|
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItem.java
// public interface ListItem {
//
// /**
// * When view visibility become bigger than "current active" view visibility then the new view becomes active.
// * This method is called
// */
// void setActive(View newActiveView, int newActiveViewPosition);
//
// /**
// * There might be a case when not only new view becomes active, but also when no view is active.
// * When view should stop being active this method is called
// */
// void deactivate(View currentView, int position);
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItemData.java
// public class ListItemData {
//
// private Integer mIndexInAdapter;
// private View mView;
// private ListItem mListItem;
//
// private boolean mIsVisibleItemChanged;
//
// public int getIndex() {
// return mIndexInAdapter;
// }
//
// public View getView() {
// return mView;
// }
//
// public ListItem getListItem() {
// return mListItem;
// }
//
// public ListItemData fillWithData(int indexInAdapter, View view, ListItem item) {
// mIndexInAdapter = indexInAdapter;
// mView = view;
// mListItem = item;
// return this;
// }
//
// public boolean isIndexValid() {
// return mIndexInAdapter != null;
// }
//
// public boolean isAvailable() {
// return mIndexInAdapter != null && mView != null && mListItem != null;
// }
//
// public void setVisibleItemChanged(boolean isDataChanged) {
// mIsVisibleItemChanged = isDataChanged;
// }
//
// public boolean isVisibleItemChanged() {
// return mIsVisibleItemChanged;
// }
//
// @Override
// public String toString() {
// return "ListItemData{" +
// "mIndexInAdapter=" + mIndexInAdapter +
// ", mView=" + mView +
// ", mListItem=" + mListItem +
// ", mIsVisibleItemChanged=" + mIsVisibleItemChanged +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ListItemData that = (ListItemData) o;
//
// return (mIndexInAdapter != null ? mIndexInAdapter.equals(that.mIndexInAdapter) : that.mIndexInAdapter == null)
// && (mView != null ? mView.equals(that.mView) : that.mView == null);
//
// }
//
// @Override
// public int hashCode() {
// int result = mIndexInAdapter != null ? mIndexInAdapter.hashCode() : 0;
// result = 31 * result + (mView != null ? mView.hashCode() : 0);
// return result;
// }
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsPositionGetter.java
// public interface ItemsPositionGetter {
// View getChildAt(int position);
//
// int indexOfChild(View view);
//
// int getChildCount();
//
// int getLastVisiblePosition();
//
// int getFirstVisiblePosition();
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsProvider.java
// public interface ItemsProvider {
//
// ListItem getListItem(int position);
//
// int listItemSize();
//
// }
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/calculator/SingleListViewItemActiveCalculator.java
import android.util.Log;
import android.view.View;
import com.waynell.videolist.visibility.items.ListItem;
import com.waynell.videolist.visibility.items.ListItemData;
import com.waynell.videolist.visibility.scroll.ItemsPositionGetter;
import com.waynell.videolist.visibility.scroll.ItemsProvider;
package com.waynell.videolist.visibility.calculator;
/**
* A utility that tracks current {@link ListItem} visibility.
* Current ListItem is an item defined by calling {@link #setCurrentItem(ListItemData)}.
* Or it might be mock current item created in method {@link #getMockCurrentItem}
*
* The logic is following: when current view is going out of screen (up or down) by {@link #INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS} or more then neighbour item become "active" by calling {@link Callback#activateNewCurrentItem}
* "Going out of screen" is calculated when {@link #onStateTouchScroll} is called from super class {@link BaseItemsVisibilityCalculator}
*
* Method {@link ListItemsVisibilityCalculator#onScrollStateIdle} should be called only when scroll state become idle. // TODO: test it
* When it's called we look for new current item that eventually will be set as "active" by calling {@link #setCurrentItem(ListItemData)}
* Regarding the {@link #mScrollDirection} new current item is calculated from top to bottom (if DOWN) or from bottom to top (if UP).
* The first(or last) visible item is set to current. It's visibility percentage is calculated. Then we are going though all visible items and find the one that is the most visible.
*
* Method {@link #onStateLost} is calling {@link Callback#deactivateCurrentItem}
*
* @author Wayne
*/
public class SingleListViewItemActiveCalculator extends BaseItemsVisibilityCalculator {
private static final String TAG = "ListViewItemActiveCal";
private static final boolean SHOW_LOGS = false;
private static final int INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS = 70;
private final Callback<ListItem> mCallback;
private final ItemsProvider mItemsProvider;
/**
* The data of this member will be changing all the time
*/
|
private final ListItemData mCurrentItem = new ListItemData();
|
waynell/VideoListPlayer
|
video-list-player/src/main/java/com/waynell/videolist/visibility/calculator/SingleListViewItemActiveCalculator.java
|
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItem.java
// public interface ListItem {
//
// /**
// * When view visibility become bigger than "current active" view visibility then the new view becomes active.
// * This method is called
// */
// void setActive(View newActiveView, int newActiveViewPosition);
//
// /**
// * There might be a case when not only new view becomes active, but also when no view is active.
// * When view should stop being active this method is called
// */
// void deactivate(View currentView, int position);
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItemData.java
// public class ListItemData {
//
// private Integer mIndexInAdapter;
// private View mView;
// private ListItem mListItem;
//
// private boolean mIsVisibleItemChanged;
//
// public int getIndex() {
// return mIndexInAdapter;
// }
//
// public View getView() {
// return mView;
// }
//
// public ListItem getListItem() {
// return mListItem;
// }
//
// public ListItemData fillWithData(int indexInAdapter, View view, ListItem item) {
// mIndexInAdapter = indexInAdapter;
// mView = view;
// mListItem = item;
// return this;
// }
//
// public boolean isIndexValid() {
// return mIndexInAdapter != null;
// }
//
// public boolean isAvailable() {
// return mIndexInAdapter != null && mView != null && mListItem != null;
// }
//
// public void setVisibleItemChanged(boolean isDataChanged) {
// mIsVisibleItemChanged = isDataChanged;
// }
//
// public boolean isVisibleItemChanged() {
// return mIsVisibleItemChanged;
// }
//
// @Override
// public String toString() {
// return "ListItemData{" +
// "mIndexInAdapter=" + mIndexInAdapter +
// ", mView=" + mView +
// ", mListItem=" + mListItem +
// ", mIsVisibleItemChanged=" + mIsVisibleItemChanged +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ListItemData that = (ListItemData) o;
//
// return (mIndexInAdapter != null ? mIndexInAdapter.equals(that.mIndexInAdapter) : that.mIndexInAdapter == null)
// && (mView != null ? mView.equals(that.mView) : that.mView == null);
//
// }
//
// @Override
// public int hashCode() {
// int result = mIndexInAdapter != null ? mIndexInAdapter.hashCode() : 0;
// result = 31 * result + (mView != null ? mView.hashCode() : 0);
// return result;
// }
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsPositionGetter.java
// public interface ItemsPositionGetter {
// View getChildAt(int position);
//
// int indexOfChild(View view);
//
// int getChildCount();
//
// int getLastVisiblePosition();
//
// int getFirstVisiblePosition();
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsProvider.java
// public interface ItemsProvider {
//
// ListItem getListItem(int position);
//
// int listItemSize();
//
// }
|
import android.util.Log;
import android.view.View;
import com.waynell.videolist.visibility.items.ListItem;
import com.waynell.videolist.visibility.items.ListItemData;
import com.waynell.videolist.visibility.scroll.ItemsPositionGetter;
import com.waynell.videolist.visibility.scroll.ItemsProvider;
|
package com.waynell.videolist.visibility.calculator;
/**
* A utility that tracks current {@link ListItem} visibility.
* Current ListItem is an item defined by calling {@link #setCurrentItem(ListItemData)}.
* Or it might be mock current item created in method {@link #getMockCurrentItem}
*
* The logic is following: when current view is going out of screen (up or down) by {@link #INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS} or more then neighbour item become "active" by calling {@link Callback#activateNewCurrentItem}
* "Going out of screen" is calculated when {@link #onStateTouchScroll} is called from super class {@link BaseItemsVisibilityCalculator}
*
* Method {@link ListItemsVisibilityCalculator#onScrollStateIdle} should be called only when scroll state become idle. // TODO: test it
* When it's called we look for new current item that eventually will be set as "active" by calling {@link #setCurrentItem(ListItemData)}
* Regarding the {@link #mScrollDirection} new current item is calculated from top to bottom (if DOWN) or from bottom to top (if UP).
* The first(or last) visible item is set to current. It's visibility percentage is calculated. Then we are going though all visible items and find the one that is the most visible.
*
* Method {@link #onStateLost} is calling {@link Callback#deactivateCurrentItem}
*
* @author Wayne
*/
public class SingleListViewItemActiveCalculator extends BaseItemsVisibilityCalculator {
private static final String TAG = "ListViewItemActiveCal";
private static final boolean SHOW_LOGS = false;
private static final int INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS = 70;
private final Callback<ListItem> mCallback;
private final ItemsProvider mItemsProvider;
/**
* The data of this member will be changing all the time
*/
private final ListItemData mCurrentItem = new ListItemData();
private final ListItemData mPreActiveItem = new ListItemData();
|
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItem.java
// public interface ListItem {
//
// /**
// * When view visibility become bigger than "current active" view visibility then the new view becomes active.
// * This method is called
// */
// void setActive(View newActiveView, int newActiveViewPosition);
//
// /**
// * There might be a case when not only new view becomes active, but also when no view is active.
// * When view should stop being active this method is called
// */
// void deactivate(View currentView, int position);
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/items/ListItemData.java
// public class ListItemData {
//
// private Integer mIndexInAdapter;
// private View mView;
// private ListItem mListItem;
//
// private boolean mIsVisibleItemChanged;
//
// public int getIndex() {
// return mIndexInAdapter;
// }
//
// public View getView() {
// return mView;
// }
//
// public ListItem getListItem() {
// return mListItem;
// }
//
// public ListItemData fillWithData(int indexInAdapter, View view, ListItem item) {
// mIndexInAdapter = indexInAdapter;
// mView = view;
// mListItem = item;
// return this;
// }
//
// public boolean isIndexValid() {
// return mIndexInAdapter != null;
// }
//
// public boolean isAvailable() {
// return mIndexInAdapter != null && mView != null && mListItem != null;
// }
//
// public void setVisibleItemChanged(boolean isDataChanged) {
// mIsVisibleItemChanged = isDataChanged;
// }
//
// public boolean isVisibleItemChanged() {
// return mIsVisibleItemChanged;
// }
//
// @Override
// public String toString() {
// return "ListItemData{" +
// "mIndexInAdapter=" + mIndexInAdapter +
// ", mView=" + mView +
// ", mListItem=" + mListItem +
// ", mIsVisibleItemChanged=" + mIsVisibleItemChanged +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ListItemData that = (ListItemData) o;
//
// return (mIndexInAdapter != null ? mIndexInAdapter.equals(that.mIndexInAdapter) : that.mIndexInAdapter == null)
// && (mView != null ? mView.equals(that.mView) : that.mView == null);
//
// }
//
// @Override
// public int hashCode() {
// int result = mIndexInAdapter != null ? mIndexInAdapter.hashCode() : 0;
// result = 31 * result + (mView != null ? mView.hashCode() : 0);
// return result;
// }
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsPositionGetter.java
// public interface ItemsPositionGetter {
// View getChildAt(int position);
//
// int indexOfChild(View view);
//
// int getChildCount();
//
// int getLastVisiblePosition();
//
// int getFirstVisiblePosition();
// }
//
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/scroll/ItemsProvider.java
// public interface ItemsProvider {
//
// ListItem getListItem(int position);
//
// int listItemSize();
//
// }
// Path: video-list-player/src/main/java/com/waynell/videolist/visibility/calculator/SingleListViewItemActiveCalculator.java
import android.util.Log;
import android.view.View;
import com.waynell.videolist.visibility.items.ListItem;
import com.waynell.videolist.visibility.items.ListItemData;
import com.waynell.videolist.visibility.scroll.ItemsPositionGetter;
import com.waynell.videolist.visibility.scroll.ItemsProvider;
package com.waynell.videolist.visibility.calculator;
/**
* A utility that tracks current {@link ListItem} visibility.
* Current ListItem is an item defined by calling {@link #setCurrentItem(ListItemData)}.
* Or it might be mock current item created in method {@link #getMockCurrentItem}
*
* The logic is following: when current view is going out of screen (up or down) by {@link #INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS} or more then neighbour item become "active" by calling {@link Callback#activateNewCurrentItem}
* "Going out of screen" is calculated when {@link #onStateTouchScroll} is called from super class {@link BaseItemsVisibilityCalculator}
*
* Method {@link ListItemsVisibilityCalculator#onScrollStateIdle} should be called only when scroll state become idle. // TODO: test it
* When it's called we look for new current item that eventually will be set as "active" by calling {@link #setCurrentItem(ListItemData)}
* Regarding the {@link #mScrollDirection} new current item is calculated from top to bottom (if DOWN) or from bottom to top (if UP).
* The first(or last) visible item is set to current. It's visibility percentage is calculated. Then we are going though all visible items and find the one that is the most visible.
*
* Method {@link #onStateLost} is calling {@link Callback#deactivateCurrentItem}
*
* @author Wayne
*/
public class SingleListViewItemActiveCalculator extends BaseItemsVisibilityCalculator {
private static final String TAG = "ListViewItemActiveCal";
private static final boolean SHOW_LOGS = false;
private static final int INACTIVE_LIST_ITEM_VISIBILITY_PERCENTS = 70;
private final Callback<ListItem> mCallback;
private final ItemsProvider mItemsProvider;
/**
* The data of this member will be changing all the time
*/
private final ListItemData mCurrentItem = new ListItemData();
private final ListItemData mPreActiveItem = new ListItemData();
|
public SingleListViewItemActiveCalculator(ItemsProvider itemsProvider, ItemsPositionGetter itemsPositionGetter) {
|
FenixEdu/fenixedu-learning
|
src/main/java/org/fenixedu/learning/domain/executionCourse/components/ObjectivesComponent.java
|
// Path: src/main/java/org/fenixedu/learning/domain/executionCourse/CompetenceCourseBean.java
// public class CompetenceCourseBean {
// private final CompetenceCourse competenceCourse;
// private final ExecutionSemester executionSemester;
// private final Set<CurricularCourse> curricularCourses;
// private final LocalizedString name;
// private final LocalizedString objectives;
// private final LocalizedString program;
// private final LocalizedString prerequisites;
// private final LocalizedString laboratorialComponent;
// private final LocalizedString programmingAndComputingComponent;
// private final LocalizedString crossCompetenceComponent;
// private final LocalizedString ethicalPrinciples;
//
//
// public CompetenceCourseBean(CompetenceCourse competenceCourse, Set<CurricularCourse> curricularCourses,
// ExecutionSemester executionSemester) {
// this.competenceCourse = competenceCourse;
// this.executionSemester = executionSemester;
// this.curricularCourses = curricularCourses;
// this.name = competenceCourse.getNameI18N(executionSemester);
// this.objectives = competenceCourse.getObjectivesI18N(executionSemester);
// this.program = competenceCourse.getProgramI18N(executionSemester);
// this.prerequisites=competenceCourse.getPrerequisitesI18N(executionSemester);
// this.laboratorialComponent=competenceCourse.getLaboratorialComponentI18N(executionSemester);
// this.programmingAndComputingComponent=competenceCourse.getProgrammingAndComputingComponentI18N(executionSemester);
// this.crossCompetenceComponent=competenceCourse.getCrossCompetenceComponentI18N(executionSemester);
// this.ethicalPrinciples=competenceCourse.getEthicalPrinciplesI18N(executionSemester);
//
// }
//
// public CompetenceCourse getCompetenceCourse() {
// return competenceCourse;
// }
//
// public ExecutionSemester getExecutionSemester() {
// return executionSemester;
// }
//
// public Set<CurricularCourse> getCurricularCourses() {
// return curricularCourses;
// }
//
// public LocalizedString getName() {
// return name;
// }
//
// public LocalizedString getObjectives() {
// return objectives;
// }
//
// public static List<CompetenceCourseBean> approvedCompetenceCourses(ExecutionCourse executionCourse) {
// return executionCourse.getCurricularCoursesIndexedByCompetenceCourse().entrySet().stream()
// .filter(entry -> entry.getKey().isApproved())
// .map(entry -> new CompetenceCourseBean(entry.getKey(), entry.getValue(), executionCourse.getExecutionPeriod()))
// .collect(Collectors.toList());
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this).add("name", this.name).add("objectives", this.objectives)
// .add("executionSemester", executionSemester).add("curricularCourses", curricularCourses).toString();
// }
//
// public LocalizedString getProgram() {
// return program;
// }
//
// public LocalizedString getPrerequisites() {
// return prerequisites;
// }
//
// public LocalizedString getLaboratorialComponent() {
// return laboratorialComponent;
// }
//
// public LocalizedString getProgrammingAndComputingComponent() {
// return programmingAndComputingComponent;
// }
//
// public LocalizedString getCrossCompetenceComponent() {
// return crossCompetenceComponent;
// }
//
// public LocalizedString getEthicalPrinciples() {
// return ethicalPrinciples;
// }
//
//
// }
|
import org.fenixedu.learning.domain.executionCourse.CompetenceCourseBean;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.fenixedu.academic.domain.CurricularCourse;
import org.fenixedu.academic.domain.Curriculum;
import org.fenixedu.academic.domain.ExecutionCourse;
import org.fenixedu.cms.domain.Page;
import org.fenixedu.cms.domain.component.ComponentType;
import org.fenixedu.cms.rendering.TemplateContext;
|
/**
* Copyright © 2015 Instituto Superior Técnico
*
* This file is part of FenixEdu Learning.
*
* FenixEdu Learning is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FenixEdu Learning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with FenixEdu Learning. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.learning.domain.executionCourse.components;
@ComponentType(name = "CompetenceCourse", description = "Competence Course information for an Execution Course")
public class ObjectivesComponent extends BaseExecutionCourseComponent {
@Override
public void handle(Page page, TemplateContext componentContext, TemplateContext globalContext) {
ExecutionCourse executionCourse = page.getSite().getExecutionCourse();
globalContext.put("executionPeriod", executionCourse.getExecutionPeriod());
|
// Path: src/main/java/org/fenixedu/learning/domain/executionCourse/CompetenceCourseBean.java
// public class CompetenceCourseBean {
// private final CompetenceCourse competenceCourse;
// private final ExecutionSemester executionSemester;
// private final Set<CurricularCourse> curricularCourses;
// private final LocalizedString name;
// private final LocalizedString objectives;
// private final LocalizedString program;
// private final LocalizedString prerequisites;
// private final LocalizedString laboratorialComponent;
// private final LocalizedString programmingAndComputingComponent;
// private final LocalizedString crossCompetenceComponent;
// private final LocalizedString ethicalPrinciples;
//
//
// public CompetenceCourseBean(CompetenceCourse competenceCourse, Set<CurricularCourse> curricularCourses,
// ExecutionSemester executionSemester) {
// this.competenceCourse = competenceCourse;
// this.executionSemester = executionSemester;
// this.curricularCourses = curricularCourses;
// this.name = competenceCourse.getNameI18N(executionSemester);
// this.objectives = competenceCourse.getObjectivesI18N(executionSemester);
// this.program = competenceCourse.getProgramI18N(executionSemester);
// this.prerequisites=competenceCourse.getPrerequisitesI18N(executionSemester);
// this.laboratorialComponent=competenceCourse.getLaboratorialComponentI18N(executionSemester);
// this.programmingAndComputingComponent=competenceCourse.getProgrammingAndComputingComponentI18N(executionSemester);
// this.crossCompetenceComponent=competenceCourse.getCrossCompetenceComponentI18N(executionSemester);
// this.ethicalPrinciples=competenceCourse.getEthicalPrinciplesI18N(executionSemester);
//
// }
//
// public CompetenceCourse getCompetenceCourse() {
// return competenceCourse;
// }
//
// public ExecutionSemester getExecutionSemester() {
// return executionSemester;
// }
//
// public Set<CurricularCourse> getCurricularCourses() {
// return curricularCourses;
// }
//
// public LocalizedString getName() {
// return name;
// }
//
// public LocalizedString getObjectives() {
// return objectives;
// }
//
// public static List<CompetenceCourseBean> approvedCompetenceCourses(ExecutionCourse executionCourse) {
// return executionCourse.getCurricularCoursesIndexedByCompetenceCourse().entrySet().stream()
// .filter(entry -> entry.getKey().isApproved())
// .map(entry -> new CompetenceCourseBean(entry.getKey(), entry.getValue(), executionCourse.getExecutionPeriod()))
// .collect(Collectors.toList());
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this).add("name", this.name).add("objectives", this.objectives)
// .add("executionSemester", executionSemester).add("curricularCourses", curricularCourses).toString();
// }
//
// public LocalizedString getProgram() {
// return program;
// }
//
// public LocalizedString getPrerequisites() {
// return prerequisites;
// }
//
// public LocalizedString getLaboratorialComponent() {
// return laboratorialComponent;
// }
//
// public LocalizedString getProgrammingAndComputingComponent() {
// return programmingAndComputingComponent;
// }
//
// public LocalizedString getCrossCompetenceComponent() {
// return crossCompetenceComponent;
// }
//
// public LocalizedString getEthicalPrinciples() {
// return ethicalPrinciples;
// }
//
//
// }
// Path: src/main/java/org/fenixedu/learning/domain/executionCourse/components/ObjectivesComponent.java
import org.fenixedu.learning.domain.executionCourse.CompetenceCourseBean;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.fenixedu.academic.domain.CurricularCourse;
import org.fenixedu.academic.domain.Curriculum;
import org.fenixedu.academic.domain.ExecutionCourse;
import org.fenixedu.cms.domain.Page;
import org.fenixedu.cms.domain.component.ComponentType;
import org.fenixedu.cms.rendering.TemplateContext;
/**
* Copyright © 2015 Instituto Superior Técnico
*
* This file is part of FenixEdu Learning.
*
* FenixEdu Learning is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FenixEdu Learning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with FenixEdu Learning. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.learning.domain.executionCourse.components;
@ComponentType(name = "CompetenceCourse", description = "Competence Course information for an Execution Course")
public class ObjectivesComponent extends BaseExecutionCourseComponent {
@Override
public void handle(Page page, TemplateContext componentContext, TemplateContext globalContext) {
ExecutionCourse executionCourse = page.getSite().getExecutionCourse();
globalContext.put("executionPeriod", executionCourse.getExecutionPeriod());
|
globalContext.put("competenceCourseBeans", CompetenceCourseBean.approvedCompetenceCourses(executionCourse));
|
FenixEdu/fenixedu-learning
|
src/main/java/org/fenixedu/learning/ui/SpecificSitesAdmin.java
|
// Path: src/main/java/org/fenixedu/learning/domain/degree/DegreeSiteListener.java
// public class DegreeSiteListener {
//
// @Atomic
// public static Site create(Degree degree) {
// LocalizedString name;
//
// if (degree.getPhdProgram() != null) {
// name = new LocalizedString().with(Locale.getDefault(), degree.getPhdProgram().getPresentationName());
// } else {
// name = new LocalizedString().with(Locale.getDefault(), degree.getPresentationName());
// }
//
// Site site = DegreeSiteBuilder.getInstance().create(name);
//
// RoleTemplate defaultTemplate = site.getDefaultRoleTemplate();
// if (defaultTemplate != null ) {
// Group group = Group.users(CoordinatorGroup.get(degree).getMembers());
// site.getDefaultRoleTemplateRole().setGroup(group);
// } else {
// throw new DomainException("no.default.role");
// }
//
// site.setDegree(degree);
// site.setSlug(degree.getSigla());
//
// return site;
// }
//
//
//
//
// }
//
// Path: src/main/java/org/fenixedu/learning/domain/executionCourse/ExecutionCourseListener.java
// public class ExecutionCourseListener {
//
//
// private static final Logger logger = LoggerFactory.getLogger(ExecutionCourseListener.class);
//
// public static Site create(ExecutionCourse executionCourse) {
// Site newSite = ExecutionCourseSiteBuilder.getInstance().create(executionCourse);
//
// RoleTemplate defaultTemplate = newSite.getDefaultRoleTemplate();
// if (defaultTemplate != null ) {
// Role teacherRole =
// new Role(defaultTemplate, executionCourse.getSite());
//
// Group group = teacherRole.getGroup();
// for(Professorship pr : executionCourse.getProfessorshipsSet()) {
// User user = pr.getPerson().getUser();
// if (pr.getPermissions().getSections() && !group.isMember(user)) {
// group = group.grant(user);
// } else if (group.isMember(user)) {
// group = group.revoke(user);
// }
// }
// teacherRole.setGroup(group);
// } else {
// throw new DomainException("no.default.role");
// }
//
// logger.info("Created site for execution course " + executionCourse.getSigla());
// return newSite;
// }
//
//
// public static void updateSiteSlug(ExecutionCourse instance) {
// instance.getSite().setSlug(ExecutionCourseSiteBuilder.formatSlugForExecutionCourse(instance));
// instance.setSiteUrl(instance.getSite().getFullUrl());
// }
//
// public static void updateProfessorship(Professorship professorship, Boolean allowAccess ) {
// ExecutionCourse executionCourse = professorship.getExecutionCourse();
//
// RoleTemplate defaultTemplate = executionCourse.getSite().getDefaultRoleTemplate();
// if (defaultTemplate != null ) {
// Role teacherRole = executionCourse.getSite().getRolesSet().stream()
// .filter(role -> role.getRoleTemplate().equals(defaultTemplate))
// .findAny().orElseGet(() -> new Role(defaultTemplate, executionCourse.getSite()));
//
// Group group = teacherRole.getGroup();
//
// User user = professorship.getPerson().getUser();
// if(allowAccess && !group.isMember(user)){
// group=group.grant(user);
// teacherRole.setGroup(group);
// } else if(group.isMember(user)) {
// group=group.revoke(user);
// teacherRole.setGroup(group);
// }
// } else {
// throw new DomainException("no.default.role");
// }
//
// }
// }
|
import org.fenixedu.academic.domain.Degree;
import org.fenixedu.academic.domain.ExecutionCourse;
import org.fenixedu.cms.domain.Site;
import org.fenixedu.cms.exceptions.CmsDomainException;
import org.fenixedu.learning.domain.degree.DegreeSiteListener;
import org.fenixedu.learning.domain.executionCourse.ExecutionCourseListener;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.RedirectView;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.net.URISyntaxException;
|
package org.fenixedu.learning.ui;
/**
* Created by diutsu on 27/09/16.
*/
@Controller
@RequestMapping("/learning/sites/")
public class SpecificSitesAdmin {
@RequestMapping(value = "/degree", method = RequestMethod.POST)
public RedirectView getDegreeSite(@RequestParam("dsigla") String degreeSigla) throws URISyntaxException {
Degree degree = Degree.readBySigla(degreeSigla);
if(degree==null){
throw CmsDomainException.notFound();
}
if(degree.getSite()!=null){
Site site = degree.getSite();
return new RedirectView(site.getEditUrl());
}
|
// Path: src/main/java/org/fenixedu/learning/domain/degree/DegreeSiteListener.java
// public class DegreeSiteListener {
//
// @Atomic
// public static Site create(Degree degree) {
// LocalizedString name;
//
// if (degree.getPhdProgram() != null) {
// name = new LocalizedString().with(Locale.getDefault(), degree.getPhdProgram().getPresentationName());
// } else {
// name = new LocalizedString().with(Locale.getDefault(), degree.getPresentationName());
// }
//
// Site site = DegreeSiteBuilder.getInstance().create(name);
//
// RoleTemplate defaultTemplate = site.getDefaultRoleTemplate();
// if (defaultTemplate != null ) {
// Group group = Group.users(CoordinatorGroup.get(degree).getMembers());
// site.getDefaultRoleTemplateRole().setGroup(group);
// } else {
// throw new DomainException("no.default.role");
// }
//
// site.setDegree(degree);
// site.setSlug(degree.getSigla());
//
// return site;
// }
//
//
//
//
// }
//
// Path: src/main/java/org/fenixedu/learning/domain/executionCourse/ExecutionCourseListener.java
// public class ExecutionCourseListener {
//
//
// private static final Logger logger = LoggerFactory.getLogger(ExecutionCourseListener.class);
//
// public static Site create(ExecutionCourse executionCourse) {
// Site newSite = ExecutionCourseSiteBuilder.getInstance().create(executionCourse);
//
// RoleTemplate defaultTemplate = newSite.getDefaultRoleTemplate();
// if (defaultTemplate != null ) {
// Role teacherRole =
// new Role(defaultTemplate, executionCourse.getSite());
//
// Group group = teacherRole.getGroup();
// for(Professorship pr : executionCourse.getProfessorshipsSet()) {
// User user = pr.getPerson().getUser();
// if (pr.getPermissions().getSections() && !group.isMember(user)) {
// group = group.grant(user);
// } else if (group.isMember(user)) {
// group = group.revoke(user);
// }
// }
// teacherRole.setGroup(group);
// } else {
// throw new DomainException("no.default.role");
// }
//
// logger.info("Created site for execution course " + executionCourse.getSigla());
// return newSite;
// }
//
//
// public static void updateSiteSlug(ExecutionCourse instance) {
// instance.getSite().setSlug(ExecutionCourseSiteBuilder.formatSlugForExecutionCourse(instance));
// instance.setSiteUrl(instance.getSite().getFullUrl());
// }
//
// public static void updateProfessorship(Professorship professorship, Boolean allowAccess ) {
// ExecutionCourse executionCourse = professorship.getExecutionCourse();
//
// RoleTemplate defaultTemplate = executionCourse.getSite().getDefaultRoleTemplate();
// if (defaultTemplate != null ) {
// Role teacherRole = executionCourse.getSite().getRolesSet().stream()
// .filter(role -> role.getRoleTemplate().equals(defaultTemplate))
// .findAny().orElseGet(() -> new Role(defaultTemplate, executionCourse.getSite()));
//
// Group group = teacherRole.getGroup();
//
// User user = professorship.getPerson().getUser();
// if(allowAccess && !group.isMember(user)){
// group=group.grant(user);
// teacherRole.setGroup(group);
// } else if(group.isMember(user)) {
// group=group.revoke(user);
// teacherRole.setGroup(group);
// }
// } else {
// throw new DomainException("no.default.role");
// }
//
// }
// }
// Path: src/main/java/org/fenixedu/learning/ui/SpecificSitesAdmin.java
import org.fenixedu.academic.domain.Degree;
import org.fenixedu.academic.domain.ExecutionCourse;
import org.fenixedu.cms.domain.Site;
import org.fenixedu.cms.exceptions.CmsDomainException;
import org.fenixedu.learning.domain.degree.DegreeSiteListener;
import org.fenixedu.learning.domain.executionCourse.ExecutionCourseListener;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.RedirectView;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.net.URISyntaxException;
package org.fenixedu.learning.ui;
/**
* Created by diutsu on 27/09/16.
*/
@Controller
@RequestMapping("/learning/sites/")
public class SpecificSitesAdmin {
@RequestMapping(value = "/degree", method = RequestMethod.POST)
public RedirectView getDegreeSite(@RequestParam("dsigla") String degreeSigla) throws URISyntaxException {
Degree degree = Degree.readBySigla(degreeSigla);
if(degree==null){
throw CmsDomainException.notFound();
}
if(degree.getSite()!=null){
Site site = degree.getSite();
return new RedirectView(site.getEditUrl());
}
|
Site site = DegreeSiteListener.create(degree);
|
FenixEdu/fenixedu-learning
|
src/main/java/org/fenixedu/learning/ui/SpecificSitesAdmin.java
|
// Path: src/main/java/org/fenixedu/learning/domain/degree/DegreeSiteListener.java
// public class DegreeSiteListener {
//
// @Atomic
// public static Site create(Degree degree) {
// LocalizedString name;
//
// if (degree.getPhdProgram() != null) {
// name = new LocalizedString().with(Locale.getDefault(), degree.getPhdProgram().getPresentationName());
// } else {
// name = new LocalizedString().with(Locale.getDefault(), degree.getPresentationName());
// }
//
// Site site = DegreeSiteBuilder.getInstance().create(name);
//
// RoleTemplate defaultTemplate = site.getDefaultRoleTemplate();
// if (defaultTemplate != null ) {
// Group group = Group.users(CoordinatorGroup.get(degree).getMembers());
// site.getDefaultRoleTemplateRole().setGroup(group);
// } else {
// throw new DomainException("no.default.role");
// }
//
// site.setDegree(degree);
// site.setSlug(degree.getSigla());
//
// return site;
// }
//
//
//
//
// }
//
// Path: src/main/java/org/fenixedu/learning/domain/executionCourse/ExecutionCourseListener.java
// public class ExecutionCourseListener {
//
//
// private static final Logger logger = LoggerFactory.getLogger(ExecutionCourseListener.class);
//
// public static Site create(ExecutionCourse executionCourse) {
// Site newSite = ExecutionCourseSiteBuilder.getInstance().create(executionCourse);
//
// RoleTemplate defaultTemplate = newSite.getDefaultRoleTemplate();
// if (defaultTemplate != null ) {
// Role teacherRole =
// new Role(defaultTemplate, executionCourse.getSite());
//
// Group group = teacherRole.getGroup();
// for(Professorship pr : executionCourse.getProfessorshipsSet()) {
// User user = pr.getPerson().getUser();
// if (pr.getPermissions().getSections() && !group.isMember(user)) {
// group = group.grant(user);
// } else if (group.isMember(user)) {
// group = group.revoke(user);
// }
// }
// teacherRole.setGroup(group);
// } else {
// throw new DomainException("no.default.role");
// }
//
// logger.info("Created site for execution course " + executionCourse.getSigla());
// return newSite;
// }
//
//
// public static void updateSiteSlug(ExecutionCourse instance) {
// instance.getSite().setSlug(ExecutionCourseSiteBuilder.formatSlugForExecutionCourse(instance));
// instance.setSiteUrl(instance.getSite().getFullUrl());
// }
//
// public static void updateProfessorship(Professorship professorship, Boolean allowAccess ) {
// ExecutionCourse executionCourse = professorship.getExecutionCourse();
//
// RoleTemplate defaultTemplate = executionCourse.getSite().getDefaultRoleTemplate();
// if (defaultTemplate != null ) {
// Role teacherRole = executionCourse.getSite().getRolesSet().stream()
// .filter(role -> role.getRoleTemplate().equals(defaultTemplate))
// .findAny().orElseGet(() -> new Role(defaultTemplate, executionCourse.getSite()));
//
// Group group = teacherRole.getGroup();
//
// User user = professorship.getPerson().getUser();
// if(allowAccess && !group.isMember(user)){
// group=group.grant(user);
// teacherRole.setGroup(group);
// } else if(group.isMember(user)) {
// group=group.revoke(user);
// teacherRole.setGroup(group);
// }
// } else {
// throw new DomainException("no.default.role");
// }
//
// }
// }
|
import org.fenixedu.academic.domain.Degree;
import org.fenixedu.academic.domain.ExecutionCourse;
import org.fenixedu.cms.domain.Site;
import org.fenixedu.cms.exceptions.CmsDomainException;
import org.fenixedu.learning.domain.degree.DegreeSiteListener;
import org.fenixedu.learning.domain.executionCourse.ExecutionCourseListener;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.RedirectView;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.net.URISyntaxException;
|
package org.fenixedu.learning.ui;
/**
* Created by diutsu on 27/09/16.
*/
@Controller
@RequestMapping("/learning/sites/")
public class SpecificSitesAdmin {
@RequestMapping(value = "/degree", method = RequestMethod.POST)
public RedirectView getDegreeSite(@RequestParam("dsigla") String degreeSigla) throws URISyntaxException {
Degree degree = Degree.readBySigla(degreeSigla);
if(degree==null){
throw CmsDomainException.notFound();
}
if(degree.getSite()!=null){
Site site = degree.getSite();
return new RedirectView(site.getEditUrl());
}
Site site = DegreeSiteListener.create(degree);
return new RedirectView(site.getEditUrl());
}
@RequestMapping(value = "/executionCourse", method = RequestMethod.POST)
public RedirectView getExecutionCourseSite(@RequestParam("ecsigla") String executionCourseSigla) throws URISyntaxException {
ExecutionCourse ec = ExecutionCourse.readLastBySigla(executionCourseSigla);
if(ec==null){
throw CmsDomainException.notFound();
}
if(ec.getSite()!=null){
Site site = ec.getSite();
return new RedirectView(site.getEditUrl());
}
|
// Path: src/main/java/org/fenixedu/learning/domain/degree/DegreeSiteListener.java
// public class DegreeSiteListener {
//
// @Atomic
// public static Site create(Degree degree) {
// LocalizedString name;
//
// if (degree.getPhdProgram() != null) {
// name = new LocalizedString().with(Locale.getDefault(), degree.getPhdProgram().getPresentationName());
// } else {
// name = new LocalizedString().with(Locale.getDefault(), degree.getPresentationName());
// }
//
// Site site = DegreeSiteBuilder.getInstance().create(name);
//
// RoleTemplate defaultTemplate = site.getDefaultRoleTemplate();
// if (defaultTemplate != null ) {
// Group group = Group.users(CoordinatorGroup.get(degree).getMembers());
// site.getDefaultRoleTemplateRole().setGroup(group);
// } else {
// throw new DomainException("no.default.role");
// }
//
// site.setDegree(degree);
// site.setSlug(degree.getSigla());
//
// return site;
// }
//
//
//
//
// }
//
// Path: src/main/java/org/fenixedu/learning/domain/executionCourse/ExecutionCourseListener.java
// public class ExecutionCourseListener {
//
//
// private static final Logger logger = LoggerFactory.getLogger(ExecutionCourseListener.class);
//
// public static Site create(ExecutionCourse executionCourse) {
// Site newSite = ExecutionCourseSiteBuilder.getInstance().create(executionCourse);
//
// RoleTemplate defaultTemplate = newSite.getDefaultRoleTemplate();
// if (defaultTemplate != null ) {
// Role teacherRole =
// new Role(defaultTemplate, executionCourse.getSite());
//
// Group group = teacherRole.getGroup();
// for(Professorship pr : executionCourse.getProfessorshipsSet()) {
// User user = pr.getPerson().getUser();
// if (pr.getPermissions().getSections() && !group.isMember(user)) {
// group = group.grant(user);
// } else if (group.isMember(user)) {
// group = group.revoke(user);
// }
// }
// teacherRole.setGroup(group);
// } else {
// throw new DomainException("no.default.role");
// }
//
// logger.info("Created site for execution course " + executionCourse.getSigla());
// return newSite;
// }
//
//
// public static void updateSiteSlug(ExecutionCourse instance) {
// instance.getSite().setSlug(ExecutionCourseSiteBuilder.formatSlugForExecutionCourse(instance));
// instance.setSiteUrl(instance.getSite().getFullUrl());
// }
//
// public static void updateProfessorship(Professorship professorship, Boolean allowAccess ) {
// ExecutionCourse executionCourse = professorship.getExecutionCourse();
//
// RoleTemplate defaultTemplate = executionCourse.getSite().getDefaultRoleTemplate();
// if (defaultTemplate != null ) {
// Role teacherRole = executionCourse.getSite().getRolesSet().stream()
// .filter(role -> role.getRoleTemplate().equals(defaultTemplate))
// .findAny().orElseGet(() -> new Role(defaultTemplate, executionCourse.getSite()));
//
// Group group = teacherRole.getGroup();
//
// User user = professorship.getPerson().getUser();
// if(allowAccess && !group.isMember(user)){
// group=group.grant(user);
// teacherRole.setGroup(group);
// } else if(group.isMember(user)) {
// group=group.revoke(user);
// teacherRole.setGroup(group);
// }
// } else {
// throw new DomainException("no.default.role");
// }
//
// }
// }
// Path: src/main/java/org/fenixedu/learning/ui/SpecificSitesAdmin.java
import org.fenixedu.academic.domain.Degree;
import org.fenixedu.academic.domain.ExecutionCourse;
import org.fenixedu.cms.domain.Site;
import org.fenixedu.cms.exceptions.CmsDomainException;
import org.fenixedu.learning.domain.degree.DegreeSiteListener;
import org.fenixedu.learning.domain.executionCourse.ExecutionCourseListener;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.RedirectView;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.net.URISyntaxException;
package org.fenixedu.learning.ui;
/**
* Created by diutsu on 27/09/16.
*/
@Controller
@RequestMapping("/learning/sites/")
public class SpecificSitesAdmin {
@RequestMapping(value = "/degree", method = RequestMethod.POST)
public RedirectView getDegreeSite(@RequestParam("dsigla") String degreeSigla) throws URISyntaxException {
Degree degree = Degree.readBySigla(degreeSigla);
if(degree==null){
throw CmsDomainException.notFound();
}
if(degree.getSite()!=null){
Site site = degree.getSite();
return new RedirectView(site.getEditUrl());
}
Site site = DegreeSiteListener.create(degree);
return new RedirectView(site.getEditUrl());
}
@RequestMapping(value = "/executionCourse", method = RequestMethod.POST)
public RedirectView getExecutionCourseSite(@RequestParam("ecsigla") String executionCourseSigla) throws URISyntaxException {
ExecutionCourse ec = ExecutionCourse.readLastBySigla(executionCourseSigla);
if(ec==null){
throw CmsDomainException.notFound();
}
if(ec.getSite()!=null){
Site site = ec.getSite();
return new RedirectView(site.getEditUrl());
}
|
Site site = ExecutionCourseListener.create(ec);
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/resource/GsonProviderTest.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/TabVO.java
// public class TabVO {
//
// private final Map<String, Object> valuesByKeys = new HashMap<String, Object>();
//
// /**
// * Maps the given {@code key} to the given {@code value}.
// *
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public TabVO add(final String key, final Object value) {
// valuesByKeys.put(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to object
// */
// public Map<String, Object> getValuesByKey() {
// return valuesByKeys;
// }
// }
|
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import com.codereligion.bugsnag.logback.model.TabVO;
import com.google.gson.TypeAdapter;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.resource;
public class GsonProviderTest {
private JsonFilterProvider jsonFilterProvider = mock(JsonFilterProvider.class);
private GsonProvider gsonProvider = new GsonProvider(jsonFilterProvider);
@Test
public void registersAdapterForMetaDataVO() {
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/TabVO.java
// public class TabVO {
//
// private final Map<String, Object> valuesByKeys = new HashMap<String, Object>();
//
// /**
// * Maps the given {@code key} to the given {@code value}.
// *
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public TabVO add(final String key, final Object value) {
// valuesByKeys.put(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to object
// */
// public Map<String, Object> getValuesByKey() {
// return valuesByKeys;
// }
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/resource/GsonProviderTest.java
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import com.codereligion.bugsnag.logback.model.TabVO;
import com.google.gson.TypeAdapter;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.resource;
public class GsonProviderTest {
private JsonFilterProvider jsonFilterProvider = mock(JsonFilterProvider.class);
private GsonProvider gsonProvider = new GsonProvider(jsonFilterProvider);
@Test
public void registersAdapterForMetaDataVO() {
|
final TypeAdapter<MetaDataVO> adapter = gsonProvider.getGson().getAdapter(MetaDataVO.class);
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/resource/GsonProviderTest.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/TabVO.java
// public class TabVO {
//
// private final Map<String, Object> valuesByKeys = new HashMap<String, Object>();
//
// /**
// * Maps the given {@code key} to the given {@code value}.
// *
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public TabVO add(final String key, final Object value) {
// valuesByKeys.put(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to object
// */
// public Map<String, Object> getValuesByKey() {
// return valuesByKeys;
// }
// }
|
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import com.codereligion.bugsnag.logback.model.TabVO;
import com.google.gson.TypeAdapter;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.resource;
public class GsonProviderTest {
private JsonFilterProvider jsonFilterProvider = mock(JsonFilterProvider.class);
private GsonProvider gsonProvider = new GsonProvider(jsonFilterProvider);
@Test
public void registersAdapterForMetaDataVO() {
final TypeAdapter<MetaDataVO> adapter = gsonProvider.getGson().getAdapter(MetaDataVO.class);
assertThat(adapter, is(notNullValue()));
}
@Test
public void registersAdapterForTabVO() {
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/TabVO.java
// public class TabVO {
//
// private final Map<String, Object> valuesByKeys = new HashMap<String, Object>();
//
// /**
// * Maps the given {@code key} to the given {@code value}.
// *
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public TabVO add(final String key, final Object value) {
// valuesByKeys.put(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to object
// */
// public Map<String, Object> getValuesByKey() {
// return valuesByKeys;
// }
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/resource/GsonProviderTest.java
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import com.codereligion.bugsnag.logback.model.TabVO;
import com.google.gson.TypeAdapter;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.resource;
public class GsonProviderTest {
private JsonFilterProvider jsonFilterProvider = mock(JsonFilterProvider.class);
private GsonProvider gsonProvider = new GsonProvider(jsonFilterProvider);
@Test
public void registersAdapterForMetaDataVO() {
final TypeAdapter<MetaDataVO> adapter = gsonProvider.getGson().getAdapter(MetaDataVO.class);
assertThat(adapter, is(notNullValue()));
}
@Test
public void registersAdapterForTabVO() {
|
final TypeAdapter<TabVO> adapter = gsonProvider.getGson().getAdapter(TabVO.class);
|
codereligion/bugsnag-logback
|
src/main/java/com/codereligion/bugsnag/logback/resource/GsonProvider.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/TabVO.java
// public class TabVO {
//
// private final Map<String, Object> valuesByKeys = new HashMap<String, Object>();
//
// /**
// * Maps the given {@code key} to the given {@code value}.
// *
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public TabVO add(final String key, final Object value) {
// valuesByKeys.put(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to object
// */
// public Map<String, Object> getValuesByKey() {
// return valuesByKeys;
// }
// }
|
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import com.codereligion.bugsnag.logback.model.TabVO;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.resource;
/**
* Provides a {@link Gson} instance to serializes data with.
*
* @author Sebastian Gröbler
*/
public class GsonProvider {
private final Gson gson;
/**
* Creates a new instance with the given {@code jsonFilterProvider}.
*
* @param jsonFilterProvider the {@link JsonFilterProvider} implementation to use
*/
public GsonProvider(final JsonFilterProvider jsonFilterProvider) {
this.gson = new GsonBuilder()
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/TabVO.java
// public class TabVO {
//
// private final Map<String, Object> valuesByKeys = new HashMap<String, Object>();
//
// /**
// * Maps the given {@code key} to the given {@code value}.
// *
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public TabVO add(final String key, final Object value) {
// valuesByKeys.put(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to object
// */
// public Map<String, Object> getValuesByKey() {
// return valuesByKeys;
// }
// }
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonProvider.java
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import com.codereligion.bugsnag.logback.model.TabVO;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.resource;
/**
* Provides a {@link Gson} instance to serializes data with.
*
* @author Sebastian Gröbler
*/
public class GsonProvider {
private final Gson gson;
/**
* Creates a new instance with the given {@code jsonFilterProvider}.
*
* @param jsonFilterProvider the {@link JsonFilterProvider} implementation to use
*/
public GsonProvider(final JsonFilterProvider jsonFilterProvider) {
this.gson = new GsonBuilder()
|
.registerTypeAdapter(MetaDataVO.class, new MetaDataVOSerializer())
|
codereligion/bugsnag-logback
|
src/main/java/com/codereligion/bugsnag/logback/resource/GsonProvider.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/TabVO.java
// public class TabVO {
//
// private final Map<String, Object> valuesByKeys = new HashMap<String, Object>();
//
// /**
// * Maps the given {@code key} to the given {@code value}.
// *
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public TabVO add(final String key, final Object value) {
// valuesByKeys.put(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to object
// */
// public Map<String, Object> getValuesByKey() {
// return valuesByKeys;
// }
// }
|
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import com.codereligion.bugsnag.logback.model.TabVO;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.resource;
/**
* Provides a {@link Gson} instance to serializes data with.
*
* @author Sebastian Gröbler
*/
public class GsonProvider {
private final Gson gson;
/**
* Creates a new instance with the given {@code jsonFilterProvider}.
*
* @param jsonFilterProvider the {@link JsonFilterProvider} implementation to use
*/
public GsonProvider(final JsonFilterProvider jsonFilterProvider) {
this.gson = new GsonBuilder()
.registerTypeAdapter(MetaDataVO.class, new MetaDataVOSerializer())
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/TabVO.java
// public class TabVO {
//
// private final Map<String, Object> valuesByKeys = new HashMap<String, Object>();
//
// /**
// * Maps the given {@code key} to the given {@code value}.
// *
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public TabVO add(final String key, final Object value) {
// valuesByKeys.put(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to object
// */
// public Map<String, Object> getValuesByKey() {
// return valuesByKeys;
// }
// }
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonProvider.java
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import com.codereligion.bugsnag.logback.model.TabVO;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.resource;
/**
* Provides a {@link Gson} instance to serializes data with.
*
* @author Sebastian Gröbler
*/
public class GsonProvider {
private final Gson gson;
/**
* Creates a new instance with the given {@code jsonFilterProvider}.
*
* @param jsonFilterProvider the {@link JsonFilterProvider} implementation to use
*/
public GsonProvider(final JsonFilterProvider jsonFilterProvider) {
this.gson = new GsonBuilder()
.registerTypeAdapter(MetaDataVO.class, new MetaDataVOSerializer())
|
.registerTypeAdapter(TabVO.class, new TabVOSerializer(jsonFilterProvider))
|
codereligion/bugsnag-logback
|
src/main/java/com/codereligion/bugsnag/logback/Appender.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
|
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
import java.util.Set;
|
@Override
public void start() {
if (configuration.isInvalid()) {
configuration.addErrors(this);
return;
}
sender.start(configuration, this);
super.start();
}
@Override
public void stop() {
if (!isStarted()) {
return;
}
sender.stop();
super.stop();
}
@Override
protected void append(final ILoggingEvent event) {
if (!isStarted() || configuration.isStageIgnored() || shouldNotNotifyFor(event)) {
return;
}
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
// Path: src/main/java/com/codereligion/bugsnag/logback/Appender.java
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
import java.util.Set;
@Override
public void start() {
if (configuration.isInvalid()) {
configuration.addErrors(this);
return;
}
sender.start(configuration, this);
super.start();
}
@Override
public void stop() {
if (!isStarted()) {
return;
}
sender.stop();
super.stop();
}
@Override
protected void append(final ILoggingEvent event) {
if (!isStarted() || configuration.isStageIgnored() || shouldNotNotifyFor(event)) {
return;
}
|
final NotificationVO notification = converter.convertToNotification(event);
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/mock/model/MockExceptionVO.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/ExceptionVO.java
// public class ExceptionVO {
//
// /**
// * The class of error that occurred.
// */
// private String errorClass;
//
// /**
// * The error message associated with the error.
// */
// private String message;
//
// /**
// * A list of stack trace objects. Each object represents one line in
// * the exception's stack trace. bugsnag uses this information to help
// * with error grouping, as well as displaying it to the user.
// */
// private List<StackTraceVO> stacktrace = Lists.newArrayList();
//
// public String getErrorClass() {
// return errorClass;
// }
//
// public void setErrorClass(final String errorClass) {
// this.errorClass = errorClass;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(final String message) {
// this.message = message;
// }
//
// public List<StackTraceVO> getStackTrace() {
// return stacktrace;
// }
//
// public void addStackTrace(final List<StackTraceVO> stackTrace) {
// this.stacktrace.addAll(stackTrace);
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/StackTraceVO.java
// public class StackTraceVO {
//
// /**
// * The file that this stack frame was executing.
// */
// private String file;
//
// /**
// * The line of the file that this frame of the stack was in.
// */
// private int lineNumber;
//
// /**
// * The method that this particular stack frame is within.
// */
// private String method;
//
// /**
// * True when this line is originated in the project's code.
// */
// private boolean inProject;
//
// public String getFile() {
// return file;
// }
//
// public void setFile(final String file) {
// this.file = file;
// }
//
// public int getLineNumber() {
// return lineNumber;
// }
//
// public void setLineNumber(final int lineNumber) {
// this.lineNumber = lineNumber;
// }
//
// public String getMethod() {
// return method;
// }
//
// public void setMethod(final String method) {
// this.method = method;
// }
//
// public boolean isInProject() {
// return inProject;
// }
//
// public void setInProject(final boolean inProject) {
// this.inProject = inProject;
// }
// }
|
import com.codereligion.bugsnag.logback.model.ExceptionVO;
import com.codereligion.bugsnag.logback.model.StackTraceVO;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.mock.model;
public class MockExceptionVO extends ExceptionVO {
public static MockExceptionVO createExceptionVO() {
return new MockExceptionVO();
}
public MockExceptionVO withErrorClass(final String errorClass) {
setErrorClass(errorClass);
return this;
}
public MockExceptionVO withMessage(final String message) {
setMessage(message);
return this;
}
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/ExceptionVO.java
// public class ExceptionVO {
//
// /**
// * The class of error that occurred.
// */
// private String errorClass;
//
// /**
// * The error message associated with the error.
// */
// private String message;
//
// /**
// * A list of stack trace objects. Each object represents one line in
// * the exception's stack trace. bugsnag uses this information to help
// * with error grouping, as well as displaying it to the user.
// */
// private List<StackTraceVO> stacktrace = Lists.newArrayList();
//
// public String getErrorClass() {
// return errorClass;
// }
//
// public void setErrorClass(final String errorClass) {
// this.errorClass = errorClass;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(final String message) {
// this.message = message;
// }
//
// public List<StackTraceVO> getStackTrace() {
// return stacktrace;
// }
//
// public void addStackTrace(final List<StackTraceVO> stackTrace) {
// this.stacktrace.addAll(stackTrace);
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/StackTraceVO.java
// public class StackTraceVO {
//
// /**
// * The file that this stack frame was executing.
// */
// private String file;
//
// /**
// * The line of the file that this frame of the stack was in.
// */
// private int lineNumber;
//
// /**
// * The method that this particular stack frame is within.
// */
// private String method;
//
// /**
// * True when this line is originated in the project's code.
// */
// private boolean inProject;
//
// public String getFile() {
// return file;
// }
//
// public void setFile(final String file) {
// this.file = file;
// }
//
// public int getLineNumber() {
// return lineNumber;
// }
//
// public void setLineNumber(final int lineNumber) {
// this.lineNumber = lineNumber;
// }
//
// public String getMethod() {
// return method;
// }
//
// public void setMethod(final String method) {
// this.method = method;
// }
//
// public boolean isInProject() {
// return inProject;
// }
//
// public void setInProject(final boolean inProject) {
// this.inProject = inProject;
// }
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/model/MockExceptionVO.java
import com.codereligion.bugsnag.logback.model.ExceptionVO;
import com.codereligion.bugsnag.logback.model.StackTraceVO;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.mock.model;
public class MockExceptionVO extends ExceptionVO {
public static MockExceptionVO createExceptionVO() {
return new MockExceptionVO();
}
public MockExceptionVO withErrorClass(final String errorClass) {
setErrorClass(errorClass);
return this;
}
public MockExceptionVO withMessage(final String message) {
setMessage(message);
return this;
}
|
public MockExceptionVO add(final StackTraceVO stackTraceVO) {
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/SenderTest.java
|
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/model/MockNotificationVO.java
// public static MockNotificationVO createNotificationVO() {
// return new MockNotificationVO();
// }
|
import ch.qos.logback.core.spi.ContextAware;
import org.junit.Test;
import static com.codereligion.bugsnag.logback.mock.model.MockNotificationVO.createNotificationVO;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback;
public class SenderTest {
private final Configuration configuration = spy(new Configuration());
private final ContextAware contextAware = mock(ContextAware.class);
private final Sender sender = new Sender();
@Test
public void isStartedAfterStart() {
sender.start(mock(Configuration.class), mock(ContextAware.class));
assertThat(sender.isStarted(), is(true));
}
@Test
public void isStoppedAfterStop() {
sender.start(mock(Configuration.class), mock(ContextAware.class));
sender.stop();
assertThat(sender.isStopped(), is(true));
}
@Test
public void doesNotSendWhenStopped() {
sender.start(configuration, contextAware);
sender.stop();
reset(configuration, contextAware);
|
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/model/MockNotificationVO.java
// public static MockNotificationVO createNotificationVO() {
// return new MockNotificationVO();
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/SenderTest.java
import ch.qos.logback.core.spi.ContextAware;
import org.junit.Test;
import static com.codereligion.bugsnag.logback.mock.model.MockNotificationVO.createNotificationVO;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback;
public class SenderTest {
private final Configuration configuration = spy(new Configuration());
private final ContextAware contextAware = mock(ContextAware.class);
private final Sender sender = new Sender();
@Test
public void isStartedAfterStart() {
sender.start(mock(Configuration.class), mock(ContextAware.class));
assertThat(sender.isStarted(), is(true));
}
@Test
public void isStoppedAfterStop() {
sender.start(mock(Configuration.class), mock(ContextAware.class));
sender.stop();
assertThat(sender.isStopped(), is(true));
}
@Test
public void doesNotSendWhenStopped() {
sender.start(configuration, contextAware);
sender.stop();
reset(configuration, contextAware);
|
sender.send(createNotificationVO());
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/model/TabVOTest.java
|
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/business/User.java
// public class User {
// private String email;
// private String password;
//
// public User(final String email, final String password) {
// this.email = email;
// this.password = password;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (email != null ? !email.equals(user.email) : user.email != null) return false;
// if (password != null ? !password.equals(user.password) : user.password != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = email != null ? email.hashCode() : 0;
// result = 31 * result + (password != null ? password.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "email='" + email + '\'' +
// ", password='" + password + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/TabVO.java
// public class TabVO {
//
// private final Map<String, Object> valuesByKeys = new HashMap<String, Object>();
//
// /**
// * Maps the given {@code key} to the given {@code value}.
// *
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public TabVO add(final String key, final Object value) {
// valuesByKeys.put(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to object
// */
// public Map<String, Object> getValuesByKey() {
// return valuesByKeys;
// }
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/matcher/TabKeyValueMatcher.java
// public static Matcher<TabVO> hasKeyValuePair(final String key, final Object value) {
// return new TabKeyValueMatcher(key, value);
// }
|
import com.codereligion.bugsnag.logback.mock.business.User;
import com.codereligion.bugsnag.logback.model.TabVO;
import org.junit.Test;
import static com.codereligion.bugsnag.logback.matcher.TabKeyValueMatcher.hasKeyValuePair;
import static org.hamcrest.MatcherAssert.assertThat;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.model;
public class TabVOTest {
@Test
public void allowsAddingOfKeyValuePairs() {
|
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/business/User.java
// public class User {
// private String email;
// private String password;
//
// public User(final String email, final String password) {
// this.email = email;
// this.password = password;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (email != null ? !email.equals(user.email) : user.email != null) return false;
// if (password != null ? !password.equals(user.password) : user.password != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = email != null ? email.hashCode() : 0;
// result = 31 * result + (password != null ? password.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "email='" + email + '\'' +
// ", password='" + password + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/TabVO.java
// public class TabVO {
//
// private final Map<String, Object> valuesByKeys = new HashMap<String, Object>();
//
// /**
// * Maps the given {@code key} to the given {@code value}.
// *
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public TabVO add(final String key, final Object value) {
// valuesByKeys.put(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to object
// */
// public Map<String, Object> getValuesByKey() {
// return valuesByKeys;
// }
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/matcher/TabKeyValueMatcher.java
// public static Matcher<TabVO> hasKeyValuePair(final String key, final Object value) {
// return new TabKeyValueMatcher(key, value);
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/model/TabVOTest.java
import com.codereligion.bugsnag.logback.mock.business.User;
import com.codereligion.bugsnag.logback.model.TabVO;
import org.junit.Test;
import static com.codereligion.bugsnag.logback.matcher.TabKeyValueMatcher.hasKeyValuePair;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.model;
public class TabVOTest {
@Test
public void allowsAddingOfKeyValuePairs() {
|
final TabVO tabVO = new TabVO();
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/model/TabVOTest.java
|
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/business/User.java
// public class User {
// private String email;
// private String password;
//
// public User(final String email, final String password) {
// this.email = email;
// this.password = password;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (email != null ? !email.equals(user.email) : user.email != null) return false;
// if (password != null ? !password.equals(user.password) : user.password != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = email != null ? email.hashCode() : 0;
// result = 31 * result + (password != null ? password.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "email='" + email + '\'' +
// ", password='" + password + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/TabVO.java
// public class TabVO {
//
// private final Map<String, Object> valuesByKeys = new HashMap<String, Object>();
//
// /**
// * Maps the given {@code key} to the given {@code value}.
// *
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public TabVO add(final String key, final Object value) {
// valuesByKeys.put(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to object
// */
// public Map<String, Object> getValuesByKey() {
// return valuesByKeys;
// }
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/matcher/TabKeyValueMatcher.java
// public static Matcher<TabVO> hasKeyValuePair(final String key, final Object value) {
// return new TabKeyValueMatcher(key, value);
// }
|
import com.codereligion.bugsnag.logback.mock.business.User;
import com.codereligion.bugsnag.logback.model.TabVO;
import org.junit.Test;
import static com.codereligion.bugsnag.logback.matcher.TabKeyValueMatcher.hasKeyValuePair;
import static org.hamcrest.MatcherAssert.assertThat;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.model;
public class TabVOTest {
@Test
public void allowsAddingOfKeyValuePairs() {
final TabVO tabVO = new TabVO();
tabVO.add("someKey", "someValue");
|
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/business/User.java
// public class User {
// private String email;
// private String password;
//
// public User(final String email, final String password) {
// this.email = email;
// this.password = password;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (email != null ? !email.equals(user.email) : user.email != null) return false;
// if (password != null ? !password.equals(user.password) : user.password != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = email != null ? email.hashCode() : 0;
// result = 31 * result + (password != null ? password.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "email='" + email + '\'' +
// ", password='" + password + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/TabVO.java
// public class TabVO {
//
// private final Map<String, Object> valuesByKeys = new HashMap<String, Object>();
//
// /**
// * Maps the given {@code key} to the given {@code value}.
// *
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public TabVO add(final String key, final Object value) {
// valuesByKeys.put(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to object
// */
// public Map<String, Object> getValuesByKey() {
// return valuesByKeys;
// }
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/matcher/TabKeyValueMatcher.java
// public static Matcher<TabVO> hasKeyValuePair(final String key, final Object value) {
// return new TabKeyValueMatcher(key, value);
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/model/TabVOTest.java
import com.codereligion.bugsnag.logback.mock.business.User;
import com.codereligion.bugsnag.logback.model.TabVO;
import org.junit.Test;
import static com.codereligion.bugsnag.logback.matcher.TabKeyValueMatcher.hasKeyValuePair;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.model;
public class TabVOTest {
@Test
public void allowsAddingOfKeyValuePairs() {
final TabVO tabVO = new TabVO();
tabVO.add("someKey", "someValue");
|
assertThat(tabVO, hasKeyValuePair("someKey", "someValue"));
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/model/TabVOTest.java
|
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/business/User.java
// public class User {
// private String email;
// private String password;
//
// public User(final String email, final String password) {
// this.email = email;
// this.password = password;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (email != null ? !email.equals(user.email) : user.email != null) return false;
// if (password != null ? !password.equals(user.password) : user.password != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = email != null ? email.hashCode() : 0;
// result = 31 * result + (password != null ? password.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "email='" + email + '\'' +
// ", password='" + password + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/TabVO.java
// public class TabVO {
//
// private final Map<String, Object> valuesByKeys = new HashMap<String, Object>();
//
// /**
// * Maps the given {@code key} to the given {@code value}.
// *
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public TabVO add(final String key, final Object value) {
// valuesByKeys.put(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to object
// */
// public Map<String, Object> getValuesByKey() {
// return valuesByKeys;
// }
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/matcher/TabKeyValueMatcher.java
// public static Matcher<TabVO> hasKeyValuePair(final String key, final Object value) {
// return new TabKeyValueMatcher(key, value);
// }
|
import com.codereligion.bugsnag.logback.mock.business.User;
import com.codereligion.bugsnag.logback.model.TabVO;
import org.junit.Test;
import static com.codereligion.bugsnag.logback.matcher.TabKeyValueMatcher.hasKeyValuePair;
import static org.hamcrest.MatcherAssert.assertThat;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.model;
public class TabVOTest {
@Test
public void allowsAddingOfKeyValuePairs() {
final TabVO tabVO = new TabVO();
tabVO.add("someKey", "someValue");
assertThat(tabVO, hasKeyValuePair("someKey", "someValue"));
}
@Test
public void allowsAddingComplexObjectsAsValues() {
final TabVO tabVO = new TabVO();
|
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/business/User.java
// public class User {
// private String email;
// private String password;
//
// public User(final String email, final String password) {
// this.email = email;
// this.password = password;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (email != null ? !email.equals(user.email) : user.email != null) return false;
// if (password != null ? !password.equals(user.password) : user.password != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = email != null ? email.hashCode() : 0;
// result = 31 * result + (password != null ? password.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "email='" + email + '\'' +
// ", password='" + password + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/TabVO.java
// public class TabVO {
//
// private final Map<String, Object> valuesByKeys = new HashMap<String, Object>();
//
// /**
// * Maps the given {@code key} to the given {@code value}.
// *
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public TabVO add(final String key, final Object value) {
// valuesByKeys.put(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to object
// */
// public Map<String, Object> getValuesByKey() {
// return valuesByKeys;
// }
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/matcher/TabKeyValueMatcher.java
// public static Matcher<TabVO> hasKeyValuePair(final String key, final Object value) {
// return new TabKeyValueMatcher(key, value);
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/model/TabVOTest.java
import com.codereligion.bugsnag.logback.mock.business.User;
import com.codereligion.bugsnag.logback.model.TabVO;
import org.junit.Test;
import static com.codereligion.bugsnag.logback.matcher.TabKeyValueMatcher.hasKeyValuePair;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.model;
public class TabVOTest {
@Test
public void allowsAddingOfKeyValuePairs() {
final TabVO tabVO = new TabVO();
tabVO.add("someKey", "someValue");
assertThat(tabVO, hasKeyValuePair("someKey", "someValue"));
}
@Test
public void allowsAddingComplexObjectsAsValues() {
final TabVO tabVO = new TabVO();
|
tabVO.add("someArray", new User("email", "password"));
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/ConfigurationTest.java
|
// Path: src/test/java/com/codereligion/bugsnag/logback/integration/CustomMetaDataProvider.java
// public class CustomMetaDataProvider implements MetaDataProvider {
//
// @Override
// public MetaDataVO provide(final ILoggingEvent loggingEvent) {
// final MetaDataVO metaDataVO = new MetaDataVO();
// metaDataVO.addToTab("Logging", "level", loggingEvent.getLevel().toString());
// metaDataVO.addToTab("Logging", "message", loggingEvent.getMessage());
// metaDataVO.addToTab("User", "password", loggingEvent.getMDCPropertyMap().get("password"));
// return metaDataVO;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
|
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.spi.ContextAware;
import com.codereligion.bugsnag.logback.integration.CustomMetaDataProvider;
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import com.google.common.collect.Sets;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.endsWith;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
|
public void isInvalidWhenMetaProviderClassIsPresentButNotLoadable() {
configuration.setApiKey("someKey");
configuration.setMetaDataProviderClassName("SomeRandomClassName");
assertThat(configuration.isInvalid(), is(true));
}
@Test
public void isInvalidWhenMetaDataProviderClassHasNoPublicConstructor() {
configuration.setApiKey("someKey");
configuration.setMetaDataProviderClassName(PrivateMetaDataProvider.class.getName());
assertThat(configuration.isInvalid(), is(true));
}
@Test
public void isInvalidWhenMetaDataProviderClassHasNoPublicDefaultConstructor() {
configuration.setApiKey("someKey");
configuration.setMetaDataProviderClassName(NoPublicDefaultConstructorMetaDataProvider.class.getName());
assertThat(configuration.isInvalid(), is(true));
}
@Test
public void isInvalidWhenMetaDataProviderClassDoesNotImplementMetaDataProvider() {
configuration.setApiKey("someKey");
configuration.setMetaDataProviderClassName(NoImplementationOfMetaDataProvider.class.getName());
assertThat(configuration.isInvalid(), is(true));
}
@Test
public void isValidWhenMetaProviderClassIsPresentAndLoadable() {
configuration.setApiKey("someKey");
|
// Path: src/test/java/com/codereligion/bugsnag/logback/integration/CustomMetaDataProvider.java
// public class CustomMetaDataProvider implements MetaDataProvider {
//
// @Override
// public MetaDataVO provide(final ILoggingEvent loggingEvent) {
// final MetaDataVO metaDataVO = new MetaDataVO();
// metaDataVO.addToTab("Logging", "level", loggingEvent.getLevel().toString());
// metaDataVO.addToTab("Logging", "message", loggingEvent.getMessage());
// metaDataVO.addToTab("User", "password", loggingEvent.getMDCPropertyMap().get("password"));
// return metaDataVO;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/ConfigurationTest.java
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.spi.ContextAware;
import com.codereligion.bugsnag.logback.integration.CustomMetaDataProvider;
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import com.google.common.collect.Sets;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.endsWith;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
public void isInvalidWhenMetaProviderClassIsPresentButNotLoadable() {
configuration.setApiKey("someKey");
configuration.setMetaDataProviderClassName("SomeRandomClassName");
assertThat(configuration.isInvalid(), is(true));
}
@Test
public void isInvalidWhenMetaDataProviderClassHasNoPublicConstructor() {
configuration.setApiKey("someKey");
configuration.setMetaDataProviderClassName(PrivateMetaDataProvider.class.getName());
assertThat(configuration.isInvalid(), is(true));
}
@Test
public void isInvalidWhenMetaDataProviderClassHasNoPublicDefaultConstructor() {
configuration.setApiKey("someKey");
configuration.setMetaDataProviderClassName(NoPublicDefaultConstructorMetaDataProvider.class.getName());
assertThat(configuration.isInvalid(), is(true));
}
@Test
public void isInvalidWhenMetaDataProviderClassDoesNotImplementMetaDataProvider() {
configuration.setApiKey("someKey");
configuration.setMetaDataProviderClassName(NoImplementationOfMetaDataProvider.class.getName());
assertThat(configuration.isInvalid(), is(true));
}
@Test
public void isValidWhenMetaProviderClassIsPresentAndLoadable() {
configuration.setApiKey("someKey");
|
configuration.setMetaDataProviderClassName(CustomMetaDataProvider.class.getCanonicalName());
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/ConfigurationTest.java
|
// Path: src/test/java/com/codereligion/bugsnag/logback/integration/CustomMetaDataProvider.java
// public class CustomMetaDataProvider implements MetaDataProvider {
//
// @Override
// public MetaDataVO provide(final ILoggingEvent loggingEvent) {
// final MetaDataVO metaDataVO = new MetaDataVO();
// metaDataVO.addToTab("Logging", "level", loggingEvent.getLevel().toString());
// metaDataVO.addToTab("Logging", "message", loggingEvent.getMessage());
// metaDataVO.addToTab("User", "password", loggingEvent.getMDCPropertyMap().get("password"));
// return metaDataVO;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
|
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.spi.ContextAware;
import com.codereligion.bugsnag.logback.integration.CustomMetaDataProvider;
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import com.google.common.collect.Sets;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.endsWith;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
|
@Test
public void shouldNotifyForNotIgnoredClass() {
configuration.setIgnoreClasses(Sets.newHashSet("some.ClassName"));
assertThat(configuration.shouldNotifyFor("some.OtherClassName"), is(true));
}
@Test
public void ignoresFilteredKeys() {
configuration.setFilters(Sets.newHashSet("password"));
assertThat(configuration.isIgnoredByFilter("password"), is(true));
}
@Test
public void doesNotIgnoreUnFilteredKeys() {
configuration.setFilters(Sets.newHashSet("password"));
assertThat(configuration.isIgnoredByFilter("otherSecretField"), is(false));
}
@Test
public void hasMetaDataProviderWhenConfigured() {
configuration.setMetaDataProviderClassName(CustomMetaDataProvider.class.getCanonicalName());
assertThat(configuration.hasMetaDataProvider(), is(true));
}
private static class PrivateMetaDataProvider implements MetaDataProvider {
@Override
|
// Path: src/test/java/com/codereligion/bugsnag/logback/integration/CustomMetaDataProvider.java
// public class CustomMetaDataProvider implements MetaDataProvider {
//
// @Override
// public MetaDataVO provide(final ILoggingEvent loggingEvent) {
// final MetaDataVO metaDataVO = new MetaDataVO();
// metaDataVO.addToTab("Logging", "level", loggingEvent.getLevel().toString());
// metaDataVO.addToTab("Logging", "message", loggingEvent.getMessage());
// metaDataVO.addToTab("User", "password", loggingEvent.getMDCPropertyMap().get("password"));
// return metaDataVO;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/ConfigurationTest.java
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.spi.ContextAware;
import com.codereligion.bugsnag.logback.integration.CustomMetaDataProvider;
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import com.google.common.collect.Sets;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.endsWith;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
@Test
public void shouldNotifyForNotIgnoredClass() {
configuration.setIgnoreClasses(Sets.newHashSet("some.ClassName"));
assertThat(configuration.shouldNotifyFor("some.OtherClassName"), is(true));
}
@Test
public void ignoresFilteredKeys() {
configuration.setFilters(Sets.newHashSet("password"));
assertThat(configuration.isIgnoredByFilter("password"), is(true));
}
@Test
public void doesNotIgnoreUnFilteredKeys() {
configuration.setFilters(Sets.newHashSet("password"));
assertThat(configuration.isIgnoredByFilter("otherSecretField"), is(false));
}
@Test
public void hasMetaDataProviderWhenConfigured() {
configuration.setMetaDataProviderClassName(CustomMetaDataProvider.class.getCanonicalName());
assertThat(configuration.hasMetaDataProvider(), is(true));
}
private static class PrivateMetaDataProvider implements MetaDataProvider {
@Override
|
public MetaDataVO provide(final ILoggingEvent loggingEvent) {
|
codereligion/bugsnag-logback
|
src/example/java/com/codereligion/bugsnag/logback/ExampleMetaDataProvider.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
|
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import java.util.Map;
|
package com.codereligion.bugsnag.logback;
public class ExampleMetaDataProvider implements MetaDataProvider {
@Override
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
// Path: src/example/java/com/codereligion/bugsnag/logback/ExampleMetaDataProvider.java
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import java.util.Map;
package com.codereligion.bugsnag.logback;
public class ExampleMetaDataProvider implements MetaDataProvider {
@Override
|
public MetaDataVO provide(ILoggingEvent loggingEvent) {
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/model/StackTraceVOTest.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/StackTraceVO.java
// public class StackTraceVO {
//
// /**
// * The file that this stack frame was executing.
// */
// private String file;
//
// /**
// * The line of the file that this frame of the stack was in.
// */
// private int lineNumber;
//
// /**
// * The method that this particular stack frame is within.
// */
// private String method;
//
// /**
// * True when this line is originated in the project's code.
// */
// private boolean inProject;
//
// public String getFile() {
// return file;
// }
//
// public void setFile(final String file) {
// this.file = file;
// }
//
// public int getLineNumber() {
// return lineNumber;
// }
//
// public void setLineNumber(final int lineNumber) {
// this.lineNumber = lineNumber;
// }
//
// public String getMethod() {
// return method;
// }
//
// public void setMethod(final String method) {
// this.method = method;
// }
//
// public boolean isInProject() {
// return inProject;
// }
//
// public void setInProject(final boolean inProject) {
// this.inProject = inProject;
// }
// }
|
import com.codereligion.bugsnag.logback.model.StackTraceVO;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.model;
public class StackTraceVOTest {
@Test
public void defaultsToNotInProject() {
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/StackTraceVO.java
// public class StackTraceVO {
//
// /**
// * The file that this stack frame was executing.
// */
// private String file;
//
// /**
// * The line of the file that this frame of the stack was in.
// */
// private int lineNumber;
//
// /**
// * The method that this particular stack frame is within.
// */
// private String method;
//
// /**
// * True when this line is originated in the project's code.
// */
// private boolean inProject;
//
// public String getFile() {
// return file;
// }
//
// public void setFile(final String file) {
// this.file = file;
// }
//
// public int getLineNumber() {
// return lineNumber;
// }
//
// public void setLineNumber(final int lineNumber) {
// this.lineNumber = lineNumber;
// }
//
// public String getMethod() {
// return method;
// }
//
// public void setMethod(final String method) {
// this.method = method;
// }
//
// public boolean isInProject() {
// return inProject;
// }
//
// public void setInProject(final boolean inProject) {
// this.inProject = inProject;
// }
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/model/StackTraceVOTest.java
import com.codereligion.bugsnag.logback.model.StackTraceVO;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.model;
public class StackTraceVOTest {
@Test
public void defaultsToNotInProject() {
|
assertThat(new StackTraceVO().isInProject(), is(false));
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/model/MetaDataVOTest.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/matcher/TabKeyValueMatcher.java
// public static Matcher<TabVO> hasKeyValuePair(final String key, final Object value) {
// return new TabKeyValueMatcher(key, value);
// }
|
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import org.junit.Test;
import static com.codereligion.bugsnag.logback.matcher.TabKeyValueMatcher.hasKeyValuePair;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.model;
public class MetaDataVOTest {
private final MetaDataVO metaData = new MetaDataVO();
@Test
public void canAddMultipleKeyValuePairsForTheSameTab() {
metaData.addToTab("User", "id", "someId");
metaData.addToTab("User", "email", "[email protected]");
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/matcher/TabKeyValueMatcher.java
// public static Matcher<TabVO> hasKeyValuePair(final String key, final Object value) {
// return new TabKeyValueMatcher(key, value);
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/model/MetaDataVOTest.java
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import org.junit.Test;
import static com.codereligion.bugsnag.logback.matcher.TabKeyValueMatcher.hasKeyValuePair;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.model;
public class MetaDataVOTest {
private final MetaDataVO metaData = new MetaDataVO();
@Test
public void canAddMultipleKeyValuePairsForTheSameTab() {
metaData.addToTab("User", "id", "someId");
metaData.addToTab("User", "email", "[email protected]");
|
assertThat(metaData.getTabsByName(), hasEntry(is("User"), hasKeyValuePair("id", "someId")));
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/model/NotificationVOTest.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
|
import com.codereligion.bugsnag.logback.model.NotificationVO;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.model;
public class NotificationVOTest {
@Test
public void doesNotHaveDefaultApiKey() {
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/model/NotificationVOTest.java
import com.codereligion.bugsnag.logback.model.NotificationVO;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.model;
public class NotificationVOTest {
@Test
public void doesNotHaveDefaultApiKey() {
|
assertThat(new NotificationVO().getApiKey(), is(nullValue()));
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/integration/CustomMetaDataProvider.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/MetaDataProvider.java
// public interface MetaDataProvider {
//
// /**
// * Provides an instance of {@link MetaDataVO}.
// *
// * @param loggingEvent implementation of {@link ILoggingEvent}, cannot be {@code null}
// * @return an instance of {@link MetaDataVO} or {@code null}
// */
// MetaDataVO provide(ILoggingEvent loggingEvent);
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
|
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.codereligion.bugsnag.logback.MetaDataProvider;
import com.codereligion.bugsnag.logback.model.MetaDataVO;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.integration;
public class CustomMetaDataProvider implements MetaDataProvider {
@Override
|
// Path: src/main/java/com/codereligion/bugsnag/logback/MetaDataProvider.java
// public interface MetaDataProvider {
//
// /**
// * Provides an instance of {@link MetaDataVO}.
// *
// * @param loggingEvent implementation of {@link ILoggingEvent}, cannot be {@code null}
// * @return an instance of {@link MetaDataVO} or {@code null}
// */
// MetaDataVO provide(ILoggingEvent loggingEvent);
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/integration/CustomMetaDataProvider.java
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.codereligion.bugsnag.logback.MetaDataProvider;
import com.codereligion.bugsnag.logback.model.MetaDataVO;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.integration;
public class CustomMetaDataProvider implements MetaDataProvider {
@Override
|
public MetaDataVO provide(final ILoggingEvent loggingEvent) {
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/AppenderTest.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/logging/MockLoggingEvent.java
// public static MockLoggingEvent createLoggingEvent() {
// return new MockLoggingEvent();
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/logging/MockThrowableProxy.java
// public static MockThrowableProxy createThrowableProxy() {
// return new MockThrowableProxy();
// }
|
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.google.common.collect.Sets;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static com.codereligion.bugsnag.logback.mock.logging.MockLoggingEvent.createLoggingEvent;
import static com.codereligion.bugsnag.logback.mock.logging.MockThrowableProxy.createThrowableProxy;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
|
appender.start();
verify(sender).start(configuration, appender);
}
@Test
public void doesNotStopWhenNotStarted() {
appender.stop();
verifyZeroInteractions(sender);
}
@Test
public void stopsSenderOnAppenderStop() {
// given
when(configuration.isInvalid()).thenReturn(Boolean.FALSE);
// when
appender.start();
appender.stop();
// then
verify(sender).stop();
assertThat(appender.isStarted(), is(Boolean.FALSE));
}
@Test
public void doesNotAppendWhenNotStarted() {
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/logging/MockLoggingEvent.java
// public static MockLoggingEvent createLoggingEvent() {
// return new MockLoggingEvent();
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/logging/MockThrowableProxy.java
// public static MockThrowableProxy createThrowableProxy() {
// return new MockThrowableProxy();
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/AppenderTest.java
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.google.common.collect.Sets;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static com.codereligion.bugsnag.logback.mock.logging.MockLoggingEvent.createLoggingEvent;
import static com.codereligion.bugsnag.logback.mock.logging.MockThrowableProxy.createThrowableProxy;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
appender.start();
verify(sender).start(configuration, appender);
}
@Test
public void doesNotStopWhenNotStarted() {
appender.stop();
verifyZeroInteractions(sender);
}
@Test
public void stopsSenderOnAppenderStop() {
// given
when(configuration.isInvalid()).thenReturn(Boolean.FALSE);
// when
appender.start();
appender.stop();
// then
verify(sender).stop();
assertThat(appender.isStarted(), is(Boolean.FALSE));
}
@Test
public void doesNotAppendWhenNotStarted() {
|
appender.append(createLoggingEvent().with(createThrowableProxy()));
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/AppenderTest.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/logging/MockLoggingEvent.java
// public static MockLoggingEvent createLoggingEvent() {
// return new MockLoggingEvent();
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/logging/MockThrowableProxy.java
// public static MockThrowableProxy createThrowableProxy() {
// return new MockThrowableProxy();
// }
|
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.google.common.collect.Sets;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static com.codereligion.bugsnag.logback.mock.logging.MockLoggingEvent.createLoggingEvent;
import static com.codereligion.bugsnag.logback.mock.logging.MockThrowableProxy.createThrowableProxy;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
|
appender.start();
verify(sender).start(configuration, appender);
}
@Test
public void doesNotStopWhenNotStarted() {
appender.stop();
verifyZeroInteractions(sender);
}
@Test
public void stopsSenderOnAppenderStop() {
// given
when(configuration.isInvalid()).thenReturn(Boolean.FALSE);
// when
appender.start();
appender.stop();
// then
verify(sender).stop();
assertThat(appender.isStarted(), is(Boolean.FALSE));
}
@Test
public void doesNotAppendWhenNotStarted() {
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/logging/MockLoggingEvent.java
// public static MockLoggingEvent createLoggingEvent() {
// return new MockLoggingEvent();
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/logging/MockThrowableProxy.java
// public static MockThrowableProxy createThrowableProxy() {
// return new MockThrowableProxy();
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/AppenderTest.java
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.google.common.collect.Sets;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static com.codereligion.bugsnag.logback.mock.logging.MockLoggingEvent.createLoggingEvent;
import static com.codereligion.bugsnag.logback.mock.logging.MockThrowableProxy.createThrowableProxy;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
appender.start();
verify(sender).start(configuration, appender);
}
@Test
public void doesNotStopWhenNotStarted() {
appender.stop();
verifyZeroInteractions(sender);
}
@Test
public void stopsSenderOnAppenderStop() {
// given
when(configuration.isInvalid()).thenReturn(Boolean.FALSE);
// when
appender.start();
appender.stop();
// then
verify(sender).stop();
assertThat(appender.isStarted(), is(Boolean.FALSE));
}
@Test
public void doesNotAppendWhenNotStarted() {
|
appender.append(createLoggingEvent().with(createThrowableProxy()));
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/AppenderTest.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/logging/MockLoggingEvent.java
// public static MockLoggingEvent createLoggingEvent() {
// return new MockLoggingEvent();
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/logging/MockThrowableProxy.java
// public static MockThrowableProxy createThrowableProxy() {
// return new MockThrowableProxy();
// }
|
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.google.common.collect.Sets;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static com.codereligion.bugsnag.logback.mock.logging.MockLoggingEvent.createLoggingEvent;
import static com.codereligion.bugsnag.logback.mock.logging.MockThrowableProxy.createThrowableProxy;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
|
when(configuration.isInvalid()).thenReturn(Boolean.FALSE);
// when
appender.start();
appender.stop();
// then
verify(sender).stop();
assertThat(appender.isStarted(), is(Boolean.FALSE));
}
@Test
public void doesNotAppendWhenNotStarted() {
appender.append(createLoggingEvent().with(createThrowableProxy()));
verifyZeroInteractions(sender);
}
@Test
public void doesNotAppendWhenStageIsIgnored() {
// given
when(configuration.isStageIgnored()).thenReturn(Boolean.TRUE);
// when
appender.start();
appender.append(createLoggingEvent().with(createThrowableProxy()));
// then
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/logging/MockLoggingEvent.java
// public static MockLoggingEvent createLoggingEvent() {
// return new MockLoggingEvent();
// }
//
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/logging/MockThrowableProxy.java
// public static MockThrowableProxy createThrowableProxy() {
// return new MockThrowableProxy();
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/AppenderTest.java
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.google.common.collect.Sets;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static com.codereligion.bugsnag.logback.mock.logging.MockLoggingEvent.createLoggingEvent;
import static com.codereligion.bugsnag.logback.mock.logging.MockThrowableProxy.createThrowableProxy;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
when(configuration.isInvalid()).thenReturn(Boolean.FALSE);
// when
appender.start();
appender.stop();
// then
verify(sender).stop();
assertThat(appender.isStarted(), is(Boolean.FALSE));
}
@Test
public void doesNotAppendWhenNotStarted() {
appender.append(createLoggingEvent().with(createThrowableProxy()));
verifyZeroInteractions(sender);
}
@Test
public void doesNotAppendWhenStageIsIgnored() {
// given
when(configuration.isStageIgnored()).thenReturn(Boolean.TRUE);
// when
appender.start();
appender.append(createLoggingEvent().with(createThrowableProxy()));
// then
|
verify(sender, never()).send(any(NotificationVO.class));
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/resource/MetaDataVOSerializerTest.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
|
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import com.google.gson.JsonSerializationContext;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.resource;
public class MetaDataVOSerializerTest {
private MetaDataVOSerializer serializer = new MetaDataVOSerializer();
@Test
public void directlySerializesTheInternalMap() {
// given
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/MetaDataVO.java
// public class MetaDataVO {
//
// private Map<String, TabVO> tabsByName = new HashMap<String, TabVO>();
//
// /**
// * Adds the given {@code key}/{@code value} pair to the specified {@code tabName}.
// *
// * @param tabName the name of the tab to add the key/value pair
// * @param key the key to map the {@code value} to
// * @param value the value for the given {@code key}
// * @return a reference of this object
// */
// public MetaDataVO addToTab(final String tabName, final String key, final Object value) {
// getAndEnsureTabExistence(tabName).add(key, value);
// return this;
// }
//
// /**
// * The underlying data structure of this object.
// *
// * @return a map of string to {@link TabVO}
// */
// public Map<String, TabVO> getTabsByName() {
// return tabsByName;
// }
//
// private TabVO getAndEnsureTabExistence(final String tabName) {
// final TabVO tab = tabsByName.get(tabName);
// final boolean tabDoesNotExist = tab == null;
// if (tabDoesNotExist) {
// final TabVO newTab = new TabVO();
// tabsByName.put(tabName, newTab);
// return newTab;
// }
//
// return tab;
// }
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/resource/MetaDataVOSerializerTest.java
import com.codereligion.bugsnag.logback.model.MetaDataVO;
import com.google.gson.JsonSerializationContext;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.resource;
public class MetaDataVOSerializerTest {
private MetaDataVOSerializer serializer = new MetaDataVOSerializer();
@Test
public void directlySerializesTheInternalMap() {
// given
|
final MetaDataVO metaData = new MetaDataVO();
|
codereligion/bugsnag-logback
|
src/main/java/com/codereligion/bugsnag/logback/Sender.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonMessageBodyWriter.java
// @Provider
// @Produces(MediaType.APPLICATION_JSON)
// public class GsonMessageBodyWriter implements MessageBodyWriter<Object> {
//
// private final Gson gson;
//
// /**
// * Creates a new instance using the given {@code gson} for serialization.
// * @param gson the {@link Gson} object to use
// */
// public GsonMessageBodyWriter(final Gson gson) {
// this.gson = gson;
// }
//
// @Override
// public boolean isWriteable(
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return true;
// }
//
// @Override
// public long getSize(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return -1;
// }
//
// @Override
// public void writeTo(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType,
// final MultivaluedMap<String, Object> httpHeaders,
// final OutputStream entityStream) throws IOException {
//
// final OutputStreamWriter writer = new OutputStreamWriter(entityStream, Charsets.UTF_8);
//
// try {
// gson.toJson(object, type, writer);
// } finally {
// writer.close();
// }
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonProvider.java
// public class GsonProvider {
//
// private final Gson gson;
//
// /**
// * Creates a new instance with the given {@code jsonFilterProvider}.
// *
// * @param jsonFilterProvider the {@link JsonFilterProvider} implementation to use
// */
// public GsonProvider(final JsonFilterProvider jsonFilterProvider) {
// this.gson = new GsonBuilder()
// .registerTypeAdapter(MetaDataVO.class, new MetaDataVOSerializer())
// .registerTypeAdapter(TabVO.class, new TabVOSerializer(jsonFilterProvider))
// .create();
// }
//
// /**
// * @return a fully configured {@link Gson} instance
// */
// public Gson getGson() {
// return gson;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/NotifierResource.java
// @Path("/")
// @Produces(MediaType.APPLICATION_JSON)
// public interface NotifierResource {
//
// @POST
// @Consumes(MediaType.APPLICATION_JSON)
// Response sendNotification(NotificationVO notificationVO);
// }
|
import ch.qos.logback.core.spi.ContextAware;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.codereligion.bugsnag.logback.resource.GsonMessageBodyWriter;
import com.codereligion.bugsnag.logback.resource.GsonProvider;
import com.codereligion.bugsnag.logback.resource.NotifierResource;
import com.google.gson.Gson;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback;
/**
* Sends {@link NotificationVO}s to the bugsnag endpoint.
*
* @author Sebastian Gröbler
*/
public class Sender {
/**
* All known and expected status codes of the bugsnag endpoint.
*/
public static final class StatusCode {
public static final int OK = 200;
public static final int BAD_REQUEST = 400;
public static final int UNAUTHORIZED = 401;
public static final int REQUEST_ENTITY_TOO_LARGE = 413;
public static final int TOO_MANY_REQUESTS = 429;
}
private String endpoint;
private ContextAware contextAware;
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonMessageBodyWriter.java
// @Provider
// @Produces(MediaType.APPLICATION_JSON)
// public class GsonMessageBodyWriter implements MessageBodyWriter<Object> {
//
// private final Gson gson;
//
// /**
// * Creates a new instance using the given {@code gson} for serialization.
// * @param gson the {@link Gson} object to use
// */
// public GsonMessageBodyWriter(final Gson gson) {
// this.gson = gson;
// }
//
// @Override
// public boolean isWriteable(
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return true;
// }
//
// @Override
// public long getSize(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return -1;
// }
//
// @Override
// public void writeTo(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType,
// final MultivaluedMap<String, Object> httpHeaders,
// final OutputStream entityStream) throws IOException {
//
// final OutputStreamWriter writer = new OutputStreamWriter(entityStream, Charsets.UTF_8);
//
// try {
// gson.toJson(object, type, writer);
// } finally {
// writer.close();
// }
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonProvider.java
// public class GsonProvider {
//
// private final Gson gson;
//
// /**
// * Creates a new instance with the given {@code jsonFilterProvider}.
// *
// * @param jsonFilterProvider the {@link JsonFilterProvider} implementation to use
// */
// public GsonProvider(final JsonFilterProvider jsonFilterProvider) {
// this.gson = new GsonBuilder()
// .registerTypeAdapter(MetaDataVO.class, new MetaDataVOSerializer())
// .registerTypeAdapter(TabVO.class, new TabVOSerializer(jsonFilterProvider))
// .create();
// }
//
// /**
// * @return a fully configured {@link Gson} instance
// */
// public Gson getGson() {
// return gson;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/NotifierResource.java
// @Path("/")
// @Produces(MediaType.APPLICATION_JSON)
// public interface NotifierResource {
//
// @POST
// @Consumes(MediaType.APPLICATION_JSON)
// Response sendNotification(NotificationVO notificationVO);
// }
// Path: src/main/java/com/codereligion/bugsnag/logback/Sender.java
import ch.qos.logback.core.spi.ContextAware;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.codereligion.bugsnag.logback.resource.GsonMessageBodyWriter;
import com.codereligion.bugsnag.logback.resource.GsonProvider;
import com.codereligion.bugsnag.logback.resource.NotifierResource;
import com.google.gson.Gson;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback;
/**
* Sends {@link NotificationVO}s to the bugsnag endpoint.
*
* @author Sebastian Gröbler
*/
public class Sender {
/**
* All known and expected status codes of the bugsnag endpoint.
*/
public static final class StatusCode {
public static final int OK = 200;
public static final int BAD_REQUEST = 400;
public static final int UNAUTHORIZED = 401;
public static final int REQUEST_ENTITY_TOO_LARGE = 413;
public static final int TOO_MANY_REQUESTS = 429;
}
private String endpoint;
private ContextAware contextAware;
|
private GsonProvider gsonProvider;
|
codereligion/bugsnag-logback
|
src/main/java/com/codereligion/bugsnag/logback/Sender.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonMessageBodyWriter.java
// @Provider
// @Produces(MediaType.APPLICATION_JSON)
// public class GsonMessageBodyWriter implements MessageBodyWriter<Object> {
//
// private final Gson gson;
//
// /**
// * Creates a new instance using the given {@code gson} for serialization.
// * @param gson the {@link Gson} object to use
// */
// public GsonMessageBodyWriter(final Gson gson) {
// this.gson = gson;
// }
//
// @Override
// public boolean isWriteable(
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return true;
// }
//
// @Override
// public long getSize(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return -1;
// }
//
// @Override
// public void writeTo(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType,
// final MultivaluedMap<String, Object> httpHeaders,
// final OutputStream entityStream) throws IOException {
//
// final OutputStreamWriter writer = new OutputStreamWriter(entityStream, Charsets.UTF_8);
//
// try {
// gson.toJson(object, type, writer);
// } finally {
// writer.close();
// }
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonProvider.java
// public class GsonProvider {
//
// private final Gson gson;
//
// /**
// * Creates a new instance with the given {@code jsonFilterProvider}.
// *
// * @param jsonFilterProvider the {@link JsonFilterProvider} implementation to use
// */
// public GsonProvider(final JsonFilterProvider jsonFilterProvider) {
// this.gson = new GsonBuilder()
// .registerTypeAdapter(MetaDataVO.class, new MetaDataVOSerializer())
// .registerTypeAdapter(TabVO.class, new TabVOSerializer(jsonFilterProvider))
// .create();
// }
//
// /**
// * @return a fully configured {@link Gson} instance
// */
// public Gson getGson() {
// return gson;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/NotifierResource.java
// @Path("/")
// @Produces(MediaType.APPLICATION_JSON)
// public interface NotifierResource {
//
// @POST
// @Consumes(MediaType.APPLICATION_JSON)
// Response sendNotification(NotificationVO notificationVO);
// }
|
import ch.qos.logback.core.spi.ContextAware;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.codereligion.bugsnag.logback.resource.GsonMessageBodyWriter;
import com.codereligion.bugsnag.logback.resource.GsonProvider;
import com.codereligion.bugsnag.logback.resource.NotifierResource;
import com.google.gson.Gson;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
|
this.started = true;
}
/**
* @return true when this sender was started
*/
public boolean isStarted() {
return started;
}
/**
* Stops this sender and closes all current connections/streams.
*/
public void stop() {
client.close();
this.started = false;
}
/**
* @return true when this sender was not yet started or was stopped
*/
public boolean isStopped() {
return !isStarted();
}
/**
* Sends the given {@code notification}, but no-ops when the sender was not yet started.
*
* @param notification the {@link NotificationVO} to send
*/
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonMessageBodyWriter.java
// @Provider
// @Produces(MediaType.APPLICATION_JSON)
// public class GsonMessageBodyWriter implements MessageBodyWriter<Object> {
//
// private final Gson gson;
//
// /**
// * Creates a new instance using the given {@code gson} for serialization.
// * @param gson the {@link Gson} object to use
// */
// public GsonMessageBodyWriter(final Gson gson) {
// this.gson = gson;
// }
//
// @Override
// public boolean isWriteable(
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return true;
// }
//
// @Override
// public long getSize(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return -1;
// }
//
// @Override
// public void writeTo(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType,
// final MultivaluedMap<String, Object> httpHeaders,
// final OutputStream entityStream) throws IOException {
//
// final OutputStreamWriter writer = new OutputStreamWriter(entityStream, Charsets.UTF_8);
//
// try {
// gson.toJson(object, type, writer);
// } finally {
// writer.close();
// }
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonProvider.java
// public class GsonProvider {
//
// private final Gson gson;
//
// /**
// * Creates a new instance with the given {@code jsonFilterProvider}.
// *
// * @param jsonFilterProvider the {@link JsonFilterProvider} implementation to use
// */
// public GsonProvider(final JsonFilterProvider jsonFilterProvider) {
// this.gson = new GsonBuilder()
// .registerTypeAdapter(MetaDataVO.class, new MetaDataVOSerializer())
// .registerTypeAdapter(TabVO.class, new TabVOSerializer(jsonFilterProvider))
// .create();
// }
//
// /**
// * @return a fully configured {@link Gson} instance
// */
// public Gson getGson() {
// return gson;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/NotifierResource.java
// @Path("/")
// @Produces(MediaType.APPLICATION_JSON)
// public interface NotifierResource {
//
// @POST
// @Consumes(MediaType.APPLICATION_JSON)
// Response sendNotification(NotificationVO notificationVO);
// }
// Path: src/main/java/com/codereligion/bugsnag/logback/Sender.java
import ch.qos.logback.core.spi.ContextAware;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.codereligion.bugsnag.logback.resource.GsonMessageBodyWriter;
import com.codereligion.bugsnag.logback.resource.GsonProvider;
import com.codereligion.bugsnag.logback.resource.NotifierResource;
import com.google.gson.Gson;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
this.started = true;
}
/**
* @return true when this sender was started
*/
public boolean isStarted() {
return started;
}
/**
* Stops this sender and closes all current connections/streams.
*/
public void stop() {
client.close();
this.started = false;
}
/**
* @return true when this sender was not yet started or was stopped
*/
public boolean isStopped() {
return !isStarted();
}
/**
* Sends the given {@code notification}, but no-ops when the sender was not yet started.
*
* @param notification the {@link NotificationVO} to send
*/
|
public void send(final NotificationVO notification) {
|
codereligion/bugsnag-logback
|
src/main/java/com/codereligion/bugsnag/logback/Sender.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonMessageBodyWriter.java
// @Provider
// @Produces(MediaType.APPLICATION_JSON)
// public class GsonMessageBodyWriter implements MessageBodyWriter<Object> {
//
// private final Gson gson;
//
// /**
// * Creates a new instance using the given {@code gson} for serialization.
// * @param gson the {@link Gson} object to use
// */
// public GsonMessageBodyWriter(final Gson gson) {
// this.gson = gson;
// }
//
// @Override
// public boolean isWriteable(
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return true;
// }
//
// @Override
// public long getSize(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return -1;
// }
//
// @Override
// public void writeTo(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType,
// final MultivaluedMap<String, Object> httpHeaders,
// final OutputStream entityStream) throws IOException {
//
// final OutputStreamWriter writer = new OutputStreamWriter(entityStream, Charsets.UTF_8);
//
// try {
// gson.toJson(object, type, writer);
// } finally {
// writer.close();
// }
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonProvider.java
// public class GsonProvider {
//
// private final Gson gson;
//
// /**
// * Creates a new instance with the given {@code jsonFilterProvider}.
// *
// * @param jsonFilterProvider the {@link JsonFilterProvider} implementation to use
// */
// public GsonProvider(final JsonFilterProvider jsonFilterProvider) {
// this.gson = new GsonBuilder()
// .registerTypeAdapter(MetaDataVO.class, new MetaDataVOSerializer())
// .registerTypeAdapter(TabVO.class, new TabVOSerializer(jsonFilterProvider))
// .create();
// }
//
// /**
// * @return a fully configured {@link Gson} instance
// */
// public Gson getGson() {
// return gson;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/NotifierResource.java
// @Path("/")
// @Produces(MediaType.APPLICATION_JSON)
// public interface NotifierResource {
//
// @POST
// @Consumes(MediaType.APPLICATION_JSON)
// Response sendNotification(NotificationVO notificationVO);
// }
|
import ch.qos.logback.core.spi.ContextAware;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.codereligion.bugsnag.logback.resource.GsonMessageBodyWriter;
import com.codereligion.bugsnag.logback.resource.GsonProvider;
import com.codereligion.bugsnag.logback.resource.NotifierResource;
import com.google.gson.Gson;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
|
/**
* Stops this sender and closes all current connections/streams.
*/
public void stop() {
client.close();
this.started = false;
}
/**
* @return true when this sender was not yet started or was stopped
*/
public boolean isStopped() {
return !isStarted();
}
/**
* Sends the given {@code notification}, but no-ops when the sender was not yet started.
*
* @param notification the {@link NotificationVO} to send
*/
public void send(final NotificationVO notification) {
if (isStopped()) {
return;
}
Response response = null;
try {
final ResteasyWebTarget resteasyWebTarget = (ResteasyWebTarget) client.target(endpoint);
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonMessageBodyWriter.java
// @Provider
// @Produces(MediaType.APPLICATION_JSON)
// public class GsonMessageBodyWriter implements MessageBodyWriter<Object> {
//
// private final Gson gson;
//
// /**
// * Creates a new instance using the given {@code gson} for serialization.
// * @param gson the {@link Gson} object to use
// */
// public GsonMessageBodyWriter(final Gson gson) {
// this.gson = gson;
// }
//
// @Override
// public boolean isWriteable(
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return true;
// }
//
// @Override
// public long getSize(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return -1;
// }
//
// @Override
// public void writeTo(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType,
// final MultivaluedMap<String, Object> httpHeaders,
// final OutputStream entityStream) throws IOException {
//
// final OutputStreamWriter writer = new OutputStreamWriter(entityStream, Charsets.UTF_8);
//
// try {
// gson.toJson(object, type, writer);
// } finally {
// writer.close();
// }
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonProvider.java
// public class GsonProvider {
//
// private final Gson gson;
//
// /**
// * Creates a new instance with the given {@code jsonFilterProvider}.
// *
// * @param jsonFilterProvider the {@link JsonFilterProvider} implementation to use
// */
// public GsonProvider(final JsonFilterProvider jsonFilterProvider) {
// this.gson = new GsonBuilder()
// .registerTypeAdapter(MetaDataVO.class, new MetaDataVOSerializer())
// .registerTypeAdapter(TabVO.class, new TabVOSerializer(jsonFilterProvider))
// .create();
// }
//
// /**
// * @return a fully configured {@link Gson} instance
// */
// public Gson getGson() {
// return gson;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/NotifierResource.java
// @Path("/")
// @Produces(MediaType.APPLICATION_JSON)
// public interface NotifierResource {
//
// @POST
// @Consumes(MediaType.APPLICATION_JSON)
// Response sendNotification(NotificationVO notificationVO);
// }
// Path: src/main/java/com/codereligion/bugsnag/logback/Sender.java
import ch.qos.logback.core.spi.ContextAware;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.codereligion.bugsnag.logback.resource.GsonMessageBodyWriter;
import com.codereligion.bugsnag.logback.resource.GsonProvider;
import com.codereligion.bugsnag.logback.resource.NotifierResource;
import com.google.gson.Gson;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
/**
* Stops this sender and closes all current connections/streams.
*/
public void stop() {
client.close();
this.started = false;
}
/**
* @return true when this sender was not yet started or was stopped
*/
public boolean isStopped() {
return !isStarted();
}
/**
* Sends the given {@code notification}, but no-ops when the sender was not yet started.
*
* @param notification the {@link NotificationVO} to send
*/
public void send(final NotificationVO notification) {
if (isStopped()) {
return;
}
Response response = null;
try {
final ResteasyWebTarget resteasyWebTarget = (ResteasyWebTarget) client.target(endpoint);
|
final NotifierResource notifierResource= resteasyWebTarget.proxy(NotifierResource.class);
|
codereligion/bugsnag-logback
|
src/main/java/com/codereligion/bugsnag/logback/Sender.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonMessageBodyWriter.java
// @Provider
// @Produces(MediaType.APPLICATION_JSON)
// public class GsonMessageBodyWriter implements MessageBodyWriter<Object> {
//
// private final Gson gson;
//
// /**
// * Creates a new instance using the given {@code gson} for serialization.
// * @param gson the {@link Gson} object to use
// */
// public GsonMessageBodyWriter(final Gson gson) {
// this.gson = gson;
// }
//
// @Override
// public boolean isWriteable(
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return true;
// }
//
// @Override
// public long getSize(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return -1;
// }
//
// @Override
// public void writeTo(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType,
// final MultivaluedMap<String, Object> httpHeaders,
// final OutputStream entityStream) throws IOException {
//
// final OutputStreamWriter writer = new OutputStreamWriter(entityStream, Charsets.UTF_8);
//
// try {
// gson.toJson(object, type, writer);
// } finally {
// writer.close();
// }
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonProvider.java
// public class GsonProvider {
//
// private final Gson gson;
//
// /**
// * Creates a new instance with the given {@code jsonFilterProvider}.
// *
// * @param jsonFilterProvider the {@link JsonFilterProvider} implementation to use
// */
// public GsonProvider(final JsonFilterProvider jsonFilterProvider) {
// this.gson = new GsonBuilder()
// .registerTypeAdapter(MetaDataVO.class, new MetaDataVOSerializer())
// .registerTypeAdapter(TabVO.class, new TabVOSerializer(jsonFilterProvider))
// .create();
// }
//
// /**
// * @return a fully configured {@link Gson} instance
// */
// public Gson getGson() {
// return gson;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/NotifierResource.java
// @Path("/")
// @Produces(MediaType.APPLICATION_JSON)
// public interface NotifierResource {
//
// @POST
// @Consumes(MediaType.APPLICATION_JSON)
// Response sendNotification(NotificationVO notificationVO);
// }
|
import ch.qos.logback.core.spi.ContextAware;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.codereligion.bugsnag.logback.resource.GsonMessageBodyWriter;
import com.codereligion.bugsnag.logback.resource.GsonProvider;
import com.codereligion.bugsnag.logback.resource.NotifierResource;
import com.google.gson.Gson;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
|
if (isOk) {
contextAware.addInfo("Successfully delivered notification to bugsnag.");
} else if (isExpectedErrorCode(statusCode)) {
contextAware.addError("Could not deliver notification to bugsnag, got http status code: " + statusCode);
} else {
contextAware.addError("Unexpected http status code: " + statusCode);
}
} catch (final Throwable throwable) {
contextAware.addError("Could not deliver notification, unexpected exception occurred.", throwable);
}
if (response != null) {
response.close();
}
}
private boolean isExpectedErrorCode(final int statusCode) {
return statusCode == StatusCode.BAD_REQUEST ||
statusCode == StatusCode.UNAUTHORIZED ||
statusCode == StatusCode.REQUEST_ENTITY_TOO_LARGE ||
statusCode == StatusCode.TOO_MANY_REQUESTS;
}
private Client createClient() {
final Gson gson = gsonProvider.getGson();
return ClientBuilder
.newClient()
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonMessageBodyWriter.java
// @Provider
// @Produces(MediaType.APPLICATION_JSON)
// public class GsonMessageBodyWriter implements MessageBodyWriter<Object> {
//
// private final Gson gson;
//
// /**
// * Creates a new instance using the given {@code gson} for serialization.
// * @param gson the {@link Gson} object to use
// */
// public GsonMessageBodyWriter(final Gson gson) {
// this.gson = gson;
// }
//
// @Override
// public boolean isWriteable(
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return true;
// }
//
// @Override
// public long getSize(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType) {
// return -1;
// }
//
// @Override
// public void writeTo(
// final Object object,
// final Class<?> type,
// final Type genericType,
// final Annotation[] annotations,
// final MediaType mediaType,
// final MultivaluedMap<String, Object> httpHeaders,
// final OutputStream entityStream) throws IOException {
//
// final OutputStreamWriter writer = new OutputStreamWriter(entityStream, Charsets.UTF_8);
//
// try {
// gson.toJson(object, type, writer);
// } finally {
// writer.close();
// }
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/GsonProvider.java
// public class GsonProvider {
//
// private final Gson gson;
//
// /**
// * Creates a new instance with the given {@code jsonFilterProvider}.
// *
// * @param jsonFilterProvider the {@link JsonFilterProvider} implementation to use
// */
// public GsonProvider(final JsonFilterProvider jsonFilterProvider) {
// this.gson = new GsonBuilder()
// .registerTypeAdapter(MetaDataVO.class, new MetaDataVOSerializer())
// .registerTypeAdapter(TabVO.class, new TabVOSerializer(jsonFilterProvider))
// .create();
// }
//
// /**
// * @return a fully configured {@link Gson} instance
// */
// public Gson getGson() {
// return gson;
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/NotifierResource.java
// @Path("/")
// @Produces(MediaType.APPLICATION_JSON)
// public interface NotifierResource {
//
// @POST
// @Consumes(MediaType.APPLICATION_JSON)
// Response sendNotification(NotificationVO notificationVO);
// }
// Path: src/main/java/com/codereligion/bugsnag/logback/Sender.java
import ch.qos.logback.core.spi.ContextAware;
import com.codereligion.bugsnag.logback.model.NotificationVO;
import com.codereligion.bugsnag.logback.resource.GsonMessageBodyWriter;
import com.codereligion.bugsnag.logback.resource.GsonProvider;
import com.codereligion.bugsnag.logback.resource.NotifierResource;
import com.google.gson.Gson;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
if (isOk) {
contextAware.addInfo("Successfully delivered notification to bugsnag.");
} else if (isExpectedErrorCode(statusCode)) {
contextAware.addError("Could not deliver notification to bugsnag, got http status code: " + statusCode);
} else {
contextAware.addError("Unexpected http status code: " + statusCode);
}
} catch (final Throwable throwable) {
contextAware.addError("Could not deliver notification, unexpected exception occurred.", throwable);
}
if (response != null) {
response.close();
}
}
private boolean isExpectedErrorCode(final int statusCode) {
return statusCode == StatusCode.BAD_REQUEST ||
statusCode == StatusCode.UNAUTHORIZED ||
statusCode == StatusCode.REQUEST_ENTITY_TOO_LARGE ||
statusCode == StatusCode.TOO_MANY_REQUESTS;
}
private Client createClient() {
final Gson gson = gsonProvider.getGson();
return ClientBuilder
.newClient()
|
.register(new GsonMessageBodyWriter(gson));
|
codereligion/bugsnag-logback
|
src/test/java/com/codereligion/bugsnag/logback/mock/model/MockNotificationVO.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/EventVO.java
// public class EventVO {
//
// /**
// * A unique identifier for a user affected by this event.
// */
// private String userId;
//
// /**
// * The version number of the application which generated the error.
// */
// private String appVersion;
//
// /**
// * The operating system version of the client that the error was
// * generated on.
// */
// private String osVersion;
//
// /**
// * The release stage that this error occurred in.
// */
// private String releaseStage;
//
// /**
// * A string representing what was happening in the application at the
// * time of the error. This string could be used for grouping purposes,
// * depending on the event.
// */
// private String context;
//
// /**
// * All errors with the same groupingHash will be grouped together within
// * the bugsnag dashboard.
// */
// private String groupingHash;
//
// /**
// * An object containing any further data which should be attached to this event.
// */
// private MetaDataVO metaData;
//
// /**
// * A list representation of the nested exceptions contained by the causing logging event.
// */
// private List<ExceptionVO> exceptions = Lists.newArrayList();
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(final String userId) {
// this.userId = userId;
// }
//
// public String getAppVersion() {
// return appVersion;
// }
//
// public void setAppVersion(final String appVersion) {
// this.appVersion = appVersion;
// }
//
// public String getOsVersion() {
// return osVersion;
// }
//
// public void setOsVersion(final String osVersion) {
// this.osVersion = osVersion;
// }
//
// public String getReleaseStage() {
// return releaseStage;
// }
//
// public void setReleaseStage(final String releaseStage) {
// this.releaseStage = releaseStage;
// }
//
// public String getContext() {
// return context;
// }
//
// public void setContext(final String context) {
// this.context = context;
// }
//
// public String getGroupingHash() {
// return groupingHash;
// }
//
// public void setGroupingHash(final String groupingHash) {
// this.groupingHash = groupingHash;
// }
//
// public MetaDataVO getMetaData() {
// return metaData;
// }
//
// public void setMetaData(final MetaDataVO metaData) {
// this.metaData = metaData;
// }
//
// public List<ExceptionVO> getExceptions() {
// return exceptions;
// }
//
// public void addExceptions(final List<ExceptionVO> exceptions) {
// this.exceptions.addAll(exceptions);
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
|
import com.codereligion.bugsnag.logback.model.EventVO;
import com.codereligion.bugsnag.logback.model.NotificationVO;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.mock.model;
public class MockNotificationVO extends NotificationVO {
public static MockNotificationVO createNotificationVO() {
return new MockNotificationVO();
}
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/EventVO.java
// public class EventVO {
//
// /**
// * A unique identifier for a user affected by this event.
// */
// private String userId;
//
// /**
// * The version number of the application which generated the error.
// */
// private String appVersion;
//
// /**
// * The operating system version of the client that the error was
// * generated on.
// */
// private String osVersion;
//
// /**
// * The release stage that this error occurred in.
// */
// private String releaseStage;
//
// /**
// * A string representing what was happening in the application at the
// * time of the error. This string could be used for grouping purposes,
// * depending on the event.
// */
// private String context;
//
// /**
// * All errors with the same groupingHash will be grouped together within
// * the bugsnag dashboard.
// */
// private String groupingHash;
//
// /**
// * An object containing any further data which should be attached to this event.
// */
// private MetaDataVO metaData;
//
// /**
// * A list representation of the nested exceptions contained by the causing logging event.
// */
// private List<ExceptionVO> exceptions = Lists.newArrayList();
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(final String userId) {
// this.userId = userId;
// }
//
// public String getAppVersion() {
// return appVersion;
// }
//
// public void setAppVersion(final String appVersion) {
// this.appVersion = appVersion;
// }
//
// public String getOsVersion() {
// return osVersion;
// }
//
// public void setOsVersion(final String osVersion) {
// this.osVersion = osVersion;
// }
//
// public String getReleaseStage() {
// return releaseStage;
// }
//
// public void setReleaseStage(final String releaseStage) {
// this.releaseStage = releaseStage;
// }
//
// public String getContext() {
// return context;
// }
//
// public void setContext(final String context) {
// this.context = context;
// }
//
// public String getGroupingHash() {
// return groupingHash;
// }
//
// public void setGroupingHash(final String groupingHash) {
// this.groupingHash = groupingHash;
// }
//
// public MetaDataVO getMetaData() {
// return metaData;
// }
//
// public void setMetaData(final MetaDataVO metaData) {
// this.metaData = metaData;
// }
//
// public List<ExceptionVO> getExceptions() {
// return exceptions;
// }
//
// public void addExceptions(final List<ExceptionVO> exceptions) {
// this.exceptions.addAll(exceptions);
// }
// }
//
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
// Path: src/test/java/com/codereligion/bugsnag/logback/mock/model/MockNotificationVO.java
import com.codereligion.bugsnag.logback.model.EventVO;
import com.codereligion.bugsnag.logback.model.NotificationVO;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.mock.model;
public class MockNotificationVO extends NotificationVO {
public static MockNotificationVO createNotificationVO() {
return new MockNotificationVO();
}
|
public MockNotificationVO add(final EventVO eventVO) {
|
codereligion/bugsnag-logback
|
src/main/java/com/codereligion/bugsnag/logback/resource/NotifierResource.java
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
|
import com.codereligion.bugsnag.logback.model.NotificationVO;
import javax.ws.rs.Consumes;
import javax.ws.rs .POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
|
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.resource;
/**
* The specification of the bugsnag endpoint.
*
* @author Sebastian Gröbler
*/
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public interface NotifierResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
|
// Path: src/main/java/com/codereligion/bugsnag/logback/model/NotificationVO.java
// public class NotificationVO {
//
// /**
// * The api key associated with the project. Informs bugsnag which project has generated this error.
// */
// private String apiKey;
//
// /**
// * This object describes the notifier itself. These properties are used
// * within bugsnag to track error rates from a notifier.
// */
// private NotifierVO notifier = new NotifierVO();
//
// /**
// * A list of error events that bugsnag should be notified of. In the current version of his notifier
// * the list will contain only one event.
// */
// private List<EventVO> events = Lists.newArrayList();
//
// public String getApiKey() {
// return apiKey;
// }
//
// public void setApiKey(final String apiKey) {
// this.apiKey = apiKey;
// }
//
// public List<EventVO> getEvents() {
// return events;
// }
//
// public void addEvents(final List<EventVO> events) {
// this.events.addAll(events);
// }
//
// public NotifierVO getNotifier() {
// return notifier;
// }
// }
// Path: src/main/java/com/codereligion/bugsnag/logback/resource/NotifierResource.java
import com.codereligion.bugsnag.logback.model.NotificationVO;
import javax.ws.rs.Consumes;
import javax.ws.rs .POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* Copyright 2014 www.codereligion.com
*
* 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.codereligion.bugsnag.logback.resource;
/**
* The specification of the bugsnag endpoint.
*
* @author Sebastian Gröbler
*/
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public interface NotifierResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
|
Response sendNotification(NotificationVO notificationVO);
|
badlogic/opencv-fun
|
src/pool/utils/MotionDetector.java
|
// Path: src/pool/tests/ColorSpace.java
// public class ColorSpace {
// public static void main (String[] args) {
// CVLoader.load();
// Mat orig = Highgui.imread("data/topdown-6.jpg");
// Mat hsv = new Mat();
// Imgproc.cvtColor(orig, hsv, Imgproc.COLOR_BGR2YCrCb);
//
// List<Mat> channels = new ArrayList<Mat>();
// for(int i = 0; i < hsv.channels(); i++) {
// Mat channel = new Mat();
// channels.add(channel);
// }
// Core.split(hsv, channels);
//
// for(Mat channel: channels) {
// ImgWindow.newWindow(channel);
// }
// }
//
// public static Mat getChannel(Mat img, int channelIdx) {
// List<Mat> channels = new ArrayList<Mat>();
// for(int i = 0; i < img.channels(); i++) {
// Mat channel = new Mat();
// channels.add(channel);
// }
// Core.split(img, channels);
// return channels.get(channelIdx);
// }
//
// public static Mat getChannel(Mat orig, int colorSpace, int channelIdx) {
// Mat hsv = new Mat();
// Imgproc.cvtColor(orig, hsv, colorSpace);
// List<Mat> channels = new ArrayList<Mat>();
// for(int i = 0; i < hsv.channels(); i++) {
// Mat channel = new Mat();
// channels.add(channel);
// }
// Core.split(hsv, channels);
// return channels.get(channelIdx);
// }
// }
|
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
import pool.tests.ColorSpace;
|
package pool.utils;
public class MotionDetector {
private float thresholdPercentage = 0.001f;
private Mat lastImage;
private Mat mask;
/**
* @return true if motion was detected compared to the last frame
*/
public boolean detect(Mat frame) {
if(lastImage == null) {
lastImage = frame.clone();
return true;
}
Mat diff = new Mat();
Core.absdiff(lastImage, frame, diff);
Imgproc.threshold(diff, diff, 35, 255, Imgproc.THRESH_BINARY);
// extract color channels and merge them to single bitmask
|
// Path: src/pool/tests/ColorSpace.java
// public class ColorSpace {
// public static void main (String[] args) {
// CVLoader.load();
// Mat orig = Highgui.imread("data/topdown-6.jpg");
// Mat hsv = new Mat();
// Imgproc.cvtColor(orig, hsv, Imgproc.COLOR_BGR2YCrCb);
//
// List<Mat> channels = new ArrayList<Mat>();
// for(int i = 0; i < hsv.channels(); i++) {
// Mat channel = new Mat();
// channels.add(channel);
// }
// Core.split(hsv, channels);
//
// for(Mat channel: channels) {
// ImgWindow.newWindow(channel);
// }
// }
//
// public static Mat getChannel(Mat img, int channelIdx) {
// List<Mat> channels = new ArrayList<Mat>();
// for(int i = 0; i < img.channels(); i++) {
// Mat channel = new Mat();
// channels.add(channel);
// }
// Core.split(img, channels);
// return channels.get(channelIdx);
// }
//
// public static Mat getChannel(Mat orig, int colorSpace, int channelIdx) {
// Mat hsv = new Mat();
// Imgproc.cvtColor(orig, hsv, colorSpace);
// List<Mat> channels = new ArrayList<Mat>();
// for(int i = 0; i < hsv.channels(); i++) {
// Mat channel = new Mat();
// channels.add(channel);
// }
// Core.split(hsv, channels);
// return channels.get(channelIdx);
// }
// }
// Path: src/pool/utils/MotionDetector.java
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
import pool.tests.ColorSpace;
package pool.utils;
public class MotionDetector {
private float thresholdPercentage = 0.001f;
private Mat lastImage;
private Mat mask;
/**
* @return true if motion was detected compared to the last frame
*/
public boolean detect(Mat frame) {
if(lastImage == null) {
lastImage = frame.clone();
return true;
}
Mat diff = new Mat();
Core.absdiff(lastImage, frame, diff);
Imgproc.threshold(diff, diff, 35, 255, Imgproc.THRESH_BINARY);
// extract color channels and merge them to single bitmask
|
Mat r = ColorSpace.getChannel(diff, 2);
|
xbynet/crawler
|
crawler-core/src/main/java/com/github/xbynet/crawler/parser/JsoupParser.java
|
// Path: crawler-core/src/main/java/com/github/xbynet/crawler/Const.java
// public class Const {
// public enum HttpMethod{
// GET,POST,HEAD
// }
// public enum CssAttr{
// innerHtml,text,allText
// }
// public enum ResponseType{
// TEXT,BIN
// }
// }
|
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.xbynet.crawler.Const;
|
} else {
return element.attr(attrName);
}
}
protected String getText(Element element) {
StringBuilder accum = new StringBuilder();
for (Node node : element.childNodes()) {
if (node instanceof TextNode) {
TextNode textNode = (TextNode) node;
accum.append(textNode.text());
}
}
return accum.toString();
}
public Element element(String cssSelector) {
Elements els = getDoc().select(cssSelector);
if (els == null || els.size() == 0) {
log.warn("所选元素不存在" + cssSelector);
return null;
}
return els.get(0);
}
public Elements elements(String cssSelector) {
Elements els = getDoc().select(cssSelector);
return els;
}
public String script(String cssSelector) {
|
// Path: crawler-core/src/main/java/com/github/xbynet/crawler/Const.java
// public class Const {
// public enum HttpMethod{
// GET,POST,HEAD
// }
// public enum CssAttr{
// innerHtml,text,allText
// }
// public enum ResponseType{
// TEXT,BIN
// }
// }
// Path: crawler-core/src/main/java/com/github/xbynet/crawler/parser/JsoupParser.java
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.xbynet.crawler.Const;
} else {
return element.attr(attrName);
}
}
protected String getText(Element element) {
StringBuilder accum = new StringBuilder();
for (Node node : element.childNodes()) {
if (node instanceof TextNode) {
TextNode textNode = (TextNode) node;
accum.append(textNode.text());
}
}
return accum.toString();
}
public Element element(String cssSelector) {
Elements els = getDoc().select(cssSelector);
if (els == null || els.size() == 0) {
log.warn("所选元素不存在" + cssSelector);
return null;
}
return els.get(0);
}
public Elements elements(String cssSelector) {
Elements els = getDoc().select(cssSelector);
return els;
}
public String script(String cssSelector) {
|
return single(cssSelector,Const.CssAttr.innerHtml.name());
|
gelldur/Common-Android
|
src/com/squareup/okhttp/interceptor/LogInterceptor.java
|
// Path: src/com/dexode/util/log/Logger.java
// public class Logger {
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void d(final String text, Object... args) {
// if (_log != null) {
// _log.d(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void i(final String text, Object... args) {
// if (_log != null) {
// _log.i(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void w(final String text, Object... args) {
// if (_log != null) {
// _log.w(text, args);
// }
// }
//
// public static void e(final String text, Object... args) {
// if (_log != null) {
// _log.e(text, args);
// }
// }
//
// public static void e(final Exception exception, @Nullable final String text) {
// if (_log != null) {
// _log.e(exception, text);
// }
// }
//
// public static void e(final Exception exception) {
// if (_log != null) {
// _log.e(exception, null);
// }
// }
//
//
// public static void setLog(Log log) {
// _log = log;
// }
//
// @Nullable
// private static Log _log;
//
// public interface Log {
// /**
// * This method should be removed in release code by proguard
// */
// public void d(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void i(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void w(final String text, Object... args);
//
// public void e(final String text, Object... args);
//
// public void e(final Exception exception, @Nullable final String text);
// }
// }
|
import com.dexode.util.log.Logger;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import java.io.IOException;
import okio.Buffer;
|
package com.squareup.okhttp.interceptor;
/**
* This class is no long supported. Please use one in okhttp3 package.
*/
public class LogInterceptor implements Interceptor {
private static final String F_BREAK = " %n";
private static final String F_URL = " %s";
private static final String F_TIME = " in %.1fms";
private static final String F_HEADERS = "%s";
private static final String F_RESPONSE = F_BREAK + "Response: %d";
private static final String F_BODY = "body: %s";
private static final String F_BREAKER = F_BREAK + "-------------------------------------------" + F_BREAK;
private static final String F_REQUEST_WITHOUT_BODY = F_URL + F_TIME + F_BREAK + F_HEADERS;
private static final String F_RESPONSE_WITHOUT_BODY = F_RESPONSE + F_BREAK + F_HEADERS + F_BREAKER;
private static final String F_REQUEST_WITH_BODY = F_URL + F_TIME + F_BREAK + F_HEADERS + F_BODY + F_BREAK;
private static final String F_RESPONSE_WITH_BODY = F_RESPONSE + F_BREAK + F_HEADERS + F_BODY + F_BREAK + F_BREAKER;
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Response response = chain.proceed(request);
long t2 = System.nanoTime();
MediaType contentType = null;
String bodyString = null;
if (response.body() != null) {
contentType = response.body().contentType();
bodyString = response.body().string();
}
double time = (t2 - t1) / 1e6d;
|
// Path: src/com/dexode/util/log/Logger.java
// public class Logger {
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void d(final String text, Object... args) {
// if (_log != null) {
// _log.d(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void i(final String text, Object... args) {
// if (_log != null) {
// _log.i(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void w(final String text, Object... args) {
// if (_log != null) {
// _log.w(text, args);
// }
// }
//
// public static void e(final String text, Object... args) {
// if (_log != null) {
// _log.e(text, args);
// }
// }
//
// public static void e(final Exception exception, @Nullable final String text) {
// if (_log != null) {
// _log.e(exception, text);
// }
// }
//
// public static void e(final Exception exception) {
// if (_log != null) {
// _log.e(exception, null);
// }
// }
//
//
// public static void setLog(Log log) {
// _log = log;
// }
//
// @Nullable
// private static Log _log;
//
// public interface Log {
// /**
// * This method should be removed in release code by proguard
// */
// public void d(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void i(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void w(final String text, Object... args);
//
// public void e(final String text, Object... args);
//
// public void e(final Exception exception, @Nullable final String text);
// }
// }
// Path: src/com/squareup/okhttp/interceptor/LogInterceptor.java
import com.dexode.util.log.Logger;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import java.io.IOException;
import okio.Buffer;
package com.squareup.okhttp.interceptor;
/**
* This class is no long supported. Please use one in okhttp3 package.
*/
public class LogInterceptor implements Interceptor {
private static final String F_BREAK = " %n";
private static final String F_URL = " %s";
private static final String F_TIME = " in %.1fms";
private static final String F_HEADERS = "%s";
private static final String F_RESPONSE = F_BREAK + "Response: %d";
private static final String F_BODY = "body: %s";
private static final String F_BREAKER = F_BREAK + "-------------------------------------------" + F_BREAK;
private static final String F_REQUEST_WITHOUT_BODY = F_URL + F_TIME + F_BREAK + F_HEADERS;
private static final String F_RESPONSE_WITHOUT_BODY = F_RESPONSE + F_BREAK + F_HEADERS + F_BREAKER;
private static final String F_REQUEST_WITH_BODY = F_URL + F_TIME + F_BREAK + F_HEADERS + F_BODY + F_BREAK;
private static final String F_RESPONSE_WITH_BODY = F_RESPONSE + F_BREAK + F_HEADERS + F_BODY + F_BREAK + F_BREAKER;
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Response response = chain.proceed(request);
long t2 = System.nanoTime();
MediaType contentType = null;
String bodyString = null;
if (response.body() != null) {
contentType = response.body().contentType();
bodyString = response.body().string();
}
double time = (t2 - t1) / 1e6d;
|
Logger.i(
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.