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 |
|---|---|---|---|---|---|---|
antelink/SourceSquare | src/main/java/com/antelink/sourcesquare/event/events/SourceSquareResultsReadyEvent.java | // Path: src/main/java/com/antelink/sourcesquare/SourceSquareResults.java
// public class SourceSquareResults {
//
// private TreemapNode rootNode;
//
// private Collection<Badge> badges;
//
// private int nodeLevel;
//
// public SourceSquareResults() {
// super();
// }
//
// public TreemapNode getRootNode() {
// return this.rootNode;
// }
//
// public void setRootNode(TreemapNode rootNode) {
// this.rootNode = rootNode;
// }
//
// public Collection<Badge> getBadges() {
// return this.badges;
// }
//
// public void setBadges(Collection<Badge> badges) {
// this.badges = badges;
// }
//
// public int getNodeLevel() {
// return this.nodeLevel;
// }
//
// public void setNodeLevel(int nodeLevel) {
// this.nodeLevel = nodeLevel;
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/base/ClientEvent.java
// public interface ClientEvent<T extends ClientEventHandler> {
//
// public ClientEventType<T> getHandlerType();
//
// public void dispatch(T handler);
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/base/ClientEventType.java
// public class ClientEventType<T extends ClientEventHandler> {
// private static int typeIndexCount = 0;
// public int type = 0;
//
// public ClientEventType() {
// this.type = ++typeIndexCount;
// }
//
// @Override
// public int hashCode() {
// return this.type;
// }
//
// @SuppressWarnings("rawtypes")
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// ClientEventType other = (ClientEventType) obj;
// if (this.type != other.type) {
// return false;
// }
// return true;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/SourceSquareResultsReadyEventHandler.java
// public interface SourceSquareResultsReadyEventHandler extends ClientEventHandler {
//
// public void handle(SourceSquareResults results);
// }
| import com.antelink.sourcesquare.SourceSquareResults;
import com.antelink.sourcesquare.event.base.ClientEvent;
import com.antelink.sourcesquare.event.base.ClientEventType;
import com.antelink.sourcesquare.event.handlers.SourceSquareResultsReadyEventHandler; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.event.events;
public class SourceSquareResultsReadyEvent implements ClientEvent<SourceSquareResultsReadyEventHandler> {
public static final ClientEventType<SourceSquareResultsReadyEventHandler> TYPE = new ClientEventType<SourceSquareResultsReadyEventHandler>();
| // Path: src/main/java/com/antelink/sourcesquare/SourceSquareResults.java
// public class SourceSquareResults {
//
// private TreemapNode rootNode;
//
// private Collection<Badge> badges;
//
// private int nodeLevel;
//
// public SourceSquareResults() {
// super();
// }
//
// public TreemapNode getRootNode() {
// return this.rootNode;
// }
//
// public void setRootNode(TreemapNode rootNode) {
// this.rootNode = rootNode;
// }
//
// public Collection<Badge> getBadges() {
// return this.badges;
// }
//
// public void setBadges(Collection<Badge> badges) {
// this.badges = badges;
// }
//
// public int getNodeLevel() {
// return this.nodeLevel;
// }
//
// public void setNodeLevel(int nodeLevel) {
// this.nodeLevel = nodeLevel;
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/base/ClientEvent.java
// public interface ClientEvent<T extends ClientEventHandler> {
//
// public ClientEventType<T> getHandlerType();
//
// public void dispatch(T handler);
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/base/ClientEventType.java
// public class ClientEventType<T extends ClientEventHandler> {
// private static int typeIndexCount = 0;
// public int type = 0;
//
// public ClientEventType() {
// this.type = ++typeIndexCount;
// }
//
// @Override
// public int hashCode() {
// return this.type;
// }
//
// @SuppressWarnings("rawtypes")
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// ClientEventType other = (ClientEventType) obj;
// if (this.type != other.type) {
// return false;
// }
// return true;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/SourceSquareResultsReadyEventHandler.java
// public interface SourceSquareResultsReadyEventHandler extends ClientEventHandler {
//
// public void handle(SourceSquareResults results);
// }
// Path: src/main/java/com/antelink/sourcesquare/event/events/SourceSquareResultsReadyEvent.java
import com.antelink.sourcesquare.SourceSquareResults;
import com.antelink.sourcesquare.event.base.ClientEvent;
import com.antelink.sourcesquare.event.base.ClientEventType;
import com.antelink.sourcesquare.event.handlers.SourceSquareResultsReadyEventHandler;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.event.events;
public class SourceSquareResultsReadyEvent implements ClientEvent<SourceSquareResultsReadyEventHandler> {
public static final ClientEventType<SourceSquareResultsReadyEventHandler> TYPE = new ClientEventType<SourceSquareResultsReadyEventHandler>();
| private final SourceSquareResults results; |
antelink/SourceSquare | src/main/java/com/antelink/sourcesquare/server/servlet/ResultFilter.java | // Path: src/main/java/com/antelink/sourcesquare/SourceSquareResults.java
// public class SourceSquareResults {
//
// private TreemapNode rootNode;
//
// private Collection<Badge> badges;
//
// private int nodeLevel;
//
// public SourceSquareResults() {
// super();
// }
//
// public TreemapNode getRootNode() {
// return this.rootNode;
// }
//
// public void setRootNode(TreemapNode rootNode) {
// this.rootNode = rootNode;
// }
//
// public Collection<Badge> getBadges() {
// return this.badges;
// }
//
// public void setBadges(Collection<Badge> badges) {
// this.badges = badges;
// }
//
// public int getNodeLevel() {
// return this.nodeLevel;
// }
//
// public void setNodeLevel(int nodeLevel) {
// this.nodeLevel = nodeLevel;
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/SourceSquareResultsReadyEvent.java
// public class SourceSquareResultsReadyEvent implements ClientEvent<SourceSquareResultsReadyEventHandler> {
//
// public static final ClientEventType<SourceSquareResultsReadyEventHandler> TYPE = new ClientEventType<SourceSquareResultsReadyEventHandler>();
//
// private final SourceSquareResults results;
//
// public SourceSquareResultsReadyEvent(SourceSquareResults results) {
// this.results = results;
// }
//
// @Override
// public ClientEventType<SourceSquareResultsReadyEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(SourceSquareResultsReadyEventHandler handler) {
// handler.handle(this.results);
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/SourceSquareResultsReadyEventHandler.java
// public interface SourceSquareResultsReadyEventHandler extends ClientEventHandler {
//
// public void handle(SourceSquareResults results);
// }
| import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.antelink.sourcesquare.SourceSquareResults;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.SourceSquareResultsReadyEvent;
import com.antelink.sourcesquare.event.handlers.SourceSquareResultsReadyEventHandler;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server.servlet;
public class ResultFilter implements Filter {
private static final Log logger = LogFactory.getLog(ResultFilter.class);
| // Path: src/main/java/com/antelink/sourcesquare/SourceSquareResults.java
// public class SourceSquareResults {
//
// private TreemapNode rootNode;
//
// private Collection<Badge> badges;
//
// private int nodeLevel;
//
// public SourceSquareResults() {
// super();
// }
//
// public TreemapNode getRootNode() {
// return this.rootNode;
// }
//
// public void setRootNode(TreemapNode rootNode) {
// this.rootNode = rootNode;
// }
//
// public Collection<Badge> getBadges() {
// return this.badges;
// }
//
// public void setBadges(Collection<Badge> badges) {
// this.badges = badges;
// }
//
// public int getNodeLevel() {
// return this.nodeLevel;
// }
//
// public void setNodeLevel(int nodeLevel) {
// this.nodeLevel = nodeLevel;
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/SourceSquareResultsReadyEvent.java
// public class SourceSquareResultsReadyEvent implements ClientEvent<SourceSquareResultsReadyEventHandler> {
//
// public static final ClientEventType<SourceSquareResultsReadyEventHandler> TYPE = new ClientEventType<SourceSquareResultsReadyEventHandler>();
//
// private final SourceSquareResults results;
//
// public SourceSquareResultsReadyEvent(SourceSquareResults results) {
// this.results = results;
// }
//
// @Override
// public ClientEventType<SourceSquareResultsReadyEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(SourceSquareResultsReadyEventHandler handler) {
// handler.handle(this.results);
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/SourceSquareResultsReadyEventHandler.java
// public interface SourceSquareResultsReadyEventHandler extends ClientEventHandler {
//
// public void handle(SourceSquareResults results);
// }
// Path: src/main/java/com/antelink/sourcesquare/server/servlet/ResultFilter.java
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.antelink.sourcesquare.SourceSquareResults;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.SourceSquareResultsReadyEvent;
import com.antelink.sourcesquare.event.handlers.SourceSquareResultsReadyEventHandler;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server.servlet;
public class ResultFilter implements Filter {
private static final Log logger = LogFactory.getLog(ResultFilter.class);
| private SourceSquareResults sourceSquareResult; |
antelink/SourceSquare | src/main/java/com/antelink/sourcesquare/server/servlet/ResultFilter.java | // Path: src/main/java/com/antelink/sourcesquare/SourceSquareResults.java
// public class SourceSquareResults {
//
// private TreemapNode rootNode;
//
// private Collection<Badge> badges;
//
// private int nodeLevel;
//
// public SourceSquareResults() {
// super();
// }
//
// public TreemapNode getRootNode() {
// return this.rootNode;
// }
//
// public void setRootNode(TreemapNode rootNode) {
// this.rootNode = rootNode;
// }
//
// public Collection<Badge> getBadges() {
// return this.badges;
// }
//
// public void setBadges(Collection<Badge> badges) {
// this.badges = badges;
// }
//
// public int getNodeLevel() {
// return this.nodeLevel;
// }
//
// public void setNodeLevel(int nodeLevel) {
// this.nodeLevel = nodeLevel;
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/SourceSquareResultsReadyEvent.java
// public class SourceSquareResultsReadyEvent implements ClientEvent<SourceSquareResultsReadyEventHandler> {
//
// public static final ClientEventType<SourceSquareResultsReadyEventHandler> TYPE = new ClientEventType<SourceSquareResultsReadyEventHandler>();
//
// private final SourceSquareResults results;
//
// public SourceSquareResultsReadyEvent(SourceSquareResults results) {
// this.results = results;
// }
//
// @Override
// public ClientEventType<SourceSquareResultsReadyEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(SourceSquareResultsReadyEventHandler handler) {
// handler.handle(this.results);
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/SourceSquareResultsReadyEventHandler.java
// public interface SourceSquareResultsReadyEventHandler extends ClientEventHandler {
//
// public void handle(SourceSquareResults results);
// }
| import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.antelink.sourcesquare.SourceSquareResults;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.SourceSquareResultsReadyEvent;
import com.antelink.sourcesquare.event.handlers.SourceSquareResultsReadyEventHandler;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server.servlet;
public class ResultFilter implements Filter {
private static final Log logger = LogFactory.getLog(ResultFilter.class);
private SourceSquareResults sourceSquareResult;
| // Path: src/main/java/com/antelink/sourcesquare/SourceSquareResults.java
// public class SourceSquareResults {
//
// private TreemapNode rootNode;
//
// private Collection<Badge> badges;
//
// private int nodeLevel;
//
// public SourceSquareResults() {
// super();
// }
//
// public TreemapNode getRootNode() {
// return this.rootNode;
// }
//
// public void setRootNode(TreemapNode rootNode) {
// this.rootNode = rootNode;
// }
//
// public Collection<Badge> getBadges() {
// return this.badges;
// }
//
// public void setBadges(Collection<Badge> badges) {
// this.badges = badges;
// }
//
// public int getNodeLevel() {
// return this.nodeLevel;
// }
//
// public void setNodeLevel(int nodeLevel) {
// this.nodeLevel = nodeLevel;
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/SourceSquareResultsReadyEvent.java
// public class SourceSquareResultsReadyEvent implements ClientEvent<SourceSquareResultsReadyEventHandler> {
//
// public static final ClientEventType<SourceSquareResultsReadyEventHandler> TYPE = new ClientEventType<SourceSquareResultsReadyEventHandler>();
//
// private final SourceSquareResults results;
//
// public SourceSquareResultsReadyEvent(SourceSquareResults results) {
// this.results = results;
// }
//
// @Override
// public ClientEventType<SourceSquareResultsReadyEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(SourceSquareResultsReadyEventHandler handler) {
// handler.handle(this.results);
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/SourceSquareResultsReadyEventHandler.java
// public interface SourceSquareResultsReadyEventHandler extends ClientEventHandler {
//
// public void handle(SourceSquareResults results);
// }
// Path: src/main/java/com/antelink/sourcesquare/server/servlet/ResultFilter.java
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.antelink.sourcesquare.SourceSquareResults;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.SourceSquareResultsReadyEvent;
import com.antelink.sourcesquare.event.handlers.SourceSquareResultsReadyEventHandler;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server.servlet;
public class ResultFilter implements Filter {
private static final Log logger = LogFactory.getLog(ResultFilter.class);
private SourceSquareResults sourceSquareResult;
| public ResultFilter(EventBus eventBus) { |
antelink/SourceSquare | src/main/java/com/antelink/sourcesquare/server/servlet/ResultFilter.java | // Path: src/main/java/com/antelink/sourcesquare/SourceSquareResults.java
// public class SourceSquareResults {
//
// private TreemapNode rootNode;
//
// private Collection<Badge> badges;
//
// private int nodeLevel;
//
// public SourceSquareResults() {
// super();
// }
//
// public TreemapNode getRootNode() {
// return this.rootNode;
// }
//
// public void setRootNode(TreemapNode rootNode) {
// this.rootNode = rootNode;
// }
//
// public Collection<Badge> getBadges() {
// return this.badges;
// }
//
// public void setBadges(Collection<Badge> badges) {
// this.badges = badges;
// }
//
// public int getNodeLevel() {
// return this.nodeLevel;
// }
//
// public void setNodeLevel(int nodeLevel) {
// this.nodeLevel = nodeLevel;
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/SourceSquareResultsReadyEvent.java
// public class SourceSquareResultsReadyEvent implements ClientEvent<SourceSquareResultsReadyEventHandler> {
//
// public static final ClientEventType<SourceSquareResultsReadyEventHandler> TYPE = new ClientEventType<SourceSquareResultsReadyEventHandler>();
//
// private final SourceSquareResults results;
//
// public SourceSquareResultsReadyEvent(SourceSquareResults results) {
// this.results = results;
// }
//
// @Override
// public ClientEventType<SourceSquareResultsReadyEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(SourceSquareResultsReadyEventHandler handler) {
// handler.handle(this.results);
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/SourceSquareResultsReadyEventHandler.java
// public interface SourceSquareResultsReadyEventHandler extends ClientEventHandler {
//
// public void handle(SourceSquareResults results);
// }
| import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.antelink.sourcesquare.SourceSquareResults;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.SourceSquareResultsReadyEvent;
import com.antelink.sourcesquare.event.handlers.SourceSquareResultsReadyEventHandler;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server.servlet;
public class ResultFilter implements Filter {
private static final Log logger = LogFactory.getLog(ResultFilter.class);
private SourceSquareResults sourceSquareResult;
public ResultFilter(EventBus eventBus) { | // Path: src/main/java/com/antelink/sourcesquare/SourceSquareResults.java
// public class SourceSquareResults {
//
// private TreemapNode rootNode;
//
// private Collection<Badge> badges;
//
// private int nodeLevel;
//
// public SourceSquareResults() {
// super();
// }
//
// public TreemapNode getRootNode() {
// return this.rootNode;
// }
//
// public void setRootNode(TreemapNode rootNode) {
// this.rootNode = rootNode;
// }
//
// public Collection<Badge> getBadges() {
// return this.badges;
// }
//
// public void setBadges(Collection<Badge> badges) {
// this.badges = badges;
// }
//
// public int getNodeLevel() {
// return this.nodeLevel;
// }
//
// public void setNodeLevel(int nodeLevel) {
// this.nodeLevel = nodeLevel;
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/SourceSquareResultsReadyEvent.java
// public class SourceSquareResultsReadyEvent implements ClientEvent<SourceSquareResultsReadyEventHandler> {
//
// public static final ClientEventType<SourceSquareResultsReadyEventHandler> TYPE = new ClientEventType<SourceSquareResultsReadyEventHandler>();
//
// private final SourceSquareResults results;
//
// public SourceSquareResultsReadyEvent(SourceSquareResults results) {
// this.results = results;
// }
//
// @Override
// public ClientEventType<SourceSquareResultsReadyEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(SourceSquareResultsReadyEventHandler handler) {
// handler.handle(this.results);
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/SourceSquareResultsReadyEventHandler.java
// public interface SourceSquareResultsReadyEventHandler extends ClientEventHandler {
//
// public void handle(SourceSquareResults results);
// }
// Path: src/main/java/com/antelink/sourcesquare/server/servlet/ResultFilter.java
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.antelink.sourcesquare.SourceSquareResults;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.SourceSquareResultsReadyEvent;
import com.antelink.sourcesquare.event.handlers.SourceSquareResultsReadyEventHandler;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server.servlet;
public class ResultFilter implements Filter {
private static final Log logger = LogFactory.getLog(ResultFilter.class);
private SourceSquareResults sourceSquareResult;
public ResultFilter(EventBus eventBus) { | eventBus.addHandler(SourceSquareResultsReadyEvent.TYPE, |
antelink/SourceSquare | src/main/java/com/antelink/sourcesquare/server/servlet/ResultFilter.java | // Path: src/main/java/com/antelink/sourcesquare/SourceSquareResults.java
// public class SourceSquareResults {
//
// private TreemapNode rootNode;
//
// private Collection<Badge> badges;
//
// private int nodeLevel;
//
// public SourceSquareResults() {
// super();
// }
//
// public TreemapNode getRootNode() {
// return this.rootNode;
// }
//
// public void setRootNode(TreemapNode rootNode) {
// this.rootNode = rootNode;
// }
//
// public Collection<Badge> getBadges() {
// return this.badges;
// }
//
// public void setBadges(Collection<Badge> badges) {
// this.badges = badges;
// }
//
// public int getNodeLevel() {
// return this.nodeLevel;
// }
//
// public void setNodeLevel(int nodeLevel) {
// this.nodeLevel = nodeLevel;
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/SourceSquareResultsReadyEvent.java
// public class SourceSquareResultsReadyEvent implements ClientEvent<SourceSquareResultsReadyEventHandler> {
//
// public static final ClientEventType<SourceSquareResultsReadyEventHandler> TYPE = new ClientEventType<SourceSquareResultsReadyEventHandler>();
//
// private final SourceSquareResults results;
//
// public SourceSquareResultsReadyEvent(SourceSquareResults results) {
// this.results = results;
// }
//
// @Override
// public ClientEventType<SourceSquareResultsReadyEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(SourceSquareResultsReadyEventHandler handler) {
// handler.handle(this.results);
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/SourceSquareResultsReadyEventHandler.java
// public interface SourceSquareResultsReadyEventHandler extends ClientEventHandler {
//
// public void handle(SourceSquareResults results);
// }
| import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.antelink.sourcesquare.SourceSquareResults;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.SourceSquareResultsReadyEvent;
import com.antelink.sourcesquare.event.handlers.SourceSquareResultsReadyEventHandler;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server.servlet;
public class ResultFilter implements Filter {
private static final Log logger = LogFactory.getLog(ResultFilter.class);
private SourceSquareResults sourceSquareResult;
public ResultFilter(EventBus eventBus) {
eventBus.addHandler(SourceSquareResultsReadyEvent.TYPE, | // Path: src/main/java/com/antelink/sourcesquare/SourceSquareResults.java
// public class SourceSquareResults {
//
// private TreemapNode rootNode;
//
// private Collection<Badge> badges;
//
// private int nodeLevel;
//
// public SourceSquareResults() {
// super();
// }
//
// public TreemapNode getRootNode() {
// return this.rootNode;
// }
//
// public void setRootNode(TreemapNode rootNode) {
// this.rootNode = rootNode;
// }
//
// public Collection<Badge> getBadges() {
// return this.badges;
// }
//
// public void setBadges(Collection<Badge> badges) {
// this.badges = badges;
// }
//
// public int getNodeLevel() {
// return this.nodeLevel;
// }
//
// public void setNodeLevel(int nodeLevel) {
// this.nodeLevel = nodeLevel;
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/SourceSquareResultsReadyEvent.java
// public class SourceSquareResultsReadyEvent implements ClientEvent<SourceSquareResultsReadyEventHandler> {
//
// public static final ClientEventType<SourceSquareResultsReadyEventHandler> TYPE = new ClientEventType<SourceSquareResultsReadyEventHandler>();
//
// private final SourceSquareResults results;
//
// public SourceSquareResultsReadyEvent(SourceSquareResults results) {
// this.results = results;
// }
//
// @Override
// public ClientEventType<SourceSquareResultsReadyEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(SourceSquareResultsReadyEventHandler handler) {
// handler.handle(this.results);
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/SourceSquareResultsReadyEventHandler.java
// public interface SourceSquareResultsReadyEventHandler extends ClientEventHandler {
//
// public void handle(SourceSquareResults results);
// }
// Path: src/main/java/com/antelink/sourcesquare/server/servlet/ResultFilter.java
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.antelink.sourcesquare.SourceSquareResults;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.SourceSquareResultsReadyEvent;
import com.antelink.sourcesquare.event.handlers.SourceSquareResultsReadyEventHandler;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server.servlet;
public class ResultFilter implements Filter {
private static final Log logger = LogFactory.getLog(ResultFilter.class);
private SourceSquareResults sourceSquareResult;
public ResultFilter(EventBus eventBus) {
eventBus.addHandler(SourceSquareResultsReadyEvent.TYPE, | new SourceSquareResultsReadyEventHandler() { |
antelink/SourceSquare | src/test/java/com/antelink/sourcesquare/server/SimulationController.java | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
| import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.antelink.sourcesquare.event.base.EventBus; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server;
public class SimulationController extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -6688301326611244068L; | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
// Path: src/test/java/com/antelink/sourcesquare/server/SimulationController.java
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.antelink.sourcesquare.event.base.EventBus;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server;
public class SimulationController extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -6688301326611244068L; | private EventBus eventBus; |
antelink/SourceSquare | src/test/java/com/antelink/sourcesquare/badge/TestBadgeProcessor.java | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/FilesIdentifiedEvent.java
// public class FilesIdentifiedEvent implements ClientEvent<FilesIdentifiedEventHandler> {
//
// public static final ClientEventType<FilesIdentifiedEventHandler> TYPE = new ClientEventType<FilesIdentifiedEventHandler>();
//
// private final TreeSet<File> fileSet;
//
// public FilesIdentifiedEvent(TreeSet<File> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<FilesIdentifiedEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(FilesIdentifiedEventHandler handler) {
// handler.handle(this.fileSet);
//
// }
//
// public TreeSet<File> getFileSet() {
// return this.fileSet;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/OSFilesFoundEvent.java
// public class OSFilesFoundEvent implements ClientEvent<OSFilesFoundEventHandler> {
//
// public static final ClientEventType<OSFilesFoundEventHandler> TYPE = new ClientEventType<OSFilesFoundEventHandler>();
//
// private final Set<String> fileSet;
//
// public OSFilesFoundEvent(Set<String> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<OSFilesFoundEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(OSFilesFoundEventHandler handler) {
// handler.handle(this.fileSet);
// }
//
// public Set<String> getFileSet() {
// return this.fileSet;
// }
//
// }
| import org.easymock.EasyMock;
import org.easymock.IAnswer;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.FilesIdentifiedEvent;
import com.antelink.sourcesquare.event.events.OSFilesFoundEvent;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.badge;
public class TestBadgeProcessor {
BadgesProcessor processor; | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/FilesIdentifiedEvent.java
// public class FilesIdentifiedEvent implements ClientEvent<FilesIdentifiedEventHandler> {
//
// public static final ClientEventType<FilesIdentifiedEventHandler> TYPE = new ClientEventType<FilesIdentifiedEventHandler>();
//
// private final TreeSet<File> fileSet;
//
// public FilesIdentifiedEvent(TreeSet<File> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<FilesIdentifiedEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(FilesIdentifiedEventHandler handler) {
// handler.handle(this.fileSet);
//
// }
//
// public TreeSet<File> getFileSet() {
// return this.fileSet;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/OSFilesFoundEvent.java
// public class OSFilesFoundEvent implements ClientEvent<OSFilesFoundEventHandler> {
//
// public static final ClientEventType<OSFilesFoundEventHandler> TYPE = new ClientEventType<OSFilesFoundEventHandler>();
//
// private final Set<String> fileSet;
//
// public OSFilesFoundEvent(Set<String> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<OSFilesFoundEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(OSFilesFoundEventHandler handler) {
// handler.handle(this.fileSet);
// }
//
// public Set<String> getFileSet() {
// return this.fileSet;
// }
//
// }
// Path: src/test/java/com/antelink/sourcesquare/badge/TestBadgeProcessor.java
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.FilesIdentifiedEvent;
import com.antelink.sourcesquare.event.events.OSFilesFoundEvent;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.badge;
public class TestBadgeProcessor {
BadgesProcessor processor; | EventBus bus; |
antelink/SourceSquare | src/test/java/com/antelink/sourcesquare/badge/TestBadgeProcessor.java | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/FilesIdentifiedEvent.java
// public class FilesIdentifiedEvent implements ClientEvent<FilesIdentifiedEventHandler> {
//
// public static final ClientEventType<FilesIdentifiedEventHandler> TYPE = new ClientEventType<FilesIdentifiedEventHandler>();
//
// private final TreeSet<File> fileSet;
//
// public FilesIdentifiedEvent(TreeSet<File> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<FilesIdentifiedEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(FilesIdentifiedEventHandler handler) {
// handler.handle(this.fileSet);
//
// }
//
// public TreeSet<File> getFileSet() {
// return this.fileSet;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/OSFilesFoundEvent.java
// public class OSFilesFoundEvent implements ClientEvent<OSFilesFoundEventHandler> {
//
// public static final ClientEventType<OSFilesFoundEventHandler> TYPE = new ClientEventType<OSFilesFoundEventHandler>();
//
// private final Set<String> fileSet;
//
// public OSFilesFoundEvent(Set<String> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<OSFilesFoundEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(OSFilesFoundEventHandler handler) {
// handler.handle(this.fileSet);
// }
//
// public Set<String> getFileSet() {
// return this.fileSet;
// }
//
// }
| import org.easymock.EasyMock;
import org.easymock.IAnswer;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.FilesIdentifiedEvent;
import com.antelink.sourcesquare.event.events.OSFilesFoundEvent;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.badge;
public class TestBadgeProcessor {
BadgesProcessor processor;
EventBus bus;
Integer count=0;
TreeSet<File> files=new TreeSet<File>(Arrays.asList(new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File("")));
@Before
public void init(){
bus=new EventBus();
processor=new BadgesProcessor(bus);
processor.bind();
count=0;
}
@Test @Ignore
// Ignored test: too asynchronous to be trusted...
public void testBadgesOpenSourceSamurai(){
Set<String> set=EasyMock.createMock(Set.class);
expect(set.size()).andReturn(8).andAnswer(new IAnswer<Integer>() {
@Override
public Integer answer() throws Throwable {
synchronized (count) {
count++;
}
return null;
}
});
| // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/FilesIdentifiedEvent.java
// public class FilesIdentifiedEvent implements ClientEvent<FilesIdentifiedEventHandler> {
//
// public static final ClientEventType<FilesIdentifiedEventHandler> TYPE = new ClientEventType<FilesIdentifiedEventHandler>();
//
// private final TreeSet<File> fileSet;
//
// public FilesIdentifiedEvent(TreeSet<File> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<FilesIdentifiedEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(FilesIdentifiedEventHandler handler) {
// handler.handle(this.fileSet);
//
// }
//
// public TreeSet<File> getFileSet() {
// return this.fileSet;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/OSFilesFoundEvent.java
// public class OSFilesFoundEvent implements ClientEvent<OSFilesFoundEventHandler> {
//
// public static final ClientEventType<OSFilesFoundEventHandler> TYPE = new ClientEventType<OSFilesFoundEventHandler>();
//
// private final Set<String> fileSet;
//
// public OSFilesFoundEvent(Set<String> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<OSFilesFoundEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(OSFilesFoundEventHandler handler) {
// handler.handle(this.fileSet);
// }
//
// public Set<String> getFileSet() {
// return this.fileSet;
// }
//
// }
// Path: src/test/java/com/antelink/sourcesquare/badge/TestBadgeProcessor.java
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.FilesIdentifiedEvent;
import com.antelink.sourcesquare.event.events.OSFilesFoundEvent;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.badge;
public class TestBadgeProcessor {
BadgesProcessor processor;
EventBus bus;
Integer count=0;
TreeSet<File> files=new TreeSet<File>(Arrays.asList(new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File("")));
@Before
public void init(){
bus=new EventBus();
processor=new BadgesProcessor(bus);
processor.bind();
count=0;
}
@Test @Ignore
// Ignored test: too asynchronous to be trusted...
public void testBadgesOpenSourceSamurai(){
Set<String> set=EasyMock.createMock(Set.class);
expect(set.size()).andReturn(8).andAnswer(new IAnswer<Integer>() {
@Override
public Integer answer() throws Throwable {
synchronized (count) {
count++;
}
return null;
}
});
| bus.fireEvent(new OSFilesFoundEvent(set)); |
antelink/SourceSquare | src/test/java/com/antelink/sourcesquare/badge/TestBadgeProcessor.java | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/FilesIdentifiedEvent.java
// public class FilesIdentifiedEvent implements ClientEvent<FilesIdentifiedEventHandler> {
//
// public static final ClientEventType<FilesIdentifiedEventHandler> TYPE = new ClientEventType<FilesIdentifiedEventHandler>();
//
// private final TreeSet<File> fileSet;
//
// public FilesIdentifiedEvent(TreeSet<File> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<FilesIdentifiedEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(FilesIdentifiedEventHandler handler) {
// handler.handle(this.fileSet);
//
// }
//
// public TreeSet<File> getFileSet() {
// return this.fileSet;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/OSFilesFoundEvent.java
// public class OSFilesFoundEvent implements ClientEvent<OSFilesFoundEventHandler> {
//
// public static final ClientEventType<OSFilesFoundEventHandler> TYPE = new ClientEventType<OSFilesFoundEventHandler>();
//
// private final Set<String> fileSet;
//
// public OSFilesFoundEvent(Set<String> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<OSFilesFoundEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(OSFilesFoundEventHandler handler) {
// handler.handle(this.fileSet);
// }
//
// public Set<String> getFileSet() {
// return this.fileSet;
// }
//
// }
| import org.easymock.EasyMock;
import org.easymock.IAnswer;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.FilesIdentifiedEvent;
import com.antelink.sourcesquare.event.events.OSFilesFoundEvent;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.badge;
public class TestBadgeProcessor {
BadgesProcessor processor;
EventBus bus;
Integer count=0;
TreeSet<File> files=new TreeSet<File>(Arrays.asList(new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File("")));
@Before
public void init(){
bus=new EventBus();
processor=new BadgesProcessor(bus);
processor.bind();
count=0;
}
@Test @Ignore
// Ignored test: too asynchronous to be trusted...
public void testBadgesOpenSourceSamurai(){
Set<String> set=EasyMock.createMock(Set.class);
expect(set.size()).andReturn(8).andAnswer(new IAnswer<Integer>() {
@Override
public Integer answer() throws Throwable {
synchronized (count) {
count++;
}
return null;
}
});
bus.fireEvent(new OSFilesFoundEvent(set)); | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/FilesIdentifiedEvent.java
// public class FilesIdentifiedEvent implements ClientEvent<FilesIdentifiedEventHandler> {
//
// public static final ClientEventType<FilesIdentifiedEventHandler> TYPE = new ClientEventType<FilesIdentifiedEventHandler>();
//
// private final TreeSet<File> fileSet;
//
// public FilesIdentifiedEvent(TreeSet<File> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<FilesIdentifiedEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(FilesIdentifiedEventHandler handler) {
// handler.handle(this.fileSet);
//
// }
//
// public TreeSet<File> getFileSet() {
// return this.fileSet;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/OSFilesFoundEvent.java
// public class OSFilesFoundEvent implements ClientEvent<OSFilesFoundEventHandler> {
//
// public static final ClientEventType<OSFilesFoundEventHandler> TYPE = new ClientEventType<OSFilesFoundEventHandler>();
//
// private final Set<String> fileSet;
//
// public OSFilesFoundEvent(Set<String> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<OSFilesFoundEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(OSFilesFoundEventHandler handler) {
// handler.handle(this.fileSet);
// }
//
// public Set<String> getFileSet() {
// return this.fileSet;
// }
//
// }
// Path: src/test/java/com/antelink/sourcesquare/badge/TestBadgeProcessor.java
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.FilesIdentifiedEvent;
import com.antelink.sourcesquare.event.events.OSFilesFoundEvent;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.badge;
public class TestBadgeProcessor {
BadgesProcessor processor;
EventBus bus;
Integer count=0;
TreeSet<File> files=new TreeSet<File>(Arrays.asList(new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File(""),new File("")));
@Before
public void init(){
bus=new EventBus();
processor=new BadgesProcessor(bus);
processor.bind();
count=0;
}
@Test @Ignore
// Ignored test: too asynchronous to be trusted...
public void testBadgesOpenSourceSamurai(){
Set<String> set=EasyMock.createMock(Set.class);
expect(set.size()).andReturn(8).andAnswer(new IAnswer<Integer>() {
@Override
public Integer answer() throws Throwable {
synchronized (count) {
count++;
}
return null;
}
});
bus.fireEvent(new OSFilesFoundEvent(set)); | bus.fireEvent(new FilesIdentifiedEvent(files)); |
antelink/SourceSquare | src/main/java/com/antelink/sourcesquare/server/servlet/QuaptchaServlet.java | // Path: src/main/java/com/antelink/sourcesquare/server/JCaptchaBean.java
// public class JCaptchaBean {
//
// private boolean error;
//
// public JCaptchaBean(){
//
// }
//
// public JCaptchaBean(boolean error) {
// this.error = error;
// }
//
// public boolean isError() {
// return error;
// }
//
// public void setError(boolean error) {
// this.error = error;
// }
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.antelink.sourcesquare.server.JCaptchaBean;
import com.google.gson.Gson;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server.servlet;
public class QuaptchaServlet extends HttpServlet {
private static final Log logger = LogFactory.getLog(QuaptchaServlet.class);
private static final long serialVersionUID = 1445253079298703388L;
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
String key = request.getParameter("qaptcha_key");
String action = request.getParameter("action");
response.setContentType("text/html;charset=utf-8"); | // Path: src/main/java/com/antelink/sourcesquare/server/JCaptchaBean.java
// public class JCaptchaBean {
//
// private boolean error;
//
// public JCaptchaBean(){
//
// }
//
// public JCaptchaBean(boolean error) {
// this.error = error;
// }
//
// public boolean isError() {
// return error;
// }
//
// public void setError(boolean error) {
// this.error = error;
// }
// }
// Path: src/main/java/com/antelink/sourcesquare/server/servlet/QuaptchaServlet.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.antelink.sourcesquare.server.JCaptchaBean;
import com.google.gson.Gson;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server.servlet;
public class QuaptchaServlet extends HttpServlet {
private static final Log logger = LogFactory.getLog(QuaptchaServlet.class);
private static final long serialVersionUID = 1445253079298703388L;
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
String key = request.getParameter("qaptcha_key");
String action = request.getParameter("action");
response.setContentType("text/html;charset=utf-8"); | JCaptchaBean qap = null; |
antelink/SourceSquare | src/test/java/com/antelink/sourcesquare/query/AntepediaQueryIT.java | // Path: src/main/java/com/antelink/sourcesquare/query/AntepediaQuery.java
// public class AntepediaQuery extends RestClient {
//
// private final static Log logger = LogFactory.getLog(AntepediaQuery.class);
//
// private final AntepediaLocations locations = new AntepediaLocations();
//
// public List<ResultEntry> getResults(Map<String, String> files) throws RestClientException,
// JsonGenerationException, JsonMappingException, IOException {
//
// ResponseObject response = getResponseObjects(files.values());
//
// if (response.hasError()) {
// response.getError().getErrorCode();
// logger.error("Error getting the results from the antepedia server : "
// + response.getError().getErrorMessage());
// logger.error("Remote service returned error code: "
// + response.getError().getErrorCode());
// }
//
// return response.getResults();
// }
//
// private ResponseObject getResponseObjects(Collection<String> hashes)
// throws JsonGenerationException, JsonMappingException, IOException {
// try {
// String queryUrl = this.locations.getBinaryBatchQueryUrl();
// ObjectMapper mapper = new ObjectMapper();
// String map = mapper.writeValueAsString(hashes);
// logger.info("contacting server " + queryUrl + " with " + hashes.size() + " hashs");
// ResponseObject postForObject = getTemplate(this.locations.getBaseDomain())
// .postForObject(queryUrl, map, ResponseObject.class);
// logger.info("response received");
// return postForObject;
// } catch (UnsupportedEncodingException e) {
// logger.error("Error contacting the server", e);
// return null;
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/query/ResultEntry.java
// public class ResultEntry {
//
// private String sha1;
//
// public ResultEntry() {
//
// }
//
// public ResultEntry(String sha1) {
// super();
// this.sha1 = sha1;
// }
//
// public String getSha1() {
// return this.sha1;
// }
//
// public void setSha1(String sha1) {
// this.sha1 = sha1;
// }
//
// }
| import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import com.antelink.sourcesquare.query.AntepediaQuery;
import com.antelink.sourcesquare.query.ResultEntry;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.util.HashMap; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.query;
public class AntepediaQueryIT {
private AntepediaQuery query;
@Before
public void init() {
this.query = new AntepediaQuery();
}
@Test
public void testAnswerNotFound() throws Exception {
Map<String, String> files = new HashMap<String, String>();
files.put("toto", "632a990d82e7381e7afeeb3478342d17e9dfb835"); | // Path: src/main/java/com/antelink/sourcesquare/query/AntepediaQuery.java
// public class AntepediaQuery extends RestClient {
//
// private final static Log logger = LogFactory.getLog(AntepediaQuery.class);
//
// private final AntepediaLocations locations = new AntepediaLocations();
//
// public List<ResultEntry> getResults(Map<String, String> files) throws RestClientException,
// JsonGenerationException, JsonMappingException, IOException {
//
// ResponseObject response = getResponseObjects(files.values());
//
// if (response.hasError()) {
// response.getError().getErrorCode();
// logger.error("Error getting the results from the antepedia server : "
// + response.getError().getErrorMessage());
// logger.error("Remote service returned error code: "
// + response.getError().getErrorCode());
// }
//
// return response.getResults();
// }
//
// private ResponseObject getResponseObjects(Collection<String> hashes)
// throws JsonGenerationException, JsonMappingException, IOException {
// try {
// String queryUrl = this.locations.getBinaryBatchQueryUrl();
// ObjectMapper mapper = new ObjectMapper();
// String map = mapper.writeValueAsString(hashes);
// logger.info("contacting server " + queryUrl + " with " + hashes.size() + " hashs");
// ResponseObject postForObject = getTemplate(this.locations.getBaseDomain())
// .postForObject(queryUrl, map, ResponseObject.class);
// logger.info("response received");
// return postForObject;
// } catch (UnsupportedEncodingException e) {
// logger.error("Error contacting the server", e);
// return null;
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/query/ResultEntry.java
// public class ResultEntry {
//
// private String sha1;
//
// public ResultEntry() {
//
// }
//
// public ResultEntry(String sha1) {
// super();
// this.sha1 = sha1;
// }
//
// public String getSha1() {
// return this.sha1;
// }
//
// public void setSha1(String sha1) {
// this.sha1 = sha1;
// }
//
// }
// Path: src/test/java/com/antelink/sourcesquare/query/AntepediaQueryIT.java
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import com.antelink.sourcesquare.query.AntepediaQuery;
import com.antelink.sourcesquare.query.ResultEntry;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.util.HashMap;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.query;
public class AntepediaQueryIT {
private AntepediaQuery query;
@Before
public void init() {
this.query = new AntepediaQuery();
}
@Test
public void testAnswerNotFound() throws Exception {
Map<String, String> files = new HashMap<String, String>();
files.put("toto", "632a990d82e7381e7afeeb3478342d17e9dfb835"); | List<ResultEntry> results = this.query.getResults(files); |
antelink/SourceSquare | src/main/java/com/antelink/sourcesquare/server/ServerController.java | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/StartScanEvent.java
// public class StartScanEvent implements ClientEvent<StartScanEventHandler> {
//
// public static final ClientEventType<StartScanEventHandler> TYPE = new ClientEventType<StartScanEventHandler>();
//
// private final File toScan;
//
// public StartScanEvent(File toScan) {
// this.toScan = toScan;
// }
//
// @Override
// public ClientEventType<StartScanEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(StartScanEventHandler handler) {
// handler.handle(this.toScan);
//
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/StartScanEventHandler.java
// public interface StartScanEventHandler extends ClientEventHandler {
//
// public void handle(File toScan);
//
// }
| import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.StartScanEvent;
import com.antelink.sourcesquare.event.handlers.StartScanEventHandler;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server;
public class ServerController {
public static final String URL = "http://localhost:" + EmbeddedServer.getPort() + "/index.jsp";
private static final Log logger = LogFactory.getLog(ServerController.class);
| // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/StartScanEvent.java
// public class StartScanEvent implements ClientEvent<StartScanEventHandler> {
//
// public static final ClientEventType<StartScanEventHandler> TYPE = new ClientEventType<StartScanEventHandler>();
//
// private final File toScan;
//
// public StartScanEvent(File toScan) {
// this.toScan = toScan;
// }
//
// @Override
// public ClientEventType<StartScanEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(StartScanEventHandler handler) {
// handler.handle(this.toScan);
//
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/StartScanEventHandler.java
// public interface StartScanEventHandler extends ClientEventHandler {
//
// public void handle(File toScan);
//
// }
// Path: src/main/java/com/antelink/sourcesquare/server/ServerController.java
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.StartScanEvent;
import com.antelink.sourcesquare.event.handlers.StartScanEventHandler;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server;
public class ServerController {
public static final String URL = "http://localhost:" + EmbeddedServer.getPort() + "/index.jsp";
private static final Log logger = LogFactory.getLog(ServerController.class);
| public static void bind(final EventBus eventbus) { |
antelink/SourceSquare | src/main/java/com/antelink/sourcesquare/server/ServerController.java | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/StartScanEvent.java
// public class StartScanEvent implements ClientEvent<StartScanEventHandler> {
//
// public static final ClientEventType<StartScanEventHandler> TYPE = new ClientEventType<StartScanEventHandler>();
//
// private final File toScan;
//
// public StartScanEvent(File toScan) {
// this.toScan = toScan;
// }
//
// @Override
// public ClientEventType<StartScanEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(StartScanEventHandler handler) {
// handler.handle(this.toScan);
//
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/StartScanEventHandler.java
// public interface StartScanEventHandler extends ClientEventHandler {
//
// public void handle(File toScan);
//
// }
| import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.StartScanEvent;
import com.antelink.sourcesquare.event.handlers.StartScanEventHandler;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server;
public class ServerController {
public static final String URL = "http://localhost:" + EmbeddedServer.getPort() + "/index.jsp";
private static final Log logger = LogFactory.getLog(ServerController.class);
public static void bind(final EventBus eventbus) { | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/StartScanEvent.java
// public class StartScanEvent implements ClientEvent<StartScanEventHandler> {
//
// public static final ClientEventType<StartScanEventHandler> TYPE = new ClientEventType<StartScanEventHandler>();
//
// private final File toScan;
//
// public StartScanEvent(File toScan) {
// this.toScan = toScan;
// }
//
// @Override
// public ClientEventType<StartScanEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(StartScanEventHandler handler) {
// handler.handle(this.toScan);
//
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/StartScanEventHandler.java
// public interface StartScanEventHandler extends ClientEventHandler {
//
// public void handle(File toScan);
//
// }
// Path: src/main/java/com/antelink/sourcesquare/server/ServerController.java
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.StartScanEvent;
import com.antelink.sourcesquare.event.handlers.StartScanEventHandler;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server;
public class ServerController {
public static final String URL = "http://localhost:" + EmbeddedServer.getPort() + "/index.jsp";
private static final Log logger = LogFactory.getLog(ServerController.class);
public static void bind(final EventBus eventbus) { | eventbus.addHandler(StartScanEvent.TYPE, new StartScanEventHandler() { |
antelink/SourceSquare | src/main/java/com/antelink/sourcesquare/server/ServerController.java | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/StartScanEvent.java
// public class StartScanEvent implements ClientEvent<StartScanEventHandler> {
//
// public static final ClientEventType<StartScanEventHandler> TYPE = new ClientEventType<StartScanEventHandler>();
//
// private final File toScan;
//
// public StartScanEvent(File toScan) {
// this.toScan = toScan;
// }
//
// @Override
// public ClientEventType<StartScanEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(StartScanEventHandler handler) {
// handler.handle(this.toScan);
//
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/StartScanEventHandler.java
// public interface StartScanEventHandler extends ClientEventHandler {
//
// public void handle(File toScan);
//
// }
| import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.StartScanEvent;
import com.antelink.sourcesquare.event.handlers.StartScanEventHandler;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server;
public class ServerController {
public static final String URL = "http://localhost:" + EmbeddedServer.getPort() + "/index.jsp";
private static final Log logger = LogFactory.getLog(ServerController.class);
public static void bind(final EventBus eventbus) { | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/StartScanEvent.java
// public class StartScanEvent implements ClientEvent<StartScanEventHandler> {
//
// public static final ClientEventType<StartScanEventHandler> TYPE = new ClientEventType<StartScanEventHandler>();
//
// private final File toScan;
//
// public StartScanEvent(File toScan) {
// this.toScan = toScan;
// }
//
// @Override
// public ClientEventType<StartScanEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(StartScanEventHandler handler) {
// handler.handle(this.toScan);
//
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/StartScanEventHandler.java
// public interface StartScanEventHandler extends ClientEventHandler {
//
// public void handle(File toScan);
//
// }
// Path: src/main/java/com/antelink/sourcesquare/server/ServerController.java
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.StartScanEvent;
import com.antelink.sourcesquare.event.handlers.StartScanEventHandler;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server;
public class ServerController {
public static final String URL = "http://localhost:" + EmbeddedServer.getPort() + "/index.jsp";
private static final Log logger = LogFactory.getLog(ServerController.class);
public static void bind(final EventBus eventbus) { | eventbus.addHandler(StartScanEvent.TYPE, new StartScanEventHandler() { |
antelink/SourceSquare | src/main/java/com/antelink/sourcesquare/badge/BadgesProcessor.java | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/FilesIdentifiedEvent.java
// public class FilesIdentifiedEvent implements ClientEvent<FilesIdentifiedEventHandler> {
//
// public static final ClientEventType<FilesIdentifiedEventHandler> TYPE = new ClientEventType<FilesIdentifiedEventHandler>();
//
// private final TreeSet<File> fileSet;
//
// public FilesIdentifiedEvent(TreeSet<File> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<FilesIdentifiedEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(FilesIdentifiedEventHandler handler) {
// handler.handle(this.fileSet);
//
// }
//
// public TreeSet<File> getFileSet() {
// return this.fileSet;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/HiddenFileFoundEvent.java
// public class HiddenFileFoundEvent implements ClientEvent<HiddenFileFoundEventHandler> {
//
// public static final ClientEventType<HiddenFileFoundEventHandler> TYPE = new ClientEventType<HiddenFileFoundEventHandler>();
// private File file;
//
// public HiddenFileFoundEvent(File file) {
// this.file = file;
// }
//
// @Override
// public ClientEventType<HiddenFileFoundEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(HiddenFileFoundEventHandler handler) {
// handler.handle(this.file);
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/OSFilesFoundEvent.java
// public class OSFilesFoundEvent implements ClientEvent<OSFilesFoundEventHandler> {
//
// public static final ClientEventType<OSFilesFoundEventHandler> TYPE = new ClientEventType<OSFilesFoundEventHandler>();
//
// private final Set<String> fileSet;
//
// public OSFilesFoundEvent(Set<String> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<OSFilesFoundEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(OSFilesFoundEventHandler handler) {
// handler.handle(this.fileSet);
// }
//
// public Set<String> getFileSet() {
// return this.fileSet;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/FilesIdentifiedEventHandler.java
// public interface FilesIdentifiedEventHandler extends ClientEventHandler {
//
// public void handle(TreeSet<File> fileSet);
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/HiddenFileFoundEventHandler.java
// public interface HiddenFileFoundEventHandler extends ClientEventHandler {
//
// void handle(File file);
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/OSFilesFoundEventHandler.java
// public interface OSFilesFoundEventHandler extends ClientEventHandler {
//
// public void handle(Set<String> fileSet);
//
// }
| import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.FilesIdentifiedEvent;
import com.antelink.sourcesquare.event.events.HiddenFileFoundEvent;
import com.antelink.sourcesquare.event.events.OSFilesFoundEvent;
import com.antelink.sourcesquare.event.handlers.FilesIdentifiedEventHandler;
import com.antelink.sourcesquare.event.handlers.HiddenFileFoundEventHandler;
import com.antelink.sourcesquare.event.handlers.OSFilesFoundEventHandler;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet; | {
add("png");
add("jpeg");
add("jpg");
add("bmp");
add("gif");
add("psd");
add("tif");
add("pcd");
add("pct");
add("pcx");
add("pdf");
add("pds");
add("pic");
add("pict");
add("ps");
add("psid");
add("psp");
add("pub");
add("pif");
add("pit");
add("pnt");
}
};
public BadgesProcessor(EventBus eventBus) {
this.eventBus = eventBus;
}
public void bind() { | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/FilesIdentifiedEvent.java
// public class FilesIdentifiedEvent implements ClientEvent<FilesIdentifiedEventHandler> {
//
// public static final ClientEventType<FilesIdentifiedEventHandler> TYPE = new ClientEventType<FilesIdentifiedEventHandler>();
//
// private final TreeSet<File> fileSet;
//
// public FilesIdentifiedEvent(TreeSet<File> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<FilesIdentifiedEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(FilesIdentifiedEventHandler handler) {
// handler.handle(this.fileSet);
//
// }
//
// public TreeSet<File> getFileSet() {
// return this.fileSet;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/HiddenFileFoundEvent.java
// public class HiddenFileFoundEvent implements ClientEvent<HiddenFileFoundEventHandler> {
//
// public static final ClientEventType<HiddenFileFoundEventHandler> TYPE = new ClientEventType<HiddenFileFoundEventHandler>();
// private File file;
//
// public HiddenFileFoundEvent(File file) {
// this.file = file;
// }
//
// @Override
// public ClientEventType<HiddenFileFoundEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(HiddenFileFoundEventHandler handler) {
// handler.handle(this.file);
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/OSFilesFoundEvent.java
// public class OSFilesFoundEvent implements ClientEvent<OSFilesFoundEventHandler> {
//
// public static final ClientEventType<OSFilesFoundEventHandler> TYPE = new ClientEventType<OSFilesFoundEventHandler>();
//
// private final Set<String> fileSet;
//
// public OSFilesFoundEvent(Set<String> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<OSFilesFoundEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(OSFilesFoundEventHandler handler) {
// handler.handle(this.fileSet);
// }
//
// public Set<String> getFileSet() {
// return this.fileSet;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/FilesIdentifiedEventHandler.java
// public interface FilesIdentifiedEventHandler extends ClientEventHandler {
//
// public void handle(TreeSet<File> fileSet);
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/HiddenFileFoundEventHandler.java
// public interface HiddenFileFoundEventHandler extends ClientEventHandler {
//
// void handle(File file);
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/OSFilesFoundEventHandler.java
// public interface OSFilesFoundEventHandler extends ClientEventHandler {
//
// public void handle(Set<String> fileSet);
//
// }
// Path: src/main/java/com/antelink/sourcesquare/badge/BadgesProcessor.java
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.FilesIdentifiedEvent;
import com.antelink.sourcesquare.event.events.HiddenFileFoundEvent;
import com.antelink.sourcesquare.event.events.OSFilesFoundEvent;
import com.antelink.sourcesquare.event.handlers.FilesIdentifiedEventHandler;
import com.antelink.sourcesquare.event.handlers.HiddenFileFoundEventHandler;
import com.antelink.sourcesquare.event.handlers.OSFilesFoundEventHandler;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
{
add("png");
add("jpeg");
add("jpg");
add("bmp");
add("gif");
add("psd");
add("tif");
add("pcd");
add("pct");
add("pcx");
add("pdf");
add("pds");
add("pic");
add("pict");
add("ps");
add("psid");
add("psp");
add("pub");
add("pif");
add("pit");
add("pnt");
}
};
public BadgesProcessor(EventBus eventBus) {
this.eventBus = eventBus;
}
public void bind() { | this.eventBus.addHandler(FilesIdentifiedEvent.TYPE, new FilesIdentifiedEventHandler() { |
antelink/SourceSquare | src/main/java/com/antelink/sourcesquare/badge/BadgesProcessor.java | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/FilesIdentifiedEvent.java
// public class FilesIdentifiedEvent implements ClientEvent<FilesIdentifiedEventHandler> {
//
// public static final ClientEventType<FilesIdentifiedEventHandler> TYPE = new ClientEventType<FilesIdentifiedEventHandler>();
//
// private final TreeSet<File> fileSet;
//
// public FilesIdentifiedEvent(TreeSet<File> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<FilesIdentifiedEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(FilesIdentifiedEventHandler handler) {
// handler.handle(this.fileSet);
//
// }
//
// public TreeSet<File> getFileSet() {
// return this.fileSet;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/HiddenFileFoundEvent.java
// public class HiddenFileFoundEvent implements ClientEvent<HiddenFileFoundEventHandler> {
//
// public static final ClientEventType<HiddenFileFoundEventHandler> TYPE = new ClientEventType<HiddenFileFoundEventHandler>();
// private File file;
//
// public HiddenFileFoundEvent(File file) {
// this.file = file;
// }
//
// @Override
// public ClientEventType<HiddenFileFoundEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(HiddenFileFoundEventHandler handler) {
// handler.handle(this.file);
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/OSFilesFoundEvent.java
// public class OSFilesFoundEvent implements ClientEvent<OSFilesFoundEventHandler> {
//
// public static final ClientEventType<OSFilesFoundEventHandler> TYPE = new ClientEventType<OSFilesFoundEventHandler>();
//
// private final Set<String> fileSet;
//
// public OSFilesFoundEvent(Set<String> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<OSFilesFoundEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(OSFilesFoundEventHandler handler) {
// handler.handle(this.fileSet);
// }
//
// public Set<String> getFileSet() {
// return this.fileSet;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/FilesIdentifiedEventHandler.java
// public interface FilesIdentifiedEventHandler extends ClientEventHandler {
//
// public void handle(TreeSet<File> fileSet);
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/HiddenFileFoundEventHandler.java
// public interface HiddenFileFoundEventHandler extends ClientEventHandler {
//
// void handle(File file);
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/OSFilesFoundEventHandler.java
// public interface OSFilesFoundEventHandler extends ClientEventHandler {
//
// public void handle(Set<String> fileSet);
//
// }
| import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.FilesIdentifiedEvent;
import com.antelink.sourcesquare.event.events.HiddenFileFoundEvent;
import com.antelink.sourcesquare.event.events.OSFilesFoundEvent;
import com.antelink.sourcesquare.event.handlers.FilesIdentifiedEventHandler;
import com.antelink.sourcesquare.event.handlers.HiddenFileFoundEventHandler;
import com.antelink.sourcesquare.event.handlers.OSFilesFoundEventHandler;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet; | {
add("png");
add("jpeg");
add("jpg");
add("bmp");
add("gif");
add("psd");
add("tif");
add("pcd");
add("pct");
add("pcx");
add("pdf");
add("pds");
add("pic");
add("pict");
add("ps");
add("psid");
add("psp");
add("pub");
add("pif");
add("pit");
add("pnt");
}
};
public BadgesProcessor(EventBus eventBus) {
this.eventBus = eventBus;
}
public void bind() { | // Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/FilesIdentifiedEvent.java
// public class FilesIdentifiedEvent implements ClientEvent<FilesIdentifiedEventHandler> {
//
// public static final ClientEventType<FilesIdentifiedEventHandler> TYPE = new ClientEventType<FilesIdentifiedEventHandler>();
//
// private final TreeSet<File> fileSet;
//
// public FilesIdentifiedEvent(TreeSet<File> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<FilesIdentifiedEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(FilesIdentifiedEventHandler handler) {
// handler.handle(this.fileSet);
//
// }
//
// public TreeSet<File> getFileSet() {
// return this.fileSet;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/HiddenFileFoundEvent.java
// public class HiddenFileFoundEvent implements ClientEvent<HiddenFileFoundEventHandler> {
//
// public static final ClientEventType<HiddenFileFoundEventHandler> TYPE = new ClientEventType<HiddenFileFoundEventHandler>();
// private File file;
//
// public HiddenFileFoundEvent(File file) {
// this.file = file;
// }
//
// @Override
// public ClientEventType<HiddenFileFoundEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(HiddenFileFoundEventHandler handler) {
// handler.handle(this.file);
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/events/OSFilesFoundEvent.java
// public class OSFilesFoundEvent implements ClientEvent<OSFilesFoundEventHandler> {
//
// public static final ClientEventType<OSFilesFoundEventHandler> TYPE = new ClientEventType<OSFilesFoundEventHandler>();
//
// private final Set<String> fileSet;
//
// public OSFilesFoundEvent(Set<String> fileSet) {
// this.fileSet = fileSet;
// }
//
// @Override
// public ClientEventType<OSFilesFoundEventHandler> getHandlerType() {
// return TYPE;
// }
//
// @Override
// public void dispatch(OSFilesFoundEventHandler handler) {
// handler.handle(this.fileSet);
// }
//
// public Set<String> getFileSet() {
// return this.fileSet;
// }
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/FilesIdentifiedEventHandler.java
// public interface FilesIdentifiedEventHandler extends ClientEventHandler {
//
// public void handle(TreeSet<File> fileSet);
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/HiddenFileFoundEventHandler.java
// public interface HiddenFileFoundEventHandler extends ClientEventHandler {
//
// void handle(File file);
//
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/handlers/OSFilesFoundEventHandler.java
// public interface OSFilesFoundEventHandler extends ClientEventHandler {
//
// public void handle(Set<String> fileSet);
//
// }
// Path: src/main/java/com/antelink/sourcesquare/badge/BadgesProcessor.java
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.event.events.FilesIdentifiedEvent;
import com.antelink.sourcesquare.event.events.HiddenFileFoundEvent;
import com.antelink.sourcesquare.event.events.OSFilesFoundEvent;
import com.antelink.sourcesquare.event.handlers.FilesIdentifiedEventHandler;
import com.antelink.sourcesquare.event.handlers.HiddenFileFoundEventHandler;
import com.antelink.sourcesquare.event.handlers.OSFilesFoundEventHandler;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
{
add("png");
add("jpeg");
add("jpg");
add("bmp");
add("gif");
add("psd");
add("tif");
add("pcd");
add("pct");
add("pcx");
add("pdf");
add("pds");
add("pic");
add("pict");
add("ps");
add("psid");
add("psp");
add("pub");
add("pif");
add("pit");
add("pnt");
}
};
public BadgesProcessor(EventBus eventBus) {
this.eventBus = eventBus;
}
public void bind() { | this.eventBus.addHandler(FilesIdentifiedEvent.TYPE, new FilesIdentifiedEventHandler() { |
antelink/SourceSquare | src/main/java/com/antelink/sourcesquare/SourceSquareResults.java | // Path: src/main/java/com/antelink/sourcesquare/badge/Badge.java
// public enum Badge {
// OS_SAMURAI("Open Source Samurai", "badge-samurai.png", "More than 80% of your files are open source"),
//
// OS_BLACKBELT("Open Source BlackBelt", "badge-blackbelt.png", "More than 60% of your files are open source"),
//
// OS_TRAINEE("Open Source Trainee", "badge-trainee.png", "More than 40% of your files are open source"),
//
// OS_WHAT("Open What?", "badge-openwhat.png", "Less than 40% of your files are open source"),
//
// OS_CLEAR("It's All Clear Capitain", "badge-clearcaptain.png", "You have no open source files"),
//
// SVN("Subversive Activity", "badge-svn.png", "You use Subversion"),
//
// GIT("Rebase yourself", "badge-git.png", "You use Git"),
//
// CVS("CVS Nostalgia", "badge-cvs.png", "You use CVS"),
//
// JAVA("Coffee maker", "badge-java.png", "More than 20% of your files are java/scala files"),
//
// C("Malloc Friend", "badge-c.png", "More than 20% of your files are c/c++ language files"),
//
// PERL("Perl Monger", "badge-perl.png", "More than 20% of your files are perl files"),
//
// EXECUTOR("Executor", "badge-executor.png", "More than 25% of your files are executable files"),
//
// OLD("Old Timer", "badge-old.png", "More than 20% of your files are cobol or fortran files"),
//
// PICASSO("Picasso Wannabe", "badge-picasso.png", "More than 25% of your files are images"),
//
// SCRIPT("Scripting paradise", "badge-scripting.png", "More than 20% of your files are script files (sh, php, ruby, python, csh, bat)"),
//
// SHAKER("Language Shaker", "badge-shaker.png", "You use more than 3 programming languages");
//
// /**
// * image alt description
// */
// private String alt;
// /**
// * image system path
// */
// private String path;
// /**
// * image toolTip
// */
// private String toolTip;
//
// private Badge(String alt, String path, String toolTip) {
// this.alt = alt;
// this.path = path;
// this.toolTip = toolTip;
// }
//
// public String getAlt() {
// return this.alt;
// }
//
// public String getPath() {
// return this.path;
// }
//
// public String getToolTip() {
// return this.toolTip;
// }
//
// public void setToolTip(String toolTip) {
// this.toolTip = toolTip;
// }
//
// }
| import java.util.Collection;
import com.antelink.sourcesquare.badge.Badge; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare;
public class SourceSquareResults {
private TreemapNode rootNode;
| // Path: src/main/java/com/antelink/sourcesquare/badge/Badge.java
// public enum Badge {
// OS_SAMURAI("Open Source Samurai", "badge-samurai.png", "More than 80% of your files are open source"),
//
// OS_BLACKBELT("Open Source BlackBelt", "badge-blackbelt.png", "More than 60% of your files are open source"),
//
// OS_TRAINEE("Open Source Trainee", "badge-trainee.png", "More than 40% of your files are open source"),
//
// OS_WHAT("Open What?", "badge-openwhat.png", "Less than 40% of your files are open source"),
//
// OS_CLEAR("It's All Clear Capitain", "badge-clearcaptain.png", "You have no open source files"),
//
// SVN("Subversive Activity", "badge-svn.png", "You use Subversion"),
//
// GIT("Rebase yourself", "badge-git.png", "You use Git"),
//
// CVS("CVS Nostalgia", "badge-cvs.png", "You use CVS"),
//
// JAVA("Coffee maker", "badge-java.png", "More than 20% of your files are java/scala files"),
//
// C("Malloc Friend", "badge-c.png", "More than 20% of your files are c/c++ language files"),
//
// PERL("Perl Monger", "badge-perl.png", "More than 20% of your files are perl files"),
//
// EXECUTOR("Executor", "badge-executor.png", "More than 25% of your files are executable files"),
//
// OLD("Old Timer", "badge-old.png", "More than 20% of your files are cobol or fortran files"),
//
// PICASSO("Picasso Wannabe", "badge-picasso.png", "More than 25% of your files are images"),
//
// SCRIPT("Scripting paradise", "badge-scripting.png", "More than 20% of your files are script files (sh, php, ruby, python, csh, bat)"),
//
// SHAKER("Language Shaker", "badge-shaker.png", "You use more than 3 programming languages");
//
// /**
// * image alt description
// */
// private String alt;
// /**
// * image system path
// */
// private String path;
// /**
// * image toolTip
// */
// private String toolTip;
//
// private Badge(String alt, String path, String toolTip) {
// this.alt = alt;
// this.path = path;
// this.toolTip = toolTip;
// }
//
// public String getAlt() {
// return this.alt;
// }
//
// public String getPath() {
// return this.path;
// }
//
// public String getToolTip() {
// return this.toolTip;
// }
//
// public void setToolTip(String toolTip) {
// this.toolTip = toolTip;
// }
//
// }
// Path: src/main/java/com/antelink/sourcesquare/SourceSquareResults.java
import java.util.Collection;
import com.antelink.sourcesquare.badge.Badge;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare;
public class SourceSquareResults {
private TreemapNode rootNode;
| private Collection<Badge> badges; |
antelink/SourceSquare | src/main/java/com/antelink/sourcesquare/server/servlet/FeedbackServlet.java | // Path: src/main/java/com/antelink/sourcesquare/SourceSquareResults.java
// public class SourceSquareResults {
//
// private TreemapNode rootNode;
//
// private Collection<Badge> badges;
//
// private int nodeLevel;
//
// public SourceSquareResults() {
// super();
// }
//
// public TreemapNode getRootNode() {
// return this.rootNode;
// }
//
// public void setRootNode(TreemapNode rootNode) {
// this.rootNode = rootNode;
// }
//
// public Collection<Badge> getBadges() {
// return this.badges;
// }
//
// public void setBadges(Collection<Badge> badges) {
// this.badges = badges;
// }
//
// public int getNodeLevel() {
// return this.nodeLevel;
// }
//
// public void setNodeLevel(int nodeLevel) {
// this.nodeLevel = nodeLevel;
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/query/PublishmentClient.java
// public class PublishmentClient extends RestClient {
//
// private final static Log logger = LogFactory.getLog(PublishmentClient.class);
//
// private static final String SOURCESQUARE_SERVER_DOMAIN = System.getProperty(
// "sourcesquare.domain", "sourcesquare.antepedia.com");
//
// Gson gson = new Gson();
//
// public void publish(Feedback feedback) {
// RestTemplate template = getTemplate(SOURCESQUARE_SERVER_DOMAIN);
// String url = "https://" + SOURCESQUARE_SERVER_DOMAIN + "/service/store/feedback";
// logger.info(url);
// try{
// template.postForObject(url, feedback, Boolean.class);
// }
// catch(Throwable t){
// logger.error("Error sending feedback",t);
// }
// }
//
// public String publish(SourceSquareResults results) {
// RestTemplate template = getTemplate(SOURCESQUARE_SERVER_DOMAIN);
//
// String request = this.gson.toJson(cleanResults(results));
// String url = "https://" + SOURCESQUARE_SERVER_DOMAIN + "/publish";
// logger.info(url);
// return template.postForObject(url, request, String.class);
// }
//
// private SourceSquareResults cleanResults(SourceSquareResults results) {
// SourceSquareResults nresults = new SourceSquareResults();
// nresults.setBadges(results.getBadges());
// String tree = this.gson.toJson(results.getRootNode());
// TreemapNode copy = this.gson.fromJson(tree, TreemapNode.class);
// copy.clean();
// nresults.setRootNode(copy);
// nresults.setNodeLevel(results.getNodeLevel());
// return nresults;
// }
//
// }
| import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.antelink.sourcesquare.SourceSquareResults;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.query.PublishmentClient;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; | /**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server.servlet;
public class FeedbackServlet extends HttpServlet {
private static final Log logger = LogFactory.getLog(FeedbackServlet.class);
| // Path: src/main/java/com/antelink/sourcesquare/SourceSquareResults.java
// public class SourceSquareResults {
//
// private TreemapNode rootNode;
//
// private Collection<Badge> badges;
//
// private int nodeLevel;
//
// public SourceSquareResults() {
// super();
// }
//
// public TreemapNode getRootNode() {
// return this.rootNode;
// }
//
// public void setRootNode(TreemapNode rootNode) {
// this.rootNode = rootNode;
// }
//
// public Collection<Badge> getBadges() {
// return this.badges;
// }
//
// public void setBadges(Collection<Badge> badges) {
// this.badges = badges;
// }
//
// public int getNodeLevel() {
// return this.nodeLevel;
// }
//
// public void setNodeLevel(int nodeLevel) {
// this.nodeLevel = nodeLevel;
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/event/base/EventBus.java
// public class EventBus {
//
// private static final Log logger = LogFactory.getLog(EventBus.class);
//
// HashMap<ClientEventType<?>, List<? extends ClientEventHandler>> eventMap = new HashMap<ClientEventType<?>, List<? extends ClientEventHandler>>();
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void addHandler(ClientEventType<T> eventType, T handler) {
// if (!this.eventMap.containsKey(eventType)) {
// this.eventMap.put(eventType, new ArrayList<T>());
// }
// ((ArrayList<T>) this.eventMap.get(eventType)).add(0, handler);
// }
//
// @SuppressWarnings("unchecked")
// public <T extends ClientEventHandler> void fireEvent(final ClientEvent<T> event) {
// if (!this.eventMap.containsKey(event.getHandlerType())) {
// return;
// }
// for (final ClientEventHandler handler : this.eventMap.get(event.getHandlerType())) {
// try {
// Runnable runner = new Runnable() {
//
// @Override
// public void run() {
// event.dispatch((T) handler);
//
// }
// };
//
// Thread thread = new Thread(runner);
// thread.start();
//
// logger.trace("event dispatched to the handler " + handler.getId());
// } catch (Exception e) {
// logger.error("An event could not be dispatched to the handler " + handler.getId(), e);
// }
// }
// }
// }
//
// Path: src/main/java/com/antelink/sourcesquare/query/PublishmentClient.java
// public class PublishmentClient extends RestClient {
//
// private final static Log logger = LogFactory.getLog(PublishmentClient.class);
//
// private static final String SOURCESQUARE_SERVER_DOMAIN = System.getProperty(
// "sourcesquare.domain", "sourcesquare.antepedia.com");
//
// Gson gson = new Gson();
//
// public void publish(Feedback feedback) {
// RestTemplate template = getTemplate(SOURCESQUARE_SERVER_DOMAIN);
// String url = "https://" + SOURCESQUARE_SERVER_DOMAIN + "/service/store/feedback";
// logger.info(url);
// try{
// template.postForObject(url, feedback, Boolean.class);
// }
// catch(Throwable t){
// logger.error("Error sending feedback",t);
// }
// }
//
// public String publish(SourceSquareResults results) {
// RestTemplate template = getTemplate(SOURCESQUARE_SERVER_DOMAIN);
//
// String request = this.gson.toJson(cleanResults(results));
// String url = "https://" + SOURCESQUARE_SERVER_DOMAIN + "/publish";
// logger.info(url);
// return template.postForObject(url, request, String.class);
// }
//
// private SourceSquareResults cleanResults(SourceSquareResults results) {
// SourceSquareResults nresults = new SourceSquareResults();
// nresults.setBadges(results.getBadges());
// String tree = this.gson.toJson(results.getRootNode());
// TreemapNode copy = this.gson.fromJson(tree, TreemapNode.class);
// copy.clean();
// nresults.setRootNode(copy);
// nresults.setNodeLevel(results.getNodeLevel());
// return nresults;
// }
//
// }
// Path: src/main/java/com/antelink/sourcesquare/server/servlet/FeedbackServlet.java
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.antelink.sourcesquare.SourceSquareResults;
import com.antelink.sourcesquare.event.base.EventBus;
import com.antelink.sourcesquare.query.PublishmentClient;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
/**
* Copyright (C) 2009-2012 Antelink SAS
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License Version 3 as published
* by the Free Software Foundation.
*
* This program 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 Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version
* 3 along with this program. If not, see http://www.gnu.org/licenses/agpl.html
*
* Additional permission under GNU AGPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it with
* Eclipse Java development tools (JDT) or Jetty (or a modified version of these
* libraries), containing parts covered by the terms of Eclipse Public License 1.0,
* the licensors of this Program grant you additional permission to convey the
* resulting work. Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of Eclipse Java development tools
* (JDT) or Jetty used as well as that of the covered work.
*/
package com.antelink.sourcesquare.server.servlet;
public class FeedbackServlet extends HttpServlet {
private static final Log logger = LogFactory.getLog(FeedbackServlet.class);
| private final PublishmentClient server = new PublishmentClient(); |
2cloud/android2cloud | src/com/suchagit/android2cloud/errors/OAuthCommunicationExceptionDialogFragment.java | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods; | final String account = getArguments().getString("account");
final String verifier = getArguments().getString("verifier");
final String requestUrl = getArguments().getString("request_url");
final String responseBody = getArguments().getString("response_body");
return new AlertDialog.Builder(getActivity())
.setCancelable(false)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
getActivity().finish();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Account: " + account +"\n";
message += "Host: " + host + "\n";
if(requestUrl != null)
message += "Request URL: " + requestUrl + "\n";
else if(verifier != null)
message += "Verifier: " + verifier + "\n";
message += "Response Body: \n";
message += responseBody + "\n";
message += "Stacktrace: \n";
message += stacktrace + "\n"; | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
// Path: src/com/suchagit/android2cloud/errors/OAuthCommunicationExceptionDialogFragment.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods;
final String account = getArguments().getString("account");
final String verifier = getArguments().getString("verifier");
final String requestUrl = getArguments().getString("request_url");
final String responseBody = getArguments().getString("response_body");
return new AlertDialog.Builder(getActivity())
.setCancelable(false)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
getActivity().finish();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Account: " + account +"\n";
message += "Host: " + host + "\n";
if(requestUrl != null)
message += "Request URL: " + requestUrl + "\n";
else if(verifier != null)
message += "Verifier: " + verifier + "\n";
message += "Response Body: \n";
message += responseBody + "\n";
message += "Stacktrace: \n";
message += stacktrace + "\n"; | Intent report = ErrorMethods.getEmailIntent(OAuthCommunicationExceptionDialogFragment.this, "oauth_communication_exception_error", message); |
2cloud/android2cloud | src/com/suchagit/android2cloud/errors/IllegalArgumentExceptionDialogFragment.java | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
| import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment; | @Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = R.string.default_error_title;
int body = R.string.illegal_argument_exception_error;
int yesButton = R.string.default_error_ok;
int noButton = R.string.report_error_button;
final String host = getArguments().getString("host");
final String request_host = getArguments().getString("request_host");
final String request_type = getArguments().getString("request_type");
final String stacktrace = getArguments().getString("stacktrace");
return new AlertDialog.Builder(getActivity())
.setCancelable(true)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Host: " + host + "\n";
message += "Request Host: " + request_host + "\n";
message += "Request Type: " + request_type + "\n";
message += "Stacktrace: " + stacktrace + "\n"; | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
// Path: src/com/suchagit/android2cloud/errors/IllegalArgumentExceptionDialogFragment.java
import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = R.string.default_error_title;
int body = R.string.illegal_argument_exception_error;
int yesButton = R.string.default_error_ok;
int noButton = R.string.report_error_button;
final String host = getArguments().getString("host");
final String request_host = getArguments().getString("request_host");
final String request_type = getArguments().getString("request_type");
final String stacktrace = getArguments().getString("stacktrace");
return new AlertDialog.Builder(getActivity())
.setCancelable(true)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Host: " + host + "\n";
message += "Request Host: " + request_host + "\n";
message += "Request Type: " + request_type + "\n";
message += "Stacktrace: " + stacktrace + "\n"; | Intent report = ErrorMethods.getEmailIntent(IllegalArgumentExceptionDialogFragment.this, "illegal_argument_exception_error", message); |
2cloud/android2cloud | src/com/suchagit/android2cloud/errors/OAuthMessageSignerExceptionDialogFragment.java | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods; |
final String stacktrace = getArguments().getString("stacktrace");
final String host = getArguments().getString("host");
final String account = getArguments().getString("account");
final String verifier = getArguments().getString("verifier");
final String requestUrl = getArguments().getString("request_url");
return new AlertDialog.Builder(getActivity())
.setCancelable(false)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
getActivity().finish();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Account: " + account +"\n";
message += "Host: " + host + "\n";
if(requestUrl != null)
message += "Request URL: " + requestUrl + "\n";
else if(verifier != null)
message += "Verifier: " + verifier + "\n";
message += "Stacktrace: \n";
message += stacktrace + "\n"; | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
// Path: src/com/suchagit/android2cloud/errors/OAuthMessageSignerExceptionDialogFragment.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods;
final String stacktrace = getArguments().getString("stacktrace");
final String host = getArguments().getString("host");
final String account = getArguments().getString("account");
final String verifier = getArguments().getString("verifier");
final String requestUrl = getArguments().getString("request_url");
return new AlertDialog.Builder(getActivity())
.setCancelable(false)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
getActivity().finish();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Account: " + account +"\n";
message += "Host: " + host + "\n";
if(requestUrl != null)
message += "Request URL: " + requestUrl + "\n";
else if(verifier != null)
message += "Verifier: " + verifier + "\n";
message += "Stacktrace: \n";
message += stacktrace + "\n"; | Intent report = ErrorMethods.getEmailIntent(OAuthMessageSignerExceptionDialogFragment.this, "oauth_message_signer_exception_error", message); |
2cloud/android2cloud | src/com/suchagit/android2cloud/errors/OAuthExpectationFailedExceptionDialogFragment.java | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods; |
final String stacktrace = getArguments().getString("stacktrace");
final String host = getArguments().getString("host");
final String account = getArguments().getString("account");
final String verifier = getArguments().getString("verifier");
final String requestUrl = getArguments().getString("request_url");
return new AlertDialog.Builder(getActivity())
.setCancelable(false)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
getActivity().finish();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Account: " + account +"\n";
message += "Host: " + host + "\n";
if(requestUrl != null)
message += "Request URL: " + requestUrl + "\n";
else if(verifier != null)
message += "Verifier: " + verifier + "\n";
message += "Stacktrace: \n";
message += stacktrace + "\n"; | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
// Path: src/com/suchagit/android2cloud/errors/OAuthExpectationFailedExceptionDialogFragment.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods;
final String stacktrace = getArguments().getString("stacktrace");
final String host = getArguments().getString("host");
final String account = getArguments().getString("account");
final String verifier = getArguments().getString("verifier");
final String requestUrl = getArguments().getString("request_url");
return new AlertDialog.Builder(getActivity())
.setCancelable(false)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
getActivity().finish();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Account: " + account +"\n";
message += "Host: " + host + "\n";
if(requestUrl != null)
message += "Request URL: " + requestUrl + "\n";
else if(verifier != null)
message += "Verifier: " + verifier + "\n";
message += "Stacktrace: \n";
message += stacktrace + "\n"; | Intent report = ErrorMethods.getEmailIntent(OAuthExpectationFailedExceptionDialogFragment.this, "oauth_expectation_failed_exception_error", message); |
2cloud/android2cloud | src/com/suchagit/android2cloud/errors/IllegalStateExceptionDialogFragment.java | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
| import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment; | @Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = R.string.default_error_title;
int body = R.string.illegal_state_exception_error;
int yesButton = R.string.default_error_ok;
int noButton = R.string.report_error_button;
final String host = getArguments().getString("host");
final String request_host = getArguments().getString("request_host");
final String request_type = getArguments().getString("request_type");
final String stacktrace = getArguments().getString("stacktrace");
return new AlertDialog.Builder(getActivity())
.setCancelable(true)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Host: " + host + "\n";
message += "Request Host: " + request_host + "\n";
message += "Request Type: " + request_type + "\n";
message += "Stacktrace: " + stacktrace + "\n"; | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
// Path: src/com/suchagit/android2cloud/errors/IllegalStateExceptionDialogFragment.java
import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = R.string.default_error_title;
int body = R.string.illegal_state_exception_error;
int yesButton = R.string.default_error_ok;
int noButton = R.string.report_error_button;
final String host = getArguments().getString("host");
final String request_host = getArguments().getString("request_host");
final String request_type = getArguments().getString("request_type");
final String stacktrace = getArguments().getString("stacktrace");
return new AlertDialog.Builder(getActivity())
.setCancelable(true)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Host: " + host + "\n";
message += "Request Host: " + request_host + "\n";
message += "Request Type: " + request_type + "\n";
message += "Stacktrace: " + stacktrace + "\n"; | Intent report = ErrorMethods.getEmailIntent(IllegalStateExceptionDialogFragment.this, "illegal_state_exception_error", message); |
2cloud/android2cloud | src/com/suchagit/android2cloud/Preferences.java | // Path: src/com/suchagit/android2cloud/util/OAuthAccount.java
// public class OAuthAccount {
// private String account;
// private String host;
// private String token;
// private String key;
//
// public void setAccount(String newAccount) {
// this.account = newAccount;
// }
//
// public String getAccount() {
// return this.account;
// }
//
// public void setHost(String newHost) {
// this.host = newHost;
// }
//
// public String getHost() {
// return this.host;
// }
//
// public void setToken(String newToken) {
// this.token = newToken;
// }
//
// public String getToken() {
// return this.token;
// }
//
// public void setKey(String newKey) {
// this.key = newKey;
// }
//
// public String getKey() {
// return this.key;
// }
//
// public OAuthAccount(String account, SharedPreferences preferences) {
// this.setAccount(account);
// this.load(preferences);
// }
// public OAuthAccount(String account, String host, String token, String key) {
// this.setAccount(account);
// this.setHost(host);
// this.setToken(token);
// this.setKey(key);
// }
//
// public OAuthAccount save(SharedPreferences preferences) {
// SharedPreferences.Editor editor = preferences.edit();
// editor.putString("host_"+this.account, this.host);
// editor.putString("oauth_token_"+this.account, this.token);
// editor.putString("oauth_secret_"+this.account, this.key);
// String accounts = preferences.getString("accounts", "|");
// if(accounts.indexOf("|" + this.account + "|") == -1) {
// accounts += this.account + "|";
// }
// editor.putString("accounts", accounts);
// editor.commit();
// return this;
// }
//
// public boolean delete(SharedPreferences preferences) {
// SharedPreferences.Editor editor = preferences.edit();
// editor.remove("host_"+this.account);
// editor.remove("oauth_token_"+this.account);
// editor.remove("oauth_secret_"+this.account);
// String accounts = preferences.getString("accounts", "|"+this.account+"|");
// accounts = accounts.replace("|"+this.account+"|", "|");
// editor.putString("accounts", accounts);
// return editor.commit();
// }
//
// public void load(SharedPreferences preferences) {
// this.setHost(preferences.getString("host_"+this.account, "error"));
// this.setToken(preferences.getString("oauth_token_"+this.account, "error"));
// this.setKey(preferences.getString("oauth_secret_"+this.account, "error"));
// }
//
// public static String[] getAccounts(SharedPreferences preferences) {
// String accountString = preferences.getString("accounts", "|");
// int chopStart = 0;
// int chopEnd = accountString.length();
// if(accountString.charAt(accountString.length() - 1) == '|') {
// chopEnd--;
// }
// if(accountString.charAt(0) == '|') {
// chopStart++;
// }
// if(chopEnd <= chopStart) {
// accountString = "";
// } else {
// accountString = accountString.substring(chopStart, chopEnd);
// }
// return accountString.split("\\|");
// }
// }
| import com.suchagit.android2cloud.util.OAuthAccount;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.Toast; | package com.suchagit.android2cloud;
public class Preferences extends PreferenceActivity implements OnPreferenceChangeListener {
protected String ACCOUNTS_PREFERENCES = "android2cloud-accounts";
protected String SETTINGS_PREFERENCES = "android2cloud-settings";
final int ACCOUNT_LIST_REQ_CODE = 0x1337;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
ListPreference accounts_pref = (ListPreference) findPreference("account");
accounts_pref.setOnPreferenceChangeListener(this);
Preference addNewAccount = (Preference) findPreference("addNewAccount");
addNewAccount.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent i = new Intent(Preferences.this, OAuthActivity.class);
startActivityForResult(i, ACCOUNT_LIST_REQ_CODE);
return true;
}
});
Preference deleteAccount = (Preference) findPreference("deleteAccount");
deleteAccount.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
SharedPreferences accounts = getSharedPreferences("android2cloud-accounts", 0);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); | // Path: src/com/suchagit/android2cloud/util/OAuthAccount.java
// public class OAuthAccount {
// private String account;
// private String host;
// private String token;
// private String key;
//
// public void setAccount(String newAccount) {
// this.account = newAccount;
// }
//
// public String getAccount() {
// return this.account;
// }
//
// public void setHost(String newHost) {
// this.host = newHost;
// }
//
// public String getHost() {
// return this.host;
// }
//
// public void setToken(String newToken) {
// this.token = newToken;
// }
//
// public String getToken() {
// return this.token;
// }
//
// public void setKey(String newKey) {
// this.key = newKey;
// }
//
// public String getKey() {
// return this.key;
// }
//
// public OAuthAccount(String account, SharedPreferences preferences) {
// this.setAccount(account);
// this.load(preferences);
// }
// public OAuthAccount(String account, String host, String token, String key) {
// this.setAccount(account);
// this.setHost(host);
// this.setToken(token);
// this.setKey(key);
// }
//
// public OAuthAccount save(SharedPreferences preferences) {
// SharedPreferences.Editor editor = preferences.edit();
// editor.putString("host_"+this.account, this.host);
// editor.putString("oauth_token_"+this.account, this.token);
// editor.putString("oauth_secret_"+this.account, this.key);
// String accounts = preferences.getString("accounts", "|");
// if(accounts.indexOf("|" + this.account + "|") == -1) {
// accounts += this.account + "|";
// }
// editor.putString("accounts", accounts);
// editor.commit();
// return this;
// }
//
// public boolean delete(SharedPreferences preferences) {
// SharedPreferences.Editor editor = preferences.edit();
// editor.remove("host_"+this.account);
// editor.remove("oauth_token_"+this.account);
// editor.remove("oauth_secret_"+this.account);
// String accounts = preferences.getString("accounts", "|"+this.account+"|");
// accounts = accounts.replace("|"+this.account+"|", "|");
// editor.putString("accounts", accounts);
// return editor.commit();
// }
//
// public void load(SharedPreferences preferences) {
// this.setHost(preferences.getString("host_"+this.account, "error"));
// this.setToken(preferences.getString("oauth_token_"+this.account, "error"));
// this.setKey(preferences.getString("oauth_secret_"+this.account, "error"));
// }
//
// public static String[] getAccounts(SharedPreferences preferences) {
// String accountString = preferences.getString("accounts", "|");
// int chopStart = 0;
// int chopEnd = accountString.length();
// if(accountString.charAt(accountString.length() - 1) == '|') {
// chopEnd--;
// }
// if(accountString.charAt(0) == '|') {
// chopStart++;
// }
// if(chopEnd <= chopStart) {
// accountString = "";
// } else {
// accountString = accountString.substring(chopStart, chopEnd);
// }
// return accountString.split("\\|");
// }
// }
// Path: src/com/suchagit/android2cloud/Preferences.java
import com.suchagit.android2cloud.util.OAuthAccount;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.Toast;
package com.suchagit.android2cloud;
public class Preferences extends PreferenceActivity implements OnPreferenceChangeListener {
protected String ACCOUNTS_PREFERENCES = "android2cloud-accounts";
protected String SETTINGS_PREFERENCES = "android2cloud-settings";
final int ACCOUNT_LIST_REQ_CODE = 0x1337;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
ListPreference accounts_pref = (ListPreference) findPreference("account");
accounts_pref.setOnPreferenceChangeListener(this);
Preference addNewAccount = (Preference) findPreference("addNewAccount");
addNewAccount.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent i = new Intent(Preferences.this, OAuthActivity.class);
startActivityForResult(i, ACCOUNT_LIST_REQ_CODE);
return true;
}
});
Preference deleteAccount = (Preference) findPreference("deleteAccount");
deleteAccount.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
SharedPreferences accounts = getSharedPreferences("android2cloud-accounts", 0);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); | OAuthAccount account = new OAuthAccount(prefs.getString("account", ""), accounts); |
2cloud/android2cloud | src/com/suchagit/android2cloud/errors/OAuthNotAuthorizedExceptionDialogFragment.java | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods; |
final String stacktrace = getArguments().getString("stacktrace");
final String host = getArguments().getString("host");
final String account = getArguments().getString("account");
final String verifier = getArguments().getString("verifier");
final String requestUrl = getArguments().getString("request_url");
return new AlertDialog.Builder(getActivity())
.setCancelable(false)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
getActivity().finish();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Account: " + account +"\n";
message += "Host: " + host + "\n";
if(requestUrl != null)
message += "Request URL: " + requestUrl + "\n";
else if(verifier != null)
message += "Verifier: " + verifier + "\n";
message += "Stacktrace: \n";
message += stacktrace + "\n"; | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
// Path: src/com/suchagit/android2cloud/errors/OAuthNotAuthorizedExceptionDialogFragment.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods;
final String stacktrace = getArguments().getString("stacktrace");
final String host = getArguments().getString("host");
final String account = getArguments().getString("account");
final String verifier = getArguments().getString("verifier");
final String requestUrl = getArguments().getString("request_url");
return new AlertDialog.Builder(getActivity())
.setCancelable(false)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
getActivity().finish();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Account: " + account +"\n";
message += "Host: " + host + "\n";
if(requestUrl != null)
message += "Request URL: " + requestUrl + "\n";
else if(verifier != null)
message += "Verifier: " + verifier + "\n";
message += "Stacktrace: \n";
message += stacktrace + "\n"; | Intent report = ErrorMethods.getEmailIntent(OAuthNotAuthorizedExceptionDialogFragment.this, "oauth_not_authorized_exception_error", message); |
2cloud/android2cloud | src/com/suchagit/android2cloud/OAuthWebView.java | // Path: src/com/suchagit/android2cloud/errors/OAuthWebviewNullIntentDialogFragment.java
// public class OAuthWebviewNullIntentDialogFragment extends DialogFragment {
//
// public static OAuthWebviewNullIntentDialogFragment newInstance() {
// OAuthWebviewNullIntentDialogFragment frag = new OAuthWebviewNullIntentDialogFragment();
// return frag;
// }
//
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState) {
// int title = R.string.default_error_title;
// int body = R.string.oauthwebview_null_intent_error;
// int yesButton = R.string.default_error_ok;
//
// return new AlertDialog.Builder(getActivity())
// .setCancelable(false)
// .setTitle(title)
// .setMessage(body)
// .setPositiveButton(yesButton,
// new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int whichButton) {
// dialog.cancel();
// getActivity().finish();
// }
// }
// )
// .create();
// }
// }
//
// Path: src/com/suchagit/android2cloud/util/OAuth.java
// public class OAuth {
//
// private static OAuthProvider provider;
// private static OAuthConsumer consumer;
//
// private static final String REQUEST_TOKEN_URL = "_ah/OAuthGetRequestToken";
// private static final String ACCESS_TOKEN_URL = "_ah/OAuthGetAccessToken";
// private static final String AUTHORISE_TOKEN_URL = "_ah/OAuthAuthorizeToken?btmpl=mobile";
//
// public static final String CALLBACK = "callback/android/";
// public static final int INTENT_ID = 0x1234;
//
//
// public static OAuthConsumer makeConsumer() {
// return new CommonsHttpOAuthConsumer(HttpClient.CONSUMER_KEY, HttpClient.CONSUMER_SECRET);
// }
//
// public static OAuthProvider makeProvider(String host) {
// String request_token_url = host + REQUEST_TOKEN_URL;
// String access_token_url = host + ACCESS_TOKEN_URL;
// String authorise_token_url = host + AUTHORISE_TOKEN_URL;
// return new CommonsHttpOAuthProvider(request_token_url, access_token_url, authorise_token_url);
// }
//
// public static String getRequestUrl(String host, String account) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException {
// if(consumer == null) {
// consumer = makeConsumer();
// }
//
// if(provider == null) {
// provider = makeProvider(host);
// }
// account = Uri.encode(account);
// String target = provider.retrieveRequestToken(consumer, host+CALLBACK+"?account="+account);
// return target;
// }
//
// public static OAuthConsumer getAccessToken(String host, String verifier) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException {
// if(provider == null) {
// provider = makeProvider(host);
// }
//
// if(consumer == null) {
// consumer = makeConsumer();
// }
// provider.retrieveAccessToken(consumer, verifier);
// return consumer;
// }
// }
| import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.suchagit.android2cloud.errors.OAuthWebviewNullIntentDialogFragment;
import com.suchagit.android2cloud.util.OAuth; | package com.suchagit.android2cloud;
public class OAuthWebView extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
String request_url = "";
if(this.getIntent() != null && this.getIntent().getDataString() != null){
request_url = this.getIntent().getDataString();
} else {
showDialog(R.string.oauthwebview_null_intent_error); | // Path: src/com/suchagit/android2cloud/errors/OAuthWebviewNullIntentDialogFragment.java
// public class OAuthWebviewNullIntentDialogFragment extends DialogFragment {
//
// public static OAuthWebviewNullIntentDialogFragment newInstance() {
// OAuthWebviewNullIntentDialogFragment frag = new OAuthWebviewNullIntentDialogFragment();
// return frag;
// }
//
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState) {
// int title = R.string.default_error_title;
// int body = R.string.oauthwebview_null_intent_error;
// int yesButton = R.string.default_error_ok;
//
// return new AlertDialog.Builder(getActivity())
// .setCancelable(false)
// .setTitle(title)
// .setMessage(body)
// .setPositiveButton(yesButton,
// new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int whichButton) {
// dialog.cancel();
// getActivity().finish();
// }
// }
// )
// .create();
// }
// }
//
// Path: src/com/suchagit/android2cloud/util/OAuth.java
// public class OAuth {
//
// private static OAuthProvider provider;
// private static OAuthConsumer consumer;
//
// private static final String REQUEST_TOKEN_URL = "_ah/OAuthGetRequestToken";
// private static final String ACCESS_TOKEN_URL = "_ah/OAuthGetAccessToken";
// private static final String AUTHORISE_TOKEN_URL = "_ah/OAuthAuthorizeToken?btmpl=mobile";
//
// public static final String CALLBACK = "callback/android/";
// public static final int INTENT_ID = 0x1234;
//
//
// public static OAuthConsumer makeConsumer() {
// return new CommonsHttpOAuthConsumer(HttpClient.CONSUMER_KEY, HttpClient.CONSUMER_SECRET);
// }
//
// public static OAuthProvider makeProvider(String host) {
// String request_token_url = host + REQUEST_TOKEN_URL;
// String access_token_url = host + ACCESS_TOKEN_URL;
// String authorise_token_url = host + AUTHORISE_TOKEN_URL;
// return new CommonsHttpOAuthProvider(request_token_url, access_token_url, authorise_token_url);
// }
//
// public static String getRequestUrl(String host, String account) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException {
// if(consumer == null) {
// consumer = makeConsumer();
// }
//
// if(provider == null) {
// provider = makeProvider(host);
// }
// account = Uri.encode(account);
// String target = provider.retrieveRequestToken(consumer, host+CALLBACK+"?account="+account);
// return target;
// }
//
// public static OAuthConsumer getAccessToken(String host, String verifier) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException {
// if(provider == null) {
// provider = makeProvider(host);
// }
//
// if(consumer == null) {
// consumer = makeConsumer();
// }
// provider.retrieveAccessToken(consumer, verifier);
// return consumer;
// }
// }
// Path: src/com/suchagit/android2cloud/OAuthWebView.java
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.suchagit.android2cloud.errors.OAuthWebviewNullIntentDialogFragment;
import com.suchagit.android2cloud.util.OAuth;
package com.suchagit.android2cloud;
public class OAuthWebView extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
String request_url = "";
if(this.getIntent() != null && this.getIntent().getDataString() != null){
request_url = this.getIntent().getDataString();
} else {
showDialog(R.string.oauthwebview_null_intent_error); | DialogFragment errorFragment = OAuthWebviewNullIntentDialogFragment.newInstance(); |
2cloud/android2cloud | src/com/suchagit/android2cloud/OAuthWebView.java | // Path: src/com/suchagit/android2cloud/errors/OAuthWebviewNullIntentDialogFragment.java
// public class OAuthWebviewNullIntentDialogFragment extends DialogFragment {
//
// public static OAuthWebviewNullIntentDialogFragment newInstance() {
// OAuthWebviewNullIntentDialogFragment frag = new OAuthWebviewNullIntentDialogFragment();
// return frag;
// }
//
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState) {
// int title = R.string.default_error_title;
// int body = R.string.oauthwebview_null_intent_error;
// int yesButton = R.string.default_error_ok;
//
// return new AlertDialog.Builder(getActivity())
// .setCancelable(false)
// .setTitle(title)
// .setMessage(body)
// .setPositiveButton(yesButton,
// new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int whichButton) {
// dialog.cancel();
// getActivity().finish();
// }
// }
// )
// .create();
// }
// }
//
// Path: src/com/suchagit/android2cloud/util/OAuth.java
// public class OAuth {
//
// private static OAuthProvider provider;
// private static OAuthConsumer consumer;
//
// private static final String REQUEST_TOKEN_URL = "_ah/OAuthGetRequestToken";
// private static final String ACCESS_TOKEN_URL = "_ah/OAuthGetAccessToken";
// private static final String AUTHORISE_TOKEN_URL = "_ah/OAuthAuthorizeToken?btmpl=mobile";
//
// public static final String CALLBACK = "callback/android/";
// public static final int INTENT_ID = 0x1234;
//
//
// public static OAuthConsumer makeConsumer() {
// return new CommonsHttpOAuthConsumer(HttpClient.CONSUMER_KEY, HttpClient.CONSUMER_SECRET);
// }
//
// public static OAuthProvider makeProvider(String host) {
// String request_token_url = host + REQUEST_TOKEN_URL;
// String access_token_url = host + ACCESS_TOKEN_URL;
// String authorise_token_url = host + AUTHORISE_TOKEN_URL;
// return new CommonsHttpOAuthProvider(request_token_url, access_token_url, authorise_token_url);
// }
//
// public static String getRequestUrl(String host, String account) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException {
// if(consumer == null) {
// consumer = makeConsumer();
// }
//
// if(provider == null) {
// provider = makeProvider(host);
// }
// account = Uri.encode(account);
// String target = provider.retrieveRequestToken(consumer, host+CALLBACK+"?account="+account);
// return target;
// }
//
// public static OAuthConsumer getAccessToken(String host, String verifier) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException {
// if(provider == null) {
// provider = makeProvider(host);
// }
//
// if(consumer == null) {
// consumer = makeConsumer();
// }
// provider.retrieveAccessToken(consumer, verifier);
// return consumer;
// }
// }
| import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.suchagit.android2cloud.errors.OAuthWebviewNullIntentDialogFragment;
import com.suchagit.android2cloud.util.OAuth; | package com.suchagit.android2cloud;
public class OAuthWebView extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
String request_url = "";
if(this.getIntent() != null && this.getIntent().getDataString() != null){
request_url = this.getIntent().getDataString();
} else {
showDialog(R.string.oauthwebview_null_intent_error);
DialogFragment errorFragment = OAuthWebviewNullIntentDialogFragment.newInstance();
errorFragment.show(getSupportFragmentManager(), "dialog");
}
WebView browser= new WebView(this);
setContentView(browser);
browser.getSettings().setJavaScriptEnabled(true);
final Activity activity = this;
browser.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 1000);
}
});
browser.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url){
super.onPageFinished(view, url);
Uri uri = Uri.parse(url); | // Path: src/com/suchagit/android2cloud/errors/OAuthWebviewNullIntentDialogFragment.java
// public class OAuthWebviewNullIntentDialogFragment extends DialogFragment {
//
// public static OAuthWebviewNullIntentDialogFragment newInstance() {
// OAuthWebviewNullIntentDialogFragment frag = new OAuthWebviewNullIntentDialogFragment();
// return frag;
// }
//
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState) {
// int title = R.string.default_error_title;
// int body = R.string.oauthwebview_null_intent_error;
// int yesButton = R.string.default_error_ok;
//
// return new AlertDialog.Builder(getActivity())
// .setCancelable(false)
// .setTitle(title)
// .setMessage(body)
// .setPositiveButton(yesButton,
// new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int whichButton) {
// dialog.cancel();
// getActivity().finish();
// }
// }
// )
// .create();
// }
// }
//
// Path: src/com/suchagit/android2cloud/util/OAuth.java
// public class OAuth {
//
// private static OAuthProvider provider;
// private static OAuthConsumer consumer;
//
// private static final String REQUEST_TOKEN_URL = "_ah/OAuthGetRequestToken";
// private static final String ACCESS_TOKEN_URL = "_ah/OAuthGetAccessToken";
// private static final String AUTHORISE_TOKEN_URL = "_ah/OAuthAuthorizeToken?btmpl=mobile";
//
// public static final String CALLBACK = "callback/android/";
// public static final int INTENT_ID = 0x1234;
//
//
// public static OAuthConsumer makeConsumer() {
// return new CommonsHttpOAuthConsumer(HttpClient.CONSUMER_KEY, HttpClient.CONSUMER_SECRET);
// }
//
// public static OAuthProvider makeProvider(String host) {
// String request_token_url = host + REQUEST_TOKEN_URL;
// String access_token_url = host + ACCESS_TOKEN_URL;
// String authorise_token_url = host + AUTHORISE_TOKEN_URL;
// return new CommonsHttpOAuthProvider(request_token_url, access_token_url, authorise_token_url);
// }
//
// public static String getRequestUrl(String host, String account) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException {
// if(consumer == null) {
// consumer = makeConsumer();
// }
//
// if(provider == null) {
// provider = makeProvider(host);
// }
// account = Uri.encode(account);
// String target = provider.retrieveRequestToken(consumer, host+CALLBACK+"?account="+account);
// return target;
// }
//
// public static OAuthConsumer getAccessToken(String host, String verifier) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException {
// if(provider == null) {
// provider = makeProvider(host);
// }
//
// if(consumer == null) {
// consumer = makeConsumer();
// }
// provider.retrieveAccessToken(consumer, verifier);
// return consumer;
// }
// }
// Path: src/com/suchagit/android2cloud/OAuthWebView.java
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.suchagit.android2cloud.errors.OAuthWebviewNullIntentDialogFragment;
import com.suchagit.android2cloud.util.OAuth;
package com.suchagit.android2cloud;
public class OAuthWebView extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
String request_url = "";
if(this.getIntent() != null && this.getIntent().getDataString() != null){
request_url = this.getIntent().getDataString();
} else {
showDialog(R.string.oauthwebview_null_intent_error);
DialogFragment errorFragment = OAuthWebviewNullIntentDialogFragment.newInstance();
errorFragment.show(getSupportFragmentManager(), "dialog");
}
WebView browser= new WebView(this);
setContentView(browser);
browser.getSettings().setJavaScriptEnabled(true);
final Activity activity = this;
browser.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 1000);
}
});
browser.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url){
super.onPageFinished(view, url);
Uri uri = Uri.parse(url); | if(("/" + OAuth.CALLBACK).equals(uri.getPath())){ |
2cloud/android2cloud | src/com/suchagit/android2cloud/errors/UnsupportedEncodingExceptionDialogFragment.java | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods; | int title = R.string.default_error_title;
int body = R.string.unsupported_encoding_exception_error;
int yesButton = R.string.default_error_ok;
int noButton = R.string.report_error_button;
final String host = getArguments().getString("host");
final String account = getArguments().getString("account");
final String device = getArguments().getString("device_name");
final String receiver = getArguments().getString("receiver");
final String link = getArguments().getString("link");
return new AlertDialog.Builder(getActivity())
.setCancelable(true)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Account: " + account +"\n";
message += "Host: " + host + "\n";
message += "Device Name: " + device + "\n";
message += "Receiver: " + receiver + "\n";
message += "Link: " + link + "\n"; | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
// Path: src/com/suchagit/android2cloud/errors/UnsupportedEncodingExceptionDialogFragment.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods;
int title = R.string.default_error_title;
int body = R.string.unsupported_encoding_exception_error;
int yesButton = R.string.default_error_ok;
int noButton = R.string.report_error_button;
final String host = getArguments().getString("host");
final String account = getArguments().getString("account");
final String device = getArguments().getString("device_name");
final String receiver = getArguments().getString("receiver");
final String link = getArguments().getString("link");
return new AlertDialog.Builder(getActivity())
.setCancelable(true)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Account: " + account +"\n";
message += "Host: " + host + "\n";
message += "Device Name: " + device + "\n";
message += "Receiver: " + receiver + "\n";
message += "Link: " + link + "\n"; | Intent report = ErrorMethods.getEmailIntent(UnsupportedEncodingExceptionDialogFragment.this, "unsupported_encoding_exception_error", message); |
2cloud/android2cloud | src/com/suchagit/android2cloud/errors/HttpClientErrorDialogFragment.java | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
| import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment; | int body = R.string.http_client_error;
int yesButton = R.string.default_error_ok;
int noButton = R.string.report_error_button;
final String host = getArguments().getString("host");
final String account = getArguments().getString("account");
final String token = getArguments().getString("token");
final String secret = getArguments().getString("secret");
final String raw_data = getArguments().getString("raw_data");
return new AlertDialog.Builder(getActivity())
.setCancelable(true)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Account: " + account +"\n";
message += "Host: " + host + "\n";
message += "Token: " + token + "\n";
message += "Secret: " + secret + "\n";
message += "Raw Result Data: \n";
message += raw_data + "\n"; | // Path: src/com/suchagit/android2cloud/util/ErrorMethods.java
// public class ErrorMethods {
// public static Intent getEmailIntent(Fragment context, String type, String message) {
// Intent i = new Intent(Intent.ACTION_SEND);
// i.setType("message/rfc822");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"android@2cloudproject.com"});
// i.putExtra(Intent.EXTRA_SUBJECT, "In-App Error Report");
// String message_prefix = "Error:\n";
// message_prefix += "Type: "+type+"\n";
// try {
// message_prefix += "Version: " + context.getActivity().getPackageManager().getPackageInfo(context.getActivity().getPackageName(), 0 ).versionCode + "\n";
// } catch (NameNotFoundException e) {
// message_prefix += "\n";
// }
// message_prefix += "Android Version: " + android.os.Build.VERSION.SDK + "\n";
// message_prefix += "Phone: " + android.os.Build.MODEL + "\n";
// message = message_prefix + message;
// i.putExtra(Intent.EXTRA_TEXT , message);
// return i;
// }
// }
// Path: src/com/suchagit/android2cloud/errors/HttpClientErrorDialogFragment.java
import com.suchagit.android2cloud.R;
import com.suchagit.android2cloud.util.ErrorMethods;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
int body = R.string.http_client_error;
int yesButton = R.string.default_error_ok;
int noButton = R.string.report_error_button;
final String host = getArguments().getString("host");
final String account = getArguments().getString("account");
final String token = getArguments().getString("token");
final String secret = getArguments().getString("secret");
final String raw_data = getArguments().getString("raw_data");
return new AlertDialog.Builder(getActivity())
.setCancelable(true)
.setTitle(title)
.setMessage(body)
.setPositiveButton(yesButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
}
)
.setNegativeButton(noButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String message = "Account: " + account +"\n";
message += "Host: " + host + "\n";
message += "Token: " + token + "\n";
message += "Secret: " + secret + "\n";
message += "Raw Result Data: \n";
message += raw_data + "\n"; | Intent report = ErrorMethods.getEmailIntent(HttpClientErrorDialogFragment.this, "http_client_error", message); |
2cloud/android2cloud | src/com/suchagit/android2cloud/PurchaseObserver.java | // Path: src/com/suchagit/android2cloud/BillingService.java
// class RequestPurchase extends BillingRequest {
// public final String mProductId;
// public final String mDeveloperPayload;
//
// public RequestPurchase(String itemId) {
// this(itemId, null);
// }
//
// public RequestPurchase(String itemId, String developerPayload) {
// // This object is never created as a side effect of starting this
// // service so we pass -1 as the startId to indicate that we should
// // not stop this service after executing this request.
// super(-1);
// mProductId = itemId;
// mDeveloperPayload = developerPayload;
// }
//
// @Override
// protected long run() throws RemoteException {
// Bundle request = makeRequestBundle("REQUEST_PURCHASE");
// request.putString(Consts.BILLING_REQUEST_ITEM_ID, mProductId);
// // Note that the developer payload is optional.
// if (mDeveloperPayload != null) {
// request.putString(Consts.BILLING_REQUEST_DEVELOPER_PAYLOAD, mDeveloperPayload);
// }
// Bundle response = mService.sendBillingRequest(request);
// PendingIntent pendingIntent
// = response.getParcelable(Consts.BILLING_RESPONSE_PURCHASE_INTENT);
// if (pendingIntent == null) {
// Log.e(TAG, "Error with requestPurchase");
// return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
// }
//
// Intent intent = new Intent();
// ResponseHandler.buyPageIntentResponse(pendingIntent, intent);
// return response.getLong(Consts.BILLING_RESPONSE_REQUEST_ID,
// Consts.BILLING_RESPONSE_INVALID_REQUEST_ID);
// }
//
// @Override
// protected void responseCodeReceived(ResponseCode responseCode) {
// ResponseHandler.responseCodeReceived(BillingService.this, this, responseCode);
// }
// }
//
// Path: src/com/suchagit/android2cloud/Consts.java
// public enum PurchaseState {
// // Responses to requestPurchase or restoreTransactions.
// PURCHASED, // User was charged for the order.
// CANCELED, // The charge failed on the server.
// REFUNDED; // User received a refund for the order.
//
// // Converts from an ordinal value to the PurchaseState
// public static PurchaseState valueOf(int index) {
// PurchaseState[] values = PurchaseState.values();
// if (index < 0 || index >= values.length) {
// return CANCELED;
// }
// return values[index];
// }
// }
//
// Path: src/com/suchagit/android2cloud/Consts.java
// public enum ResponseCode {
// RESULT_OK,
// RESULT_USER_CANCELED,
// RESULT_SERVICE_UNAVAILABLE,
// RESULT_BILLING_UNAVAILABLE,
// RESULT_ITEM_UNAVAILABLE,
// RESULT_DEVELOPER_ERROR,
// RESULT_ERROR;
//
// // Converts from an ordinal value to the ResponseCode
// public static ResponseCode valueOf(int index) {
// ResponseCode[] values = ResponseCode.values();
// if (index < 0 || index >= values.length) {
// return RESULT_ERROR;
// }
// return values[index];
// }
// }
| import com.suchagit.android2cloud.BillingService.RequestPurchase;
import com.suchagit.android2cloud.Consts.PurchaseState;
import com.suchagit.android2cloud.Consts.ResponseCode;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Handler;
import android.util.Log;
import java.lang.reflect.Method; | // Copyright 2010 Google Inc. All Rights Reserved.
package com.suchagit.android2cloud;
/**
* An interface for observing changes related to purchases. The main application
* extends this class and registers an instance of that derived class with
* {@link ResponseHandler}. The main application implements the callbacks
* {@link #onBillingSupported(boolean)} and
* {@link #onPurchaseStateChange(PurchaseState, String, int, long)}. These methods
* are used to update the UI.
*/
public abstract class PurchaseObserver {
private static final String TAG = "PurchaseObserver";
private final Activity mActivity;
private final Handler mHandler;
private Method mStartIntentSender;
private Object[] mStartIntentSenderArgs = new Object[5];
@SuppressWarnings({ "rawtypes" })
private static final Class[] START_INTENT_SENDER_SIG = new Class[] {
IntentSender.class, Intent.class, int.class, int.class, int.class
};
public PurchaseObserver(Activity activity, Handler handler) {
mActivity = activity;
mHandler = handler;
initCompatibilityLayer();
}
/**
* This is the callback that is invoked when Android Market responds to the
* {@link BillingService#checkBillingSupported()} request.
* @param supported true if in-app billing is supported.
*/
public abstract void onBillingSupported(boolean supported);
/**
* This is the callback that is invoked when an item is purchased,
* refunded, or canceled. It is the callback invoked in response to
* calling {@link BillingService#requestPurchase(String)}. It may also
* be invoked asynchronously when a purchase is made on another device
* (if the purchase was for a Market-managed item), or if the purchase
* was refunded, or the charge was canceled. This handles the UI
* update. The database update is handled in
* {@link ResponseHandler#purchaseResponse(Context, PurchaseState,
* String, String, long)}.
* @param purchaseState the purchase state of the item
* @param itemId a string identifying the item (the "SKU")
* @param quantity the current quantity of this item after the purchase
* @param purchaseTime the time the product was purchased, in
* milliseconds since the epoch (Jan 1, 1970)
* @param orderId the Google Checkout order ID number
*/ | // Path: src/com/suchagit/android2cloud/BillingService.java
// class RequestPurchase extends BillingRequest {
// public final String mProductId;
// public final String mDeveloperPayload;
//
// public RequestPurchase(String itemId) {
// this(itemId, null);
// }
//
// public RequestPurchase(String itemId, String developerPayload) {
// // This object is never created as a side effect of starting this
// // service so we pass -1 as the startId to indicate that we should
// // not stop this service after executing this request.
// super(-1);
// mProductId = itemId;
// mDeveloperPayload = developerPayload;
// }
//
// @Override
// protected long run() throws RemoteException {
// Bundle request = makeRequestBundle("REQUEST_PURCHASE");
// request.putString(Consts.BILLING_REQUEST_ITEM_ID, mProductId);
// // Note that the developer payload is optional.
// if (mDeveloperPayload != null) {
// request.putString(Consts.BILLING_REQUEST_DEVELOPER_PAYLOAD, mDeveloperPayload);
// }
// Bundle response = mService.sendBillingRequest(request);
// PendingIntent pendingIntent
// = response.getParcelable(Consts.BILLING_RESPONSE_PURCHASE_INTENT);
// if (pendingIntent == null) {
// Log.e(TAG, "Error with requestPurchase");
// return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
// }
//
// Intent intent = new Intent();
// ResponseHandler.buyPageIntentResponse(pendingIntent, intent);
// return response.getLong(Consts.BILLING_RESPONSE_REQUEST_ID,
// Consts.BILLING_RESPONSE_INVALID_REQUEST_ID);
// }
//
// @Override
// protected void responseCodeReceived(ResponseCode responseCode) {
// ResponseHandler.responseCodeReceived(BillingService.this, this, responseCode);
// }
// }
//
// Path: src/com/suchagit/android2cloud/Consts.java
// public enum PurchaseState {
// // Responses to requestPurchase or restoreTransactions.
// PURCHASED, // User was charged for the order.
// CANCELED, // The charge failed on the server.
// REFUNDED; // User received a refund for the order.
//
// // Converts from an ordinal value to the PurchaseState
// public static PurchaseState valueOf(int index) {
// PurchaseState[] values = PurchaseState.values();
// if (index < 0 || index >= values.length) {
// return CANCELED;
// }
// return values[index];
// }
// }
//
// Path: src/com/suchagit/android2cloud/Consts.java
// public enum ResponseCode {
// RESULT_OK,
// RESULT_USER_CANCELED,
// RESULT_SERVICE_UNAVAILABLE,
// RESULT_BILLING_UNAVAILABLE,
// RESULT_ITEM_UNAVAILABLE,
// RESULT_DEVELOPER_ERROR,
// RESULT_ERROR;
//
// // Converts from an ordinal value to the ResponseCode
// public static ResponseCode valueOf(int index) {
// ResponseCode[] values = ResponseCode.values();
// if (index < 0 || index >= values.length) {
// return RESULT_ERROR;
// }
// return values[index];
// }
// }
// Path: src/com/suchagit/android2cloud/PurchaseObserver.java
import com.suchagit.android2cloud.BillingService.RequestPurchase;
import com.suchagit.android2cloud.Consts.PurchaseState;
import com.suchagit.android2cloud.Consts.ResponseCode;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Handler;
import android.util.Log;
import java.lang.reflect.Method;
// Copyright 2010 Google Inc. All Rights Reserved.
package com.suchagit.android2cloud;
/**
* An interface for observing changes related to purchases. The main application
* extends this class and registers an instance of that derived class with
* {@link ResponseHandler}. The main application implements the callbacks
* {@link #onBillingSupported(boolean)} and
* {@link #onPurchaseStateChange(PurchaseState, String, int, long)}. These methods
* are used to update the UI.
*/
public abstract class PurchaseObserver {
private static final String TAG = "PurchaseObserver";
private final Activity mActivity;
private final Handler mHandler;
private Method mStartIntentSender;
private Object[] mStartIntentSenderArgs = new Object[5];
@SuppressWarnings({ "rawtypes" })
private static final Class[] START_INTENT_SENDER_SIG = new Class[] {
IntentSender.class, Intent.class, int.class, int.class, int.class
};
public PurchaseObserver(Activity activity, Handler handler) {
mActivity = activity;
mHandler = handler;
initCompatibilityLayer();
}
/**
* This is the callback that is invoked when Android Market responds to the
* {@link BillingService#checkBillingSupported()} request.
* @param supported true if in-app billing is supported.
*/
public abstract void onBillingSupported(boolean supported);
/**
* This is the callback that is invoked when an item is purchased,
* refunded, or canceled. It is the callback invoked in response to
* calling {@link BillingService#requestPurchase(String)}. It may also
* be invoked asynchronously when a purchase is made on another device
* (if the purchase was for a Market-managed item), or if the purchase
* was refunded, or the charge was canceled. This handles the UI
* update. The database update is handled in
* {@link ResponseHandler#purchaseResponse(Context, PurchaseState,
* String, String, long)}.
* @param purchaseState the purchase state of the item
* @param itemId a string identifying the item (the "SKU")
* @param quantity the current quantity of this item after the purchase
* @param purchaseTime the time the product was purchased, in
* milliseconds since the epoch (Jan 1, 1970)
* @param orderId the Google Checkout order ID number
*/ | public abstract void onPurchaseStateChange(PurchaseState purchaseState, |
2cloud/android2cloud | src/com/suchagit/android2cloud/BillingReceiver.java | // Path: src/com/suchagit/android2cloud/Consts.java
// public enum ResponseCode {
// RESULT_OK,
// RESULT_USER_CANCELED,
// RESULT_SERVICE_UNAVAILABLE,
// RESULT_BILLING_UNAVAILABLE,
// RESULT_ITEM_UNAVAILABLE,
// RESULT_DEVELOPER_ERROR,
// RESULT_ERROR;
//
// // Converts from an ordinal value to the ResponseCode
// public static ResponseCode valueOf(int index) {
// ResponseCode[] values = ResponseCode.values();
// if (index < 0 || index >= values.length) {
// return RESULT_ERROR;
// }
// return values[index];
// }
// }
| import com.suchagit.android2cloud.Consts.ResponseCode;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log; | /*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.suchagit.android2cloud;
/**
* This class implements the broadcast receiver for in-app billing. All asynchronous messages from
* Android Market come to this app through this receiver. This class forwards all
* messages to the {@link BillingService}, which can start background threads,
* if necessary, to process the messages. This class runs on the UI thread and must not do any
* network I/O, database updates, or any tasks that might take a long time to complete.
* It also must not start a background thread because that may be killed as soon as
* {@link #onReceive(Context, Intent)} returns.
*
* You should modify and obfuscate this code before using it.
*/
public class BillingReceiver extends BroadcastReceiver {
private static final String TAG = "BillingReceiver";
/**
* This is the entry point for all asynchronous messages sent from Android Market to
* the application. This method forwards the messages on to the
* {@link BillingService}, which handles the communication back to Android Market.
* The {@link BillingService} also reports state changes back to the application through
* the {@link ResponseHandler}.
*/
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Consts.ACTION_PURCHASE_STATE_CHANGED.equals(action)) {
String signedData = intent.getStringExtra(Consts.INAPP_SIGNED_DATA);
String signature = intent.getStringExtra(Consts.INAPP_SIGNATURE);
purchaseStateChanged(context, signedData, signature);
} else if (Consts.ACTION_NOTIFY.equals(action)) {
String notifyId = intent.getStringExtra(Consts.NOTIFICATION_ID);
if (Consts.DEBUG) {
Log.i(TAG, "notifyId: " + notifyId);
}
notify(context, notifyId);
} else if (Consts.ACTION_RESPONSE_CODE.equals(action)) {
long requestId = intent.getLongExtra(Consts.INAPP_REQUEST_ID, -1);
int responseCodeIndex = intent.getIntExtra(Consts.INAPP_RESPONSE_CODE, | // Path: src/com/suchagit/android2cloud/Consts.java
// public enum ResponseCode {
// RESULT_OK,
// RESULT_USER_CANCELED,
// RESULT_SERVICE_UNAVAILABLE,
// RESULT_BILLING_UNAVAILABLE,
// RESULT_ITEM_UNAVAILABLE,
// RESULT_DEVELOPER_ERROR,
// RESULT_ERROR;
//
// // Converts from an ordinal value to the ResponseCode
// public static ResponseCode valueOf(int index) {
// ResponseCode[] values = ResponseCode.values();
// if (index < 0 || index >= values.length) {
// return RESULT_ERROR;
// }
// return values[index];
// }
// }
// Path: src/com/suchagit/android2cloud/BillingReceiver.java
import com.suchagit.android2cloud.Consts.ResponseCode;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.suchagit.android2cloud;
/**
* This class implements the broadcast receiver for in-app billing. All asynchronous messages from
* Android Market come to this app through this receiver. This class forwards all
* messages to the {@link BillingService}, which can start background threads,
* if necessary, to process the messages. This class runs on the UI thread and must not do any
* network I/O, database updates, or any tasks that might take a long time to complete.
* It also must not start a background thread because that may be killed as soon as
* {@link #onReceive(Context, Intent)} returns.
*
* You should modify and obfuscate this code before using it.
*/
public class BillingReceiver extends BroadcastReceiver {
private static final String TAG = "BillingReceiver";
/**
* This is the entry point for all asynchronous messages sent from Android Market to
* the application. This method forwards the messages on to the
* {@link BillingService}, which handles the communication back to Android Market.
* The {@link BillingService} also reports state changes back to the application through
* the {@link ResponseHandler}.
*/
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Consts.ACTION_PURCHASE_STATE_CHANGED.equals(action)) {
String signedData = intent.getStringExtra(Consts.INAPP_SIGNED_DATA);
String signature = intent.getStringExtra(Consts.INAPP_SIGNATURE);
purchaseStateChanged(context, signedData, signature);
} else if (Consts.ACTION_NOTIFY.equals(action)) {
String notifyId = intent.getStringExtra(Consts.NOTIFICATION_ID);
if (Consts.DEBUG) {
Log.i(TAG, "notifyId: " + notifyId);
}
notify(context, notifyId);
} else if (Consts.ACTION_RESPONSE_CODE.equals(action)) {
long requestId = intent.getLongExtra(Consts.INAPP_REQUEST_ID, -1);
int responseCodeIndex = intent.getIntExtra(Consts.INAPP_RESPONSE_CODE, | ResponseCode.RESULT_ERROR.ordinal()); |
Shrewbi/hltv-Csgolounge-scraper | brinbot/src/csgoscraper/Csglscraper.java | // Path: brinbot/src/csgoscraper/Database.java
// public static int getTid(String team, String comp){
//
// if(comp != null && comp.contains("King of Nordic")){
// if(team.equals("KoN Denmark") || team.equals("Denmark")){return 652;}
// if(team.equals("KoN Norway") || team.equals("Norway")){return 654;}
// if(team.equals("KoN Sweden") || team.equals("Sweden")){return 653;}
// if(team.equals("KoN Finland") || team.equals("Finland")){return 655;}
// else{return 108;}
// }
//
// int tid = 108; // filler team
//
// Connection conn = null;
// Statement stmt = null;
// int active = 0;
// String teamfix = team.replaceAll("'", "''");
// try{
// Class.forName("com.mysql.jdbc.Driver");
// conn = DriverManager.getConnection(DB_URL, USER, PASS);
// stmt = conn.createStatement();
//
// String sql = "SELECT tid, active FROM Teams WHERE (hltvname ='"+teamfix+"' OR name = '"+teamfix+"' OR csglname = '"+teamfix+"') LIMIT 1";
// ResultSet rs = stmt.executeQuery(sql);
// while(rs.next()){
// tid = rs.getInt("tid");
// active = rs.getInt("active");
// }
// rs.close();
// }catch(SQLException se){
// se.printStackTrace();
// }catch(Exception e){
// e.printStackTrace();
// }finally{
// try{
// if(stmt!=null)
// conn.close();
// }catch(SQLException se){
// }
// try{
// if(conn!=null)
// conn.close();
// }catch(SQLException se){
// se.printStackTrace();
// }
// if(active == 0){markteamactive(tid);}
//
//
// }
// return tid;
// }
| import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import static csgoscraper.Database.getTid; | }
// Scrape odds
Elements odds = doc.select("div.match div.teamtext i");
count = 0;
for (Element odd : odds) {
String scraped = odd.text();
String scrapeodds;
count++;
switch (scraped.length()) {
case 2: scrapeodds = scraped.substring(0,1); break;
case 3: scrapeodds = scraped.substring(0,2); break;
case 4: scrapeodds = scraped.substring(0,3); break;
default: scrapeodds = "0";
}
if(count % 2 != 0){scrapedodds1.add(Integer.parseInt(scrapeodds));}
else{scrapedodds2.add(Integer.parseInt(scrapeodds));}
}
// Scrape competition
Elements comps = doc.select("div.matchheader div.eventm");
for (Element comp : comps) {
String scraped = comp.text();
scrapedcomps.add(scraped);
}
// Convert to teamids
for(int s = 0; s < scrapedteam1.size(); s++){ | // Path: brinbot/src/csgoscraper/Database.java
// public static int getTid(String team, String comp){
//
// if(comp != null && comp.contains("King of Nordic")){
// if(team.equals("KoN Denmark") || team.equals("Denmark")){return 652;}
// if(team.equals("KoN Norway") || team.equals("Norway")){return 654;}
// if(team.equals("KoN Sweden") || team.equals("Sweden")){return 653;}
// if(team.equals("KoN Finland") || team.equals("Finland")){return 655;}
// else{return 108;}
// }
//
// int tid = 108; // filler team
//
// Connection conn = null;
// Statement stmt = null;
// int active = 0;
// String teamfix = team.replaceAll("'", "''");
// try{
// Class.forName("com.mysql.jdbc.Driver");
// conn = DriverManager.getConnection(DB_URL, USER, PASS);
// stmt = conn.createStatement();
//
// String sql = "SELECT tid, active FROM Teams WHERE (hltvname ='"+teamfix+"' OR name = '"+teamfix+"' OR csglname = '"+teamfix+"') LIMIT 1";
// ResultSet rs = stmt.executeQuery(sql);
// while(rs.next()){
// tid = rs.getInt("tid");
// active = rs.getInt("active");
// }
// rs.close();
// }catch(SQLException se){
// se.printStackTrace();
// }catch(Exception e){
// e.printStackTrace();
// }finally{
// try{
// if(stmt!=null)
// conn.close();
// }catch(SQLException se){
// }
// try{
// if(conn!=null)
// conn.close();
// }catch(SQLException se){
// se.printStackTrace();
// }
// if(active == 0){markteamactive(tid);}
//
//
// }
// return tid;
// }
// Path: brinbot/src/csgoscraper/Csglscraper.java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import static csgoscraper.Database.getTid;
}
// Scrape odds
Elements odds = doc.select("div.match div.teamtext i");
count = 0;
for (Element odd : odds) {
String scraped = odd.text();
String scrapeodds;
count++;
switch (scraped.length()) {
case 2: scrapeodds = scraped.substring(0,1); break;
case 3: scrapeodds = scraped.substring(0,2); break;
case 4: scrapeodds = scraped.substring(0,3); break;
default: scrapeodds = "0";
}
if(count % 2 != 0){scrapedodds1.add(Integer.parseInt(scrapeodds));}
else{scrapedodds2.add(Integer.parseInt(scrapeodds));}
}
// Scrape competition
Elements comps = doc.select("div.matchheader div.eventm");
for (Element comp : comps) {
String scraped = comp.text();
scrapedcomps.add(scraped);
}
// Convert to teamids
for(int s = 0; s < scrapedteam1.size(); s++){ | int stid1 = getTid(scrapedteam1.get(s), scrapedcomps.get(s)); |
symbiont/cdiqi | cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/basic/BasicTest.java | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
| import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil; | package cz.symbiont_it.cdiqi.tests.basic;
/**
* Basic test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class BasicTest {
static final int JOB_EXEC_COUNT_DEPENDANT = 10;
static final int JOB_EXEC_COUNT_REQUEST = 16;
static final int JOB_EXEC_COUNT_APPLICATION = 5;
@Inject | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/basic/BasicTest.java
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil;
package cz.symbiont_it.cdiqi.tests.basic;
/**
* Basic test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class BasicTest {
static final int JOB_EXEC_COUNT_DEPENDANT = 10;
static final int JOB_EXEC_COUNT_REQUEST = 16;
static final int JOB_EXEC_COUNT_APPLICATION = 5;
@Inject | private QuartzSchedulerManager quartzManager; |
symbiont/cdiqi | cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/basic/BasicTest.java | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
| import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil; | package cz.symbiont_it.cdiqi.tests.basic;
/**
* Basic test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class BasicTest {
static final int JOB_EXEC_COUNT_DEPENDANT = 10;
static final int JOB_EXEC_COUNT_REQUEST = 16;
static final int JOB_EXEC_COUNT_APPLICATION = 5;
@Inject
private QuartzSchedulerManager quartzManager;
@Inject
BasicResultStore resultStore;
@Deployment
public static WebArchive createTestArchive() { | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/basic/BasicTest.java
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil;
package cz.symbiont_it.cdiqi.tests.basic;
/**
* Basic test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class BasicTest {
static final int JOB_EXEC_COUNT_DEPENDANT = 10;
static final int JOB_EXEC_COUNT_REQUEST = 16;
static final int JOB_EXEC_COUNT_APPLICATION = 5;
@Inject
private QuartzSchedulerManager quartzManager;
@Inject
BasicResultStore resultStore;
@Deployment
public static WebArchive createTestArchive() { | return CdiqiTestUtil.createTestArchive().addPackage( |
symbiont/cdiqi | cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/concurrent/StatefulTest.java | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
| import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import javax.inject.Inject;
import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil; | package cz.symbiont_it.cdiqi.tests.concurrent;
/**
* Stateful job test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class StatefulTest {
@Inject | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/concurrent/StatefulTest.java
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import javax.inject.Inject;
import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil;
package cz.symbiont_it.cdiqi.tests.concurrent;
/**
* Stateful job test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class StatefulTest {
@Inject | private QuartzSchedulerManager quartzManager; |
symbiont/cdiqi | cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/concurrent/StatefulTest.java | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
| import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import javax.inject.Inject;
import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil; | package cz.symbiont_it.cdiqi.tests.concurrent;
/**
* Stateful job test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class StatefulTest {
@Inject
private QuartzSchedulerManager quartzManager;
@Inject
private NotGuardedApplicationScopedService notGuardedApplicationScopedService;
@Deployment
public static WebArchive createTestArchive() { | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/concurrent/StatefulTest.java
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import javax.inject.Inject;
import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil;
package cz.symbiont_it.cdiqi.tests.concurrent;
/**
* Stateful job test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class StatefulTest {
@Inject
private QuartzSchedulerManager quartzManager;
@Inject
private NotGuardedApplicationScopedService notGuardedApplicationScopedService;
@Deployment
public static WebArchive createTestArchive() { | return CdiqiTestUtil.createTestArchive().addPackage( |
symbiont/cdiqi | cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/impl/AsyncJob.java | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/AsyncEvent.java
// public final class AsyncEvent {
//
// private final Object targetEvent;
//
// private final Annotation[] qualifiers;
//
// public AsyncEvent(Object targetEvent, Annotation... qualifiers) {
// super();
//
// if(targetEvent == null)
// throw new IllegalArgumentException("Target event must not be null");
//
// this.targetEvent = targetEvent;
// this.qualifiers = qualifiers;
// }
//
// public Object getTargetEvent() {
// return targetEvent;
// }
//
// public Annotation[] getQualifiers() {
// return qualifiers;
// }
//
// }
| import javax.enterprise.context.Dependent;
import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Inject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cz.symbiont_it.cdiqi.api.AsyncEvent; | /*
* Copyright 2011, Symbiont v.o.s
*
* 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 cz.symbiont_it.cdiqi.impl;
/**
* Job that fires {@link AsyncEvent#getTargetEvent()} asynchronously.
*
* @author Martin Kouba
*/
@Dependent
public class AsyncJob implements Job {
| // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/AsyncEvent.java
// public final class AsyncEvent {
//
// private final Object targetEvent;
//
// private final Annotation[] qualifiers;
//
// public AsyncEvent(Object targetEvent, Annotation... qualifiers) {
// super();
//
// if(targetEvent == null)
// throw new IllegalArgumentException("Target event must not be null");
//
// this.targetEvent = targetEvent;
// this.qualifiers = qualifiers;
// }
//
// public Object getTargetEvent() {
// return targetEvent;
// }
//
// public Annotation[] getQualifiers() {
// return qualifiers;
// }
//
// }
// Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/impl/AsyncJob.java
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Inject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cz.symbiont_it.cdiqi.api.AsyncEvent;
/*
* Copyright 2011, Symbiont v.o.s
*
* 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 cz.symbiont_it.cdiqi.impl;
/**
* Job that fires {@link AsyncEvent#getTargetEvent()} asynchronously.
*
* @author Martin Kouba
*/
@Dependent
public class AsyncJob implements Job {
| public static final String KEY_ASYNC_EVENT = AsyncEvent.class.getName(); |
symbiont/cdiqi | cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/impl/QuartzSchedulerManagerImpl.java | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/AsyncEvent.java
// public final class AsyncEvent {
//
// private final Object targetEvent;
//
// private final Annotation[] qualifiers;
//
// public AsyncEvent(Object targetEvent, Annotation... qualifiers) {
// super();
//
// if(targetEvent == null)
// throw new IllegalArgumentException("Target event must not be null");
//
// this.targetEvent = targetEvent;
// this.qualifiers = qualifiers;
// }
//
// public Object getTargetEvent() {
// return targetEvent;
// }
//
// public Annotation[] getQualifiers() {
// return qualifiers;
// }
//
// }
//
// Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/spi/BoundRequestJobListener.java
// public abstract class BoundRequestJobListener implements JobListener {
//
// protected static final String REQUEST_DATA_STORE_KEY = BoundRequestJobListener.class
// .getName() + "_REQUEST_DATA_STORE_KEY";
//
// /*
// * (non-Javadoc)
// *
// * @see org.quartz.JobListener#getName()
// */
// public String getName() {
// return getClass().getName();
// }
//
// /*
// * (non-Javadoc)
// *
// * @see
// * org.quartz.JobListener#jobToBeExecuted(org.quartz.JobExecutionContext)
// */
// public void jobToBeExecuted(JobExecutionContext context) {
// startRequest(context);
// }
//
// /*
// * (non-Javadoc)
// *
// * @see
// * org.quartz.JobListener#jobExecutionVetoed(org.quartz.JobExecutionContext)
// */
// public void jobExecutionVetoed(JobExecutionContext context) {
// endRequest(context);
// }
//
// /*
// * (non-Javadoc)
// *
// * @see
// * org.quartz.JobListener#jobWasExecuted(org.quartz.JobExecutionContext,
// * org.quartz.JobExecutionException)
// */
// public void jobWasExecuted(JobExecutionContext context,
// JobExecutionException jobException) {
// endRequest(context);
// }
//
// /**
// * @param context
// */
// protected abstract void startRequest(JobExecutionContext context);
//
// /**
// * @param context
// */
// protected abstract void endRequest(JobExecutionContext context);
//
// }
| import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
import java.util.UUID;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.EverythingMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cz.symbiont_it.cdiqi.api.AsyncEvent;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.spi.BoundRequestJobListener; | /*
* Copyright 2011, Symbiont v.o.s
*
* 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 cz.symbiont_it.cdiqi.impl;
/**
* Quartz scheduler manager implementation.
*
* @author Martin Kouba
*/
@ApplicationScoped
public class QuartzSchedulerManagerImpl implements QuartzSchedulerManager {
private static final Logger logger = LoggerFactory
.getLogger(QuartzSchedulerManagerImpl.class);
private static final String ASYNC_GROUP = "CdiqiAsync";
@Inject | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/AsyncEvent.java
// public final class AsyncEvent {
//
// private final Object targetEvent;
//
// private final Annotation[] qualifiers;
//
// public AsyncEvent(Object targetEvent, Annotation... qualifiers) {
// super();
//
// if(targetEvent == null)
// throw new IllegalArgumentException("Target event must not be null");
//
// this.targetEvent = targetEvent;
// this.qualifiers = qualifiers;
// }
//
// public Object getTargetEvent() {
// return targetEvent;
// }
//
// public Annotation[] getQualifiers() {
// return qualifiers;
// }
//
// }
//
// Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/spi/BoundRequestJobListener.java
// public abstract class BoundRequestJobListener implements JobListener {
//
// protected static final String REQUEST_DATA_STORE_KEY = BoundRequestJobListener.class
// .getName() + "_REQUEST_DATA_STORE_KEY";
//
// /*
// * (non-Javadoc)
// *
// * @see org.quartz.JobListener#getName()
// */
// public String getName() {
// return getClass().getName();
// }
//
// /*
// * (non-Javadoc)
// *
// * @see
// * org.quartz.JobListener#jobToBeExecuted(org.quartz.JobExecutionContext)
// */
// public void jobToBeExecuted(JobExecutionContext context) {
// startRequest(context);
// }
//
// /*
// * (non-Javadoc)
// *
// * @see
// * org.quartz.JobListener#jobExecutionVetoed(org.quartz.JobExecutionContext)
// */
// public void jobExecutionVetoed(JobExecutionContext context) {
// endRequest(context);
// }
//
// /*
// * (non-Javadoc)
// *
// * @see
// * org.quartz.JobListener#jobWasExecuted(org.quartz.JobExecutionContext,
// * org.quartz.JobExecutionException)
// */
// public void jobWasExecuted(JobExecutionContext context,
// JobExecutionException jobException) {
// endRequest(context);
// }
//
// /**
// * @param context
// */
// protected abstract void startRequest(JobExecutionContext context);
//
// /**
// * @param context
// */
// protected abstract void endRequest(JobExecutionContext context);
//
// }
// Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/impl/QuartzSchedulerManagerImpl.java
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
import java.util.UUID;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.EverythingMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cz.symbiont_it.cdiqi.api.AsyncEvent;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.spi.BoundRequestJobListener;
/*
* Copyright 2011, Symbiont v.o.s
*
* 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 cz.symbiont_it.cdiqi.impl;
/**
* Quartz scheduler manager implementation.
*
* @author Martin Kouba
*/
@ApplicationScoped
public class QuartzSchedulerManagerImpl implements QuartzSchedulerManager {
private static final Logger logger = LoggerFactory
.getLogger(QuartzSchedulerManagerImpl.class);
private static final String ASYNC_GROUP = "CdiqiAsync";
@Inject | private BoundRequestJobListener jobListener; |
symbiont/cdiqi | cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/clear/ClearTest.java | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
| import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil; | package cz.symbiont_it.cdiqi.tests.clear;
/**
* Scheduler clear test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class ClearTest {
static final int JOB_EXEC_COUNT_DEPENDANT = 10;
@Inject | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/clear/ClearTest.java
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil;
package cz.symbiont_it.cdiqi.tests.clear;
/**
* Scheduler clear test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class ClearTest {
static final int JOB_EXEC_COUNT_DEPENDANT = 10;
@Inject | private QuartzSchedulerManager quartzManager; |
symbiont/cdiqi | cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/clear/ClearTest.java | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
| import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil; | package cz.symbiont_it.cdiqi.tests.clear;
/**
* Scheduler clear test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class ClearTest {
static final int JOB_EXEC_COUNT_DEPENDANT = 10;
@Inject
private QuartzSchedulerManager quartzManager;
@Inject
ClearResultStore resultStore;
@Deployment
public static WebArchive createTestArchive() { | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/clear/ClearTest.java
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil;
package cz.symbiont_it.cdiqi.tests.clear;
/**
* Scheduler clear test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class ClearTest {
static final int JOB_EXEC_COUNT_DEPENDANT = 10;
@Inject
private QuartzSchedulerManager quartzManager;
@Inject
ClearResultStore resultStore;
@Deployment
public static WebArchive createTestArchive() { | return CdiqiTestUtil.createTestArchive().addPackage( |
symbiont/cdiqi | cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/async/AsyncTest.java | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/AsyncEvent.java
// public final class AsyncEvent {
//
// private final Object targetEvent;
//
// private final Annotation[] qualifiers;
//
// public AsyncEvent(Object targetEvent, Annotation... qualifiers) {
// super();
//
// if(targetEvent == null)
// throw new IllegalArgumentException("Target event must not be null");
//
// this.targetEvent = targetEvent;
// this.qualifiers = qualifiers;
// }
//
// public Object getTargetEvent() {
// return targetEvent;
// }
//
// public Annotation[] getQualifiers() {
// return qualifiers;
// }
//
// }
//
// Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import javax.enterprise.event.Event;
import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.SchedulerException;
import cz.symbiont_it.cdiqi.api.AsyncEvent;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil; | package cz.symbiont_it.cdiqi.tests.async;
/**
* Simple asynchronous test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class AsyncTest {
@Inject | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/AsyncEvent.java
// public final class AsyncEvent {
//
// private final Object targetEvent;
//
// private final Annotation[] qualifiers;
//
// public AsyncEvent(Object targetEvent, Annotation... qualifiers) {
// super();
//
// if(targetEvent == null)
// throw new IllegalArgumentException("Target event must not be null");
//
// this.targetEvent = targetEvent;
// this.qualifiers = qualifiers;
// }
//
// public Object getTargetEvent() {
// return targetEvent;
// }
//
// public Annotation[] getQualifiers() {
// return qualifiers;
// }
//
// }
//
// Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/async/AsyncTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import javax.enterprise.event.Event;
import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.SchedulerException;
import cz.symbiont_it.cdiqi.api.AsyncEvent;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil;
package cz.symbiont_it.cdiqi.tests.async;
/**
* Simple asynchronous test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class AsyncTest {
@Inject | private QuartzSchedulerManager quartzManager; |
symbiont/cdiqi | cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/async/AsyncTest.java | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/AsyncEvent.java
// public final class AsyncEvent {
//
// private final Object targetEvent;
//
// private final Annotation[] qualifiers;
//
// public AsyncEvent(Object targetEvent, Annotation... qualifiers) {
// super();
//
// if(targetEvent == null)
// throw new IllegalArgumentException("Target event must not be null");
//
// this.targetEvent = targetEvent;
// this.qualifiers = qualifiers;
// }
//
// public Object getTargetEvent() {
// return targetEvent;
// }
//
// public Annotation[] getQualifiers() {
// return qualifiers;
// }
//
// }
//
// Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import javax.enterprise.event.Event;
import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.SchedulerException;
import cz.symbiont_it.cdiqi.api.AsyncEvent;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil; | package cz.symbiont_it.cdiqi.tests.async;
/**
* Simple asynchronous test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class AsyncTest {
@Inject
private QuartzSchedulerManager quartzManager;
@Inject
private AsyncResultStore resultStore;
@Inject | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/AsyncEvent.java
// public final class AsyncEvent {
//
// private final Object targetEvent;
//
// private final Annotation[] qualifiers;
//
// public AsyncEvent(Object targetEvent, Annotation... qualifiers) {
// super();
//
// if(targetEvent == null)
// throw new IllegalArgumentException("Target event must not be null");
//
// this.targetEvent = targetEvent;
// this.qualifiers = qualifiers;
// }
//
// public Object getTargetEvent() {
// return targetEvent;
// }
//
// public Annotation[] getQualifiers() {
// return qualifiers;
// }
//
// }
//
// Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/async/AsyncTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import javax.enterprise.event.Event;
import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.SchedulerException;
import cz.symbiont_it.cdiqi.api.AsyncEvent;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil;
package cz.symbiont_it.cdiqi.tests.async;
/**
* Simple asynchronous test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class AsyncTest {
@Inject
private QuartzSchedulerManager quartzManager;
@Inject
private AsyncResultStore resultStore;
@Inject | Event<AsyncEvent> event; |
symbiont/cdiqi | cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/async/AsyncTest.java | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/AsyncEvent.java
// public final class AsyncEvent {
//
// private final Object targetEvent;
//
// private final Annotation[] qualifiers;
//
// public AsyncEvent(Object targetEvent, Annotation... qualifiers) {
// super();
//
// if(targetEvent == null)
// throw new IllegalArgumentException("Target event must not be null");
//
// this.targetEvent = targetEvent;
// this.qualifiers = qualifiers;
// }
//
// public Object getTargetEvent() {
// return targetEvent;
// }
//
// public Annotation[] getQualifiers() {
// return qualifiers;
// }
//
// }
//
// Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import javax.enterprise.event.Event;
import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.SchedulerException;
import cz.symbiont_it.cdiqi.api.AsyncEvent;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil; | package cz.symbiont_it.cdiqi.tests.async;
/**
* Simple asynchronous test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class AsyncTest {
@Inject
private QuartzSchedulerManager quartzManager;
@Inject
private AsyncResultStore resultStore;
@Inject
Event<AsyncEvent> event;
@Deployment
public static WebArchive createTestArchive() { | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/AsyncEvent.java
// public final class AsyncEvent {
//
// private final Object targetEvent;
//
// private final Annotation[] qualifiers;
//
// public AsyncEvent(Object targetEvent, Annotation... qualifiers) {
// super();
//
// if(targetEvent == null)
// throw new IllegalArgumentException("Target event must not be null");
//
// this.targetEvent = targetEvent;
// this.qualifiers = qualifiers;
// }
//
// public Object getTargetEvent() {
// return targetEvent;
// }
//
// public Annotation[] getQualifiers() {
// return qualifiers;
// }
//
// }
//
// Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/async/AsyncTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import javax.enterprise.event.Event;
import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.SchedulerException;
import cz.symbiont_it.cdiqi.api.AsyncEvent;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil;
package cz.symbiont_it.cdiqi.tests.async;
/**
* Simple asynchronous test.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class AsyncTest {
@Inject
private QuartzSchedulerManager quartzManager;
@Inject
private AsyncResultStore resultStore;
@Inject
Event<AsyncEvent> event;
@Deployment
public static WebArchive createTestArchive() { | return CdiqiTestUtil.createTestArchive().addPackage( |
symbiont/cdiqi | cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/performance/PerformanceTest.java | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
| import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import java.text.ParseException;
import javax.inject.Inject;
import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil; | package cz.symbiont_it.cdiqi.tests.performance;
/**
* Simple performance test. Useful when testing <a
* href="https://issues.jboss.org/browse/WELD-920">WELD-920</a> memory leak.
*
* This test is ignored by default.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class PerformanceTest {
static final int JOB_EXEC_COUNT = 500;
@Inject | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/performance/PerformanceTest.java
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import java.text.ParseException;
import javax.inject.Inject;
import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil;
package cz.symbiont_it.cdiqi.tests.performance;
/**
* Simple performance test. Useful when testing <a
* href="https://issues.jboss.org/browse/WELD-920">WELD-920</a> memory leak.
*
* This test is ignored by default.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class PerformanceTest {
static final int JOB_EXEC_COUNT = 500;
@Inject | private QuartzSchedulerManager quartzManager; |
symbiont/cdiqi | cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/performance/PerformanceTest.java | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
| import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import java.text.ParseException;
import javax.inject.Inject;
import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil; | package cz.symbiont_it.cdiqi.tests.performance;
/**
* Simple performance test. Useful when testing <a
* href="https://issues.jboss.org/browse/WELD-920">WELD-920</a> memory leak.
*
* This test is ignored by default.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class PerformanceTest {
static final int JOB_EXEC_COUNT = 500;
@Inject
private QuartzSchedulerManager quartzManager;
@Inject
private PerformanceResultStore resultStore;
@Deployment
public static WebArchive createTestArchive() { | // Path: cdiqi-core/src/main/java/cz/symbiont_it/cdiqi/api/QuartzSchedulerManager.java
// public interface QuartzSchedulerManager {
//
// public static final String QUARTZ_PROPERTY_FILE_NAME = "cdiqi-quartz.properties";
//
// /**
// * Perform init.
// *
// * @throws SchedulerException
// */
// public void init() throws SchedulerException;
//
// /**
// * @return <code>true</code> if initialized, <code>false</code> otherwise
// */
// public boolean isInitialized();
//
// /**
// * Start underlying quartz scheduler. If not initialized perform init first.
// *
// * @throws SchedulerException
// */
// public void start() throws SchedulerException;
//
// /**
// * Pause underlying quartz scheduler.
// *
// * @throws SchedulerException
// */
// public void standby() throws SchedulerException;
//
// /**
// * Deletes all scheduling data.
// *
// * @throws SchedulerException
// */
// public void clear() throws SchedulerException;
//
// /**
// * Schedule new job.
// *
// * @param jobDetail
// * @param trigger
// * @throws SchedulerException
// */
// public void schedule(JobDetail jobDetail, Trigger trigger)
// throws SchedulerException;
//
// }
//
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/CdiqiTestUtil.java
// public final class CdiqiTestUtil {
//
// private CdiqiTestUtil() {
// }
//
// /**
// * @return default test archive
// */
// public static WebArchive createTestArchive() {
//
// WebArchive archive = ShrinkWrap.create(WebArchive.class, "test.war");
//
// // API
// archive.addPackage(QuartzSchedulerManager.class.getPackage());
// // SPI
// archive.addPackage(BoundRequestJobListener.class.getPackage());
// // Core impl
// archive.addPackage(QuartzSchedulerManagerImpl.class.getPackage());
// // Weld impl
// archive.addPackage(WeldBoundRequestJobListener.class.getPackage());
//
// archive.addClass(ResultStore.class);
// archive.addAsLibraries(DependencyResolvers
// .use(MavenDependencyResolver.class)
// .artifact("org.quartz-scheduler:quartz:2.0.2")
// .artifact("org.slf4j:slf4j-log4j12:1.6.1")
// .resolveAs(GenericArchive.class));
// archive.addAsResource(new File(
// "src/test/resources/cdiqi-quartz.properties"));
// archive.addAsResource(new File("src/test/resources/log4j.properties"));
// archive.setWebXML(new File("src/test/webapp/WEB-INF/web.xml"));
// archive.addAsWebInfResource(new File("src/test/resources/beans.xml"));
// // archive.addAsWebInfResource(EmptyAsset.INSTANCE,
// // ArchivePaths.create("beans.xml"));
// // ARQ will replace in the end
// // archive.setManifest(new
// // File("src/test/webapp/META-INF/MANIFEST.MF"));
// return archive;
// }
//
// }
// Path: cdiqi-weld/src/test/java/cz/symbiont_it/cdiqi/tests/performance/PerformanceTest.java
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForTotalCount;
import static org.quartz.TriggerBuilder.newTrigger;
import java.text.ParseException;
import javax.inject.Inject;
import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import cz.symbiont_it.cdiqi.api.QuartzSchedulerManager;
import cz.symbiont_it.cdiqi.tests.CdiqiTestUtil;
package cz.symbiont_it.cdiqi.tests.performance;
/**
* Simple performance test. Useful when testing <a
* href="https://issues.jboss.org/browse/WELD-920">WELD-920</a> memory leak.
*
* This test is ignored by default.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class PerformanceTest {
static final int JOB_EXEC_COUNT = 500;
@Inject
private QuartzSchedulerManager quartzManager;
@Inject
private PerformanceResultStore resultStore;
@Deployment
public static WebArchive createTestArchive() { | return CdiqiTestUtil.createTestArchive().addPackage( |
reinhapa/rabbitmq-cdi | src/test/java/net/reini/rabbitmq/cdi/ConsumerHolderTest.java | // Path: src/main/java/net/reini/rabbitmq/cdi/ConsumerHolder.java
// @FunctionalInterface
// interface AckAction {
// void apply(RecoverableChannel channel) throws IOException;
// }
| import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.ConsumerShutdownSignalCallback;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.client.RecoverableChannel;
import com.rabbitmq.client.ShutdownSignalException;
import net.reini.rabbitmq.cdi.ConsumerHolder.AckAction; | BasicProperties properties = MessageProperties.BASIC;
byte[] body = "some body".getBytes();
Envelope envelope = new Envelope(123L, false, "exchange", "routingKey");
Delivery message = new Delivery(envelope, properties, body);
IOException ioe = new IOException("some error");
when(consumerChannelFactoryMock.createChannel()).thenReturn(channelMock);
when(eventConsumerMock.consume("consumerTag", envelope, properties, body)).thenReturn(false);
doThrow(ioe).when(channelMock).basicNack(123L, false, false);
sut.activate();
assertThrows(IOException.class, () -> sut.deliverWithAck("consumerTag", message));
}
@Test
void ensureCompleteShutdown() throws IOException, TimeoutException {
sut = new ConsumerHolder(eventConsumerMock, "queue", true, PREFETCH_COUNT,
consumerChannelFactoryMock, declarationsListMock, declarerRepositoryMock);
when(consumerChannelFactoryMock.createChannel()).thenReturn(channelMock);
sut.activate();
sut.ensureCompleteShutdown();
verify(channelMock).close();
}
@Test
void invokePendingAckAction() throws IOException {
sut = new ConsumerHolder(eventConsumerMock, "queue", true, PREFETCH_COUNT,
consumerChannelFactoryMock, declarationsListMock, declarerRepositoryMock); | // Path: src/main/java/net/reini/rabbitmq/cdi/ConsumerHolder.java
// @FunctionalInterface
// interface AckAction {
// void apply(RecoverableChannel channel) throws IOException;
// }
// Path: src/test/java/net/reini/rabbitmq/cdi/ConsumerHolderTest.java
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.ConsumerShutdownSignalCallback;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.client.RecoverableChannel;
import com.rabbitmq.client.ShutdownSignalException;
import net.reini.rabbitmq.cdi.ConsumerHolder.AckAction;
BasicProperties properties = MessageProperties.BASIC;
byte[] body = "some body".getBytes();
Envelope envelope = new Envelope(123L, false, "exchange", "routingKey");
Delivery message = new Delivery(envelope, properties, body);
IOException ioe = new IOException("some error");
when(consumerChannelFactoryMock.createChannel()).thenReturn(channelMock);
when(eventConsumerMock.consume("consumerTag", envelope, properties, body)).thenReturn(false);
doThrow(ioe).when(channelMock).basicNack(123L, false, false);
sut.activate();
assertThrows(IOException.class, () -> sut.deliverWithAck("consumerTag", message));
}
@Test
void ensureCompleteShutdown() throws IOException, TimeoutException {
sut = new ConsumerHolder(eventConsumerMock, "queue", true, PREFETCH_COUNT,
consumerChannelFactoryMock, declarationsListMock, declarerRepositoryMock);
when(consumerChannelFactoryMock.createChannel()).thenReturn(channelMock);
sut.activate();
sut.ensureCompleteShutdown();
verify(channelMock).close();
}
@Test
void invokePendingAckAction() throws IOException {
sut = new ConsumerHolder(eventConsumerMock, "queue", true, PREFETCH_COUNT,
consumerChannelFactoryMock, declarationsListMock, declarerRepositoryMock); | AckAction action = mock(AckAction.class); |
socialsensor/storm-focused-crawler | src/main/java/eu/socialsensor/focused/crawler/bolts/media/ConceptDetectionBolt.java | // Path: src/main/java/eu/socialsensor/focused/crawler/models/ImageVector.java
// public class ImageVector {
// public String id;
// public double[] v;
// public String url;
//
// public ImageVector(String id, String url, double[] v) {
// this.id = id;
// this.url = url;
// this.v = v;
// }
// }
| import static backtype.storm.utils.Utils.tuple;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.log4j.Logger;
import com.mathworks.toolbox.javabuilder.MWException;
import eu.socialsensor.focused.crawler.models.ImageVector;
import eu.socialsensor.framework.common.domain.Concept;
import eu.socialsensor.framework.common.domain.Concept.ConceptType;
import eu.socialsensor.framework.common.domain.MediaItem;
import gr.iti.mklab.detector.examples.Example;
import gr.iti.mklab.detector.examples.ReadFileToStringList;
import gr.iti.mklab.detector.smal.ConceptDetector;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple; | package eu.socialsensor.focused.crawler.bolts.media;
public class ConceptDetectionBolt extends BaseRichBolt {
/**
* @author Manos Schinas - manosetro@iti.gr
*
* Storm Bolt using to detect concepts in media items. The bolt collects Visual Features
* of Media Items, and periodically runs a Concept Detection method.
*
* For more information in Concept detection algorithm used from ConceptDetectionBolt
* check the following project in github:
* https://github.com/socialsensor/mm-concept-detection-experiments
*
*/
private static final long serialVersionUID = 8098257892768970548L;
private static Logger _logger;
private String matlabFile; | // Path: src/main/java/eu/socialsensor/focused/crawler/models/ImageVector.java
// public class ImageVector {
// public String id;
// public double[] v;
// public String url;
//
// public ImageVector(String id, String url, double[] v) {
// this.id = id;
// this.url = url;
// this.v = v;
// }
// }
// Path: src/main/java/eu/socialsensor/focused/crawler/bolts/media/ConceptDetectionBolt.java
import static backtype.storm.utils.Utils.tuple;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.log4j.Logger;
import com.mathworks.toolbox.javabuilder.MWException;
import eu.socialsensor.focused.crawler.models.ImageVector;
import eu.socialsensor.framework.common.domain.Concept;
import eu.socialsensor.framework.common.domain.Concept.ConceptType;
import eu.socialsensor.framework.common.domain.MediaItem;
import gr.iti.mklab.detector.examples.Example;
import gr.iti.mklab.detector.examples.ReadFileToStringList;
import gr.iti.mklab.detector.smal.ConceptDetector;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
package eu.socialsensor.focused.crawler.bolts.media;
public class ConceptDetectionBolt extends BaseRichBolt {
/**
* @author Manos Schinas - manosetro@iti.gr
*
* Storm Bolt using to detect concepts in media items. The bolt collects Visual Features
* of Media Items, and periodically runs a Concept Detection method.
*
* For more information in Concept detection algorithm used from ConceptDetectionBolt
* check the following project in github:
* https://github.com/socialsensor/mm-concept-detection-experiments
*
*/
private static final long serialVersionUID = 8098257892768970548L;
private static Logger _logger;
private String matlabFile; | private BlockingQueue<Pair<ImageVector, MediaItem>> queue; |
socialsensor/storm-focused-crawler | src/main/java/eu/socialsensor/focused/crawler/utils/ImageExtractor.java | // Path: src/main/java/eu/socialsensor/focused/crawler/utils/Image.java
// public class Image implements Comparable<Image> {
// private final String src;
// private final String width;
// private final String height;
// private final String alt;
// private final int area;
//
// public Image(final String src, final String width, final String height, final String alt) {
// this.src = src;
// if(src == null) {
// throw new NullPointerException("src attribute must not be null");
// }
// this.width = nullTrim(width);
// this.height = nullTrim(height);
// this.alt = nullTrim(alt);
//
// if(width != null && height != null) {
// int a;
// try {
// a = Integer.parseInt(width) * Integer.parseInt(height);
// } catch(NumberFormatException e) {
// a = -1;
// }
// this.area = a;
// } else {
// this.area = -1;
// }
// }
//
// public String getSrc() {
// return src;
// }
//
// public String getWidth() {
// return width;
// }
//
// public String getHeight() {
// return height;
// }
//
// public String getAlt() {
// return alt;
// }
//
// private static String nullTrim(String s) {
// if(s == null) {
// return null;
// }
// s = s.trim();
// if(s.length() == 0) {
// return null;
// }
// return s;
// }
//
// /**
// * Returns the image's area (specified by width * height), or -1 if width/height weren't both specified or could not be parsed.
// *
// * @return
// */
// public int getArea() {
// return area;
// }
//
// public String toString() {
// return src+"\twidth="+width+"\theight="+height+"\talt="+alt+"\tarea="+area;
// }
//
// public int compareTo(Image o) {
// if(o == this) {
// return 0;
// }
// if(area > o.area) {
// return -1;
// } else if(area == o.area) {
// return src.compareTo(o.src);
// } else {
// return 1;
// }
// }
// }
| import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.xerces.parsers.AbstractSAXParser;
import org.cyberneko.html.HTMLConfiguration;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import de.l3s.boilerpipe.BoilerpipeExtractor;
import de.l3s.boilerpipe.BoilerpipeProcessingException;
import de.l3s.boilerpipe.document.TextBlock;
import de.l3s.boilerpipe.document.TextDocument;
import de.l3s.boilerpipe.sax.BoilerpipeSAXInput;
import de.l3s.boilerpipe.sax.HTMLDocument;
import de.l3s.boilerpipe.sax.HTMLFetcher;
import eu.socialsensor.focused.crawler.utils.Image; | package eu.socialsensor.focused.crawler.utils;
/**
* Extracts the images that are enclosed by extracted content.
*
* @author Christian Kohlschütter
*/
public final class ImageExtractor {
public static final ImageExtractor INSTANCE = new ImageExtractor();
/**
* Returns the singleton instance of {@link ImageExtractor}.
*
* @return
*/
public static ImageExtractor getInstance() {
return INSTANCE;
}
private ImageExtractor() {
}
/**
* Processes the given {@link TextDocument} and the original HTML text (as a
* String).
*
* @param doc
* The processed {@link TextDocument}.
* @param origHTML
* The original HTML document.
* @return A List of enclosed {@link Image}s
* @throws BoilerpipeProcessingException
*/ | // Path: src/main/java/eu/socialsensor/focused/crawler/utils/Image.java
// public class Image implements Comparable<Image> {
// private final String src;
// private final String width;
// private final String height;
// private final String alt;
// private final int area;
//
// public Image(final String src, final String width, final String height, final String alt) {
// this.src = src;
// if(src == null) {
// throw new NullPointerException("src attribute must not be null");
// }
// this.width = nullTrim(width);
// this.height = nullTrim(height);
// this.alt = nullTrim(alt);
//
// if(width != null && height != null) {
// int a;
// try {
// a = Integer.parseInt(width) * Integer.parseInt(height);
// } catch(NumberFormatException e) {
// a = -1;
// }
// this.area = a;
// } else {
// this.area = -1;
// }
// }
//
// public String getSrc() {
// return src;
// }
//
// public String getWidth() {
// return width;
// }
//
// public String getHeight() {
// return height;
// }
//
// public String getAlt() {
// return alt;
// }
//
// private static String nullTrim(String s) {
// if(s == null) {
// return null;
// }
// s = s.trim();
// if(s.length() == 0) {
// return null;
// }
// return s;
// }
//
// /**
// * Returns the image's area (specified by width * height), or -1 if width/height weren't both specified or could not be parsed.
// *
// * @return
// */
// public int getArea() {
// return area;
// }
//
// public String toString() {
// return src+"\twidth="+width+"\theight="+height+"\talt="+alt+"\tarea="+area;
// }
//
// public int compareTo(Image o) {
// if(o == this) {
// return 0;
// }
// if(area > o.area) {
// return -1;
// } else if(area == o.area) {
// return src.compareTo(o.src);
// } else {
// return 1;
// }
// }
// }
// Path: src/main/java/eu/socialsensor/focused/crawler/utils/ImageExtractor.java
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.xerces.parsers.AbstractSAXParser;
import org.cyberneko.html.HTMLConfiguration;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import de.l3s.boilerpipe.BoilerpipeExtractor;
import de.l3s.boilerpipe.BoilerpipeProcessingException;
import de.l3s.boilerpipe.document.TextBlock;
import de.l3s.boilerpipe.document.TextDocument;
import de.l3s.boilerpipe.sax.BoilerpipeSAXInput;
import de.l3s.boilerpipe.sax.HTMLDocument;
import de.l3s.boilerpipe.sax.HTMLFetcher;
import eu.socialsensor.focused.crawler.utils.Image;
package eu.socialsensor.focused.crawler.utils;
/**
* Extracts the images that are enclosed by extracted content.
*
* @author Christian Kohlschütter
*/
public final class ImageExtractor {
public static final ImageExtractor INSTANCE = new ImageExtractor();
/**
* Returns the singleton instance of {@link ImageExtractor}.
*
* @return
*/
public static ImageExtractor getInstance() {
return INSTANCE;
}
private ImageExtractor() {
}
/**
* Processes the given {@link TextDocument} and the original HTML text (as a
* String).
*
* @param doc
* The processed {@link TextDocument}.
* @param origHTML
* The original HTML document.
* @return A List of enclosed {@link Image}s
* @throws BoilerpipeProcessingException
*/ | public List<Image> process(final TextDocument doc, |
socialsensor/storm-focused-crawler | src/main/java/eu/socialsensor/focused/crawler/bolts/webpages/RankerBolt.java | // Path: src/main/java/eu/socialsensor/focused/crawler/models/RankedWebPage.java
// public class RankedWebPage implements Comparable<RankedWebPage> {
//
// private WebPage webPage;
// private double score = 0;
//
// public RankedWebPage(WebPage webPage, double score) {
// this.webPage = webPage;
// this.score = score;
// }
//
// public WebPage getWebPage() {
// return webPage;
// }
//
// public double getScore() {
// return score;
// }
//
// @Override
// public String toString() {
// return webPage.getUrl() + " : " + score;
// }
//
// public int compareTo(RankedWebPage other) {
// if(this.score > other.score) {
// return -1;
// }
// return 1;
// }
//
// public static void main(String[] args) {
// PriorityQueue<RankedWebPage> _queue = new PriorityQueue<RankedWebPage>();
//
// RankedWebPage rwp1 = new RankedWebPage(new WebPage("A", "1"), 0.1);
// RankedWebPage rwp2 = new RankedWebPage(new WebPage("B", "1"), 0.2);
// RankedWebPage rwp3 = new RankedWebPage(new WebPage("C", "1"), 0.4);
// RankedWebPage rwp4 = new RankedWebPage(new WebPage("D", "1"), 0.1);
//
// _queue.offer(rwp1);
// _queue.offer(rwp2);
// _queue.offer(rwp3);
// _queue.offer(rwp4);
//
// System.out.println(_queue.poll());
// System.out.println(_queue.poll());
// System.out.println(_queue.poll());
// System.out.println(_queue.poll());
// }
// }
| import static backtype.storm.utils.Utils.tuple;
import java.util.Date;
import java.util.Map;
import java.util.PriorityQueue;
import org.apache.log4j.Logger;
import eu.socialsensor.focused.crawler.models.RankedWebPage;
import eu.socialsensor.framework.common.domain.WebPage;
import eu.socialsensor.framework.common.factories.ItemFactory;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.utils.Utils; | package eu.socialsensor.focused.crawler.bolts.webpages;
public class RankerBolt extends BaseRichBolt {
/**
*
*/
private static final long serialVersionUID = 1L;
private Logger logger;
private static long avgTimeDiff = 10 * 60 * 1000; // 10 minutes
private OutputCollector _collector; | // Path: src/main/java/eu/socialsensor/focused/crawler/models/RankedWebPage.java
// public class RankedWebPage implements Comparable<RankedWebPage> {
//
// private WebPage webPage;
// private double score = 0;
//
// public RankedWebPage(WebPage webPage, double score) {
// this.webPage = webPage;
// this.score = score;
// }
//
// public WebPage getWebPage() {
// return webPage;
// }
//
// public double getScore() {
// return score;
// }
//
// @Override
// public String toString() {
// return webPage.getUrl() + " : " + score;
// }
//
// public int compareTo(RankedWebPage other) {
// if(this.score > other.score) {
// return -1;
// }
// return 1;
// }
//
// public static void main(String[] args) {
// PriorityQueue<RankedWebPage> _queue = new PriorityQueue<RankedWebPage>();
//
// RankedWebPage rwp1 = new RankedWebPage(new WebPage("A", "1"), 0.1);
// RankedWebPage rwp2 = new RankedWebPage(new WebPage("B", "1"), 0.2);
// RankedWebPage rwp3 = new RankedWebPage(new WebPage("C", "1"), 0.4);
// RankedWebPage rwp4 = new RankedWebPage(new WebPage("D", "1"), 0.1);
//
// _queue.offer(rwp1);
// _queue.offer(rwp2);
// _queue.offer(rwp3);
// _queue.offer(rwp4);
//
// System.out.println(_queue.poll());
// System.out.println(_queue.poll());
// System.out.println(_queue.poll());
// System.out.println(_queue.poll());
// }
// }
// Path: src/main/java/eu/socialsensor/focused/crawler/bolts/webpages/RankerBolt.java
import static backtype.storm.utils.Utils.tuple;
import java.util.Date;
import java.util.Map;
import java.util.PriorityQueue;
import org.apache.log4j.Logger;
import eu.socialsensor.focused.crawler.models.RankedWebPage;
import eu.socialsensor.framework.common.domain.WebPage;
import eu.socialsensor.framework.common.factories.ItemFactory;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.utils.Utils;
package eu.socialsensor.focused.crawler.bolts.webpages;
public class RankerBolt extends BaseRichBolt {
/**
*
*/
private static final long serialVersionUID = 1L;
private Logger logger;
private static long avgTimeDiff = 10 * 60 * 1000; // 10 minutes
private OutputCollector _collector; | private PriorityQueue<RankedWebPage> _queue; |
socialsensor/storm-focused-crawler | src/main/java/eu/socialsensor/focused/crawler/bolts/media/FeatureExtractorBolt.java | // Path: src/main/java/eu/socialsensor/focused/crawler/models/ImageVector.java
// public class ImageVector {
// public String id;
// public double[] v;
// public String url;
//
// public ImageVector(String id, String url, double[] v) {
// this.id = id;
// this.url = url;
// this.v = v;
// }
// }
| import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.log4j.Logger;
import eu.socialsensor.focused.crawler.models.ImageVector;
import eu.socialsensor.framework.common.domain.MediaItem;
import gr.iti.mklab.visual.aggregation.VladAggregatorMultipleVocabularies;
import gr.iti.mklab.visual.dimreduction.PCA;
import gr.iti.mklab.visual.extraction.AbstractFeatureExtractor;
import gr.iti.mklab.visual.extraction.SURFExtractor;
import gr.iti.mklab.visual.vectorization.ImageVectorization;
import gr.iti.mklab.visual.vectorization.ImageVectorizationResult;
import static backtype.storm.utils.Utils.tuple;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple; | if(initialLength > targetLengthMax) {
PCA pca = new PCA(targetLengthMax, 1, initialLength, true);
pca.loadPCAFromFile(pcaFile);
ImageVectorization.setPcaProjector(pca);
}
}
public void prepare(@SuppressWarnings("rawtypes") Map stormConf, TopologyContext context,
OutputCollector collector) {
_logger = Logger.getLogger(FeatureExtractorBolt.class);
_collector = collector;
_requestConfig = RequestConfig.custom()
.setSocketTimeout(30000)
.setConnectTimeout(30000)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
_httpclient = HttpClients.custom()
.setConnectionManager(cm)
.build();
}
public void execute(Tuple tuple) {
MediaItem mediaItem = (MediaItem) tuple.getValueByField("MediaItem");
if(mediaItem == null)
return;
HttpGet httpget = null; | // Path: src/main/java/eu/socialsensor/focused/crawler/models/ImageVector.java
// public class ImageVector {
// public String id;
// public double[] v;
// public String url;
//
// public ImageVector(String id, String url, double[] v) {
// this.id = id;
// this.url = url;
// this.v = v;
// }
// }
// Path: src/main/java/eu/socialsensor/focused/crawler/bolts/media/FeatureExtractorBolt.java
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.log4j.Logger;
import eu.socialsensor.focused.crawler.models.ImageVector;
import eu.socialsensor.framework.common.domain.MediaItem;
import gr.iti.mklab.visual.aggregation.VladAggregatorMultipleVocabularies;
import gr.iti.mklab.visual.dimreduction.PCA;
import gr.iti.mklab.visual.extraction.AbstractFeatureExtractor;
import gr.iti.mklab.visual.extraction.SURFExtractor;
import gr.iti.mklab.visual.vectorization.ImageVectorization;
import gr.iti.mklab.visual.vectorization.ImageVectorizationResult;
import static backtype.storm.utils.Utils.tuple;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
if(initialLength > targetLengthMax) {
PCA pca = new PCA(targetLengthMax, 1, initialLength, true);
pca.loadPCAFromFile(pcaFile);
ImageVectorization.setPcaProjector(pca);
}
}
public void prepare(@SuppressWarnings("rawtypes") Map stormConf, TopologyContext context,
OutputCollector collector) {
_logger = Logger.getLogger(FeatureExtractorBolt.class);
_collector = collector;
_requestConfig = RequestConfig.custom()
.setSocketTimeout(30000)
.setConnectTimeout(30000)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
_httpclient = HttpClients.custom()
.setConnectionManager(cm)
.build();
}
public void execute(Tuple tuple) {
MediaItem mediaItem = (MediaItem) tuple.getValueByField("MediaItem");
if(mediaItem == null)
return;
HttpGet httpget = null; | ImageVector imageVector = null; |
socialsensor/storm-focused-crawler | src/main/java/eu/socialsensor/focused/crawler/bolts/media/VisualIndexerBolt.java | // Path: src/main/java/eu/socialsensor/focused/crawler/models/ImageVector.java
// public class ImageVector {
// public String id;
// public double[] v;
// public String url;
//
// public ImageVector(String id, String url, double[] v) {
// this.id = id;
// this.url = url;
// this.v = v;
// }
// }
| import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.log4j.Logger;
import eu.socialsensor.focused.crawler.models.ImageVector;
import eu.socialsensor.framework.client.search.visual.JsonResultSet;
import eu.socialsensor.framework.client.search.visual.JsonResultSet.JsonResult;
import eu.socialsensor.framework.client.search.visual.VisualIndexHandler;
import eu.socialsensor.framework.common.domain.MediaItem;
import gr.iti.mklab.visual.aggregation.VladAggregatorMultipleVocabularies;
import gr.iti.mklab.visual.dimreduction.PCA;
import gr.iti.mklab.visual.extraction.AbstractFeatureExtractor;
import gr.iti.mklab.visual.extraction.SURFExtractor;
import gr.iti.mklab.visual.vectorization.ImageVectorization;
import gr.iti.mklab.visual.vectorization.ImageVectorizationResult;
import static backtype.storm.utils.Utils.tuple;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple; | PCA pca = new PCA(targetLengthMax, 1, initialLength, true);
pca.loadPCAFromFile(pcaFile);
ImageVectorization.setPcaProjector(pca);
}
}
public void prepare(@SuppressWarnings("rawtypes") Map stormConf, TopologyContext context,
OutputCollector collector) {
_logger = Logger.getLogger(VisualIndexerBolt.class);
_collector = collector;
_visualIndex = new VisualIndexHandler(_webServiceHost, _indexCollection);
_requestConfig = RequestConfig.custom()
.setSocketTimeout(30000)
.setConnectTimeout(30000)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
_httpclient = HttpClients.custom()
.setConnectionManager(cm)
.build();
}
public void execute(Tuple tuple) {
MediaItem mediaItem = (MediaItem) tuple.getValueByField("MediaItem");
if(mediaItem == null)
return;
| // Path: src/main/java/eu/socialsensor/focused/crawler/models/ImageVector.java
// public class ImageVector {
// public String id;
// public double[] v;
// public String url;
//
// public ImageVector(String id, String url, double[] v) {
// this.id = id;
// this.url = url;
// this.v = v;
// }
// }
// Path: src/main/java/eu/socialsensor/focused/crawler/bolts/media/VisualIndexerBolt.java
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.log4j.Logger;
import eu.socialsensor.focused.crawler.models.ImageVector;
import eu.socialsensor.framework.client.search.visual.JsonResultSet;
import eu.socialsensor.framework.client.search.visual.JsonResultSet.JsonResult;
import eu.socialsensor.framework.client.search.visual.VisualIndexHandler;
import eu.socialsensor.framework.common.domain.MediaItem;
import gr.iti.mklab.visual.aggregation.VladAggregatorMultipleVocabularies;
import gr.iti.mklab.visual.dimreduction.PCA;
import gr.iti.mklab.visual.extraction.AbstractFeatureExtractor;
import gr.iti.mklab.visual.extraction.SURFExtractor;
import gr.iti.mklab.visual.vectorization.ImageVectorization;
import gr.iti.mklab.visual.vectorization.ImageVectorizationResult;
import static backtype.storm.utils.Utils.tuple;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
PCA pca = new PCA(targetLengthMax, 1, initialLength, true);
pca.loadPCAFromFile(pcaFile);
ImageVectorization.setPcaProjector(pca);
}
}
public void prepare(@SuppressWarnings("rawtypes") Map stormConf, TopologyContext context,
OutputCollector collector) {
_logger = Logger.getLogger(VisualIndexerBolt.class);
_collector = collector;
_visualIndex = new VisualIndexHandler(_webServiceHost, _indexCollection);
_requestConfig = RequestConfig.custom()
.setSocketTimeout(30000)
.setConnectTimeout(30000)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
_httpclient = HttpClients.custom()
.setConnectionManager(cm)
.build();
}
public void execute(Tuple tuple) {
MediaItem mediaItem = (MediaItem) tuple.getValueByField("MediaItem");
if(mediaItem == null)
return;
| ImageVector imageVector = null; |
SimpleServer/SimpleServer | src/simpleserver/Coordinate.java | // Path: src/simpleserver/nbt/NBTByte.java
// public class NBTByte extends NBTag {
// private Byte value;
//
// NBTByte() {
// super();
// }
//
// NBTByte(DataInputStream in, Boolean named) throws Exception {
// super(in, named);
// }
//
// public NBTByte(byte value) {
// set(value);
// }
//
// public NBTByte(String name, byte value) {
// super(name);
// set(value);
// }
//
// @Override
// protected byte id() {
// return 1;
// }
//
// @Override
// public Byte get() {
// return value;
// }
//
// @Override
// void set(String value) {
// if (value.startsWith("0x")) {
// this.value = Integer.valueOf(value.substring(2), 16).byteValue();
// } else {
// this.value = Integer.valueOf(value).byteValue();
// }
// }
//
// public void set(byte value) {
// this.value = value;
// }
//
// @Override
// protected void loadValue(DataInputStream in) throws IOException {
// value = in.readByte();
// }
//
// @Override
// protected void saveValue(DataOutputStream out) throws IOException {
// out.writeByte(value);
// }
//
// @Override
// protected String valueToString(int level) {
// return String.format("0x%1$02x (%1$d)", get());
// }
// }
| import simpleserver.nbt.NBTCompound;
import simpleserver.nbt.NBTInt;
import simpleserver.nbt.NBT;
import simpleserver.nbt.NBTByte; | /*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package simpleserver;
public class Coordinate {
private int x;
private int y;
private int z;
private Dimension dimension;
private final int hashCode;
public Coordinate(int x, int y, int z) {
this(x, y, z, Dimension.EARTH);
}
public Coordinate(int x, int y, int z, Player player) {
this(x, y, z, player.getDimension());
}
public Coordinate(NBTCompound tag) {
// TEMPORARY COMPATIBILITY CODE FOR Y
// tests whether y coordinate was saved as byte (new format: int)
// TODO: Remove check for byte in some future update!
this(tag.getInt("x").get(),
(tag.get("y").type() == NBT.BYTE) ? tag.getByte("y").get() : tag.getInt("y").get(),
tag.getInt("z").get(), | // Path: src/simpleserver/nbt/NBTByte.java
// public class NBTByte extends NBTag {
// private Byte value;
//
// NBTByte() {
// super();
// }
//
// NBTByte(DataInputStream in, Boolean named) throws Exception {
// super(in, named);
// }
//
// public NBTByte(byte value) {
// set(value);
// }
//
// public NBTByte(String name, byte value) {
// super(name);
// set(value);
// }
//
// @Override
// protected byte id() {
// return 1;
// }
//
// @Override
// public Byte get() {
// return value;
// }
//
// @Override
// void set(String value) {
// if (value.startsWith("0x")) {
// this.value = Integer.valueOf(value.substring(2), 16).byteValue();
// } else {
// this.value = Integer.valueOf(value).byteValue();
// }
// }
//
// public void set(byte value) {
// this.value = value;
// }
//
// @Override
// protected void loadValue(DataInputStream in) throws IOException {
// value = in.readByte();
// }
//
// @Override
// protected void saveValue(DataOutputStream out) throws IOException {
// out.writeByte(value);
// }
//
// @Override
// protected String valueToString(int level) {
// return String.format("0x%1$02x (%1$d)", get());
// }
// }
// Path: src/simpleserver/Coordinate.java
import simpleserver.nbt.NBTCompound;
import simpleserver.nbt.NBTInt;
import simpleserver.nbt.NBT;
import simpleserver.nbt.NBTByte;
/*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package simpleserver;
public class Coordinate {
private int x;
private int y;
private int z;
private Dimension dimension;
private final int hashCode;
public Coordinate(int x, int y, int z) {
this(x, y, z, Dimension.EARTH);
}
public Coordinate(int x, int y, int z, Player player) {
this(x, y, z, player.getDimension());
}
public Coordinate(NBTCompound tag) {
// TEMPORARY COMPATIBILITY CODE FOR Y
// tests whether y coordinate was saved as byte (new format: int)
// TODO: Remove check for byte in some future update!
this(tag.getInt("x").get(),
(tag.get("y").type() == NBT.BYTE) ? tag.getByte("y").get() : tag.getInt("y").get(),
tag.getInt("z").get(), | (tag.get("dimension") instanceof NBTByte) ? |
SimpleServer/SimpleServer | src/simpleserver/PlayerList.java | // Path: src/simpleserver/lang/Translations.java
// public static String t(String key) {
// return TranslationsHolder.INSTANCE.get(key);
// }
| import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static simpleserver.lang.Translations.t; | if (name.startsWith(prefix)) {
return players.get(name);
}
}
return null;
}
public Player findPlayerExact(String name) {
return players.get(name.toLowerCase());
}
public synchronized void removePlayer(Player player) {
players.remove(player.getName().toLowerCase());
notifyAll();
}
public synchronized void addPlayer(Player player) {
if (players.size() < server.config.properties.getInt("maxPlayers")) {
players.put(player.getName().toLowerCase(), player);
} else {
Player playerToKick = null;
for (Player friend : players.values()) {
if (!((friend.getGroupId() >= player.getGroupId()) || (playerToKick != null)
&& (friend.getConnectedAt() < playerToKick.getConnectedAt())
&& (friend.getGroupId() > playerToKick.getGroupId()))) {
playerToKick = friend;
}
}
if (playerToKick == null) { | // Path: src/simpleserver/lang/Translations.java
// public static String t(String key) {
// return TranslationsHolder.INSTANCE.get(key);
// }
// Path: src/simpleserver/PlayerList.java
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static simpleserver.lang.Translations.t;
if (name.startsWith(prefix)) {
return players.get(name);
}
}
return null;
}
public Player findPlayerExact(String name) {
return players.get(name.toLowerCase());
}
public synchronized void removePlayer(Player player) {
players.remove(player.getName().toLowerCase());
notifyAll();
}
public synchronized void addPlayer(Player player) {
if (players.size() < server.config.properties.getInt("maxPlayers")) {
players.put(player.getName().toLowerCase(), player);
} else {
Player playerToKick = null;
for (Player friend : players.values()) {
if (!((friend.getGroupId() >= player.getGroupId()) || (playerToKick != null)
&& (friend.getConnectedAt() < playerToKick.getConnectedAt())
&& (friend.getGroupId() > playerToKick.getGroupId()))) {
playerToKick = friend;
}
}
if (playerToKick == null) { | player.kick(t("Sorry, server is full!")); |
SimpleServer/SimpleServer | src/simpleserver/config/GiveAliasList.java | // Path: src/simpleserver/util/DamerauLevenshtein.java
// public static int distance(String a, String b) {
// int n = a.length();
// int m = b.length();
// int d[][] = new int[n + 1][m + 1];
//
// for (int i = 0; i <= n; i++) {
// d[i][0] = i;
// }
//
// for (int j = 1; j <= m; j++) {
// d[0][j] = j;
// }
//
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < m; j++) {
// int k = i + 1;
// int q = j + 1;
// int cost = (a.charAt(i) == b.charAt(j)) ? 0 : 1;
// d[k][q] = Math.min(d[i][q] + 1,
// Math.min(d[k][j] + 1,
// d[i][j] + cost));
// if (i >= 1 && j >= 1 && a.charAt(i) == b.charAt(j - 1) && a.charAt(i - 1) == b.charAt(j)) {
// d[k][q] = Math.min(d[k][q],
// d[i - 1][j - 1] + cost);
// }
// }
// }
//
// return d[n][m];
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import static simpleserver.util.DamerauLevenshtein.distance; |
return item;
}
public String getAlias(int itemId, int damage) {
for (String alias : aliases.keySet()) {
Item i = aliases.get(alias);
if (i.id == itemId && i.damage == damage) {
return alias;
}
}
return null;
}
private Item findWithSuffix(String find) {
for (String suffix : suffixes) {
if (find.endsWith(suffix)) {
int prefixLength = find.length() - suffix.length();
if (aliases.containsKey(find.substring(0, prefixLength))) {
return aliases.get(find.substring(0, prefixLength));
}
}
}
return null;
}
public Suggestion findWithLevenshtein(String find) {
int bestDistance = 100;
String bestItem = null;
for (String name : aliases.keySet()) { | // Path: src/simpleserver/util/DamerauLevenshtein.java
// public static int distance(String a, String b) {
// int n = a.length();
// int m = b.length();
// int d[][] = new int[n + 1][m + 1];
//
// for (int i = 0; i <= n; i++) {
// d[i][0] = i;
// }
//
// for (int j = 1; j <= m; j++) {
// d[0][j] = j;
// }
//
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < m; j++) {
// int k = i + 1;
// int q = j + 1;
// int cost = (a.charAt(i) == b.charAt(j)) ? 0 : 1;
// d[k][q] = Math.min(d[i][q] + 1,
// Math.min(d[k][j] + 1,
// d[i][j] + cost));
// if (i >= 1 && j >= 1 && a.charAt(i) == b.charAt(j - 1) && a.charAt(i - 1) == b.charAt(j)) {
// d[k][q] = Math.min(d[k][q],
// d[i - 1][j - 1] + cost);
// }
// }
// }
//
// return d[n][m];
// }
// Path: src/simpleserver/config/GiveAliasList.java
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import static simpleserver.util.DamerauLevenshtein.distance;
return item;
}
public String getAlias(int itemId, int damage) {
for (String alias : aliases.keySet()) {
Item i = aliases.get(alias);
if (i.id == itemId && i.damage == damage) {
return alias;
}
}
return null;
}
private Item findWithSuffix(String find) {
for (String suffix : suffixes) {
if (find.endsWith(suffix)) {
int prefixLength = find.length() - suffix.length();
if (aliases.containsKey(find.substring(0, prefixLength))) {
return aliases.get(find.substring(0, prefixLength));
}
}
}
return null;
}
public Suggestion findWithLevenshtein(String find) {
int bestDistance = 100;
String bestItem = null;
for (String name : aliases.keySet()) { | int distance = distance(name, find); |
SimpleServer/SimpleServer | src/simpleserver/Position.java | // Path: src/simpleserver/Coordinate.java
// public enum Dimension {
// EARTH(0),
// NETHER(-1),
// END(1),
// LIMBO;
//
// private int index;
//
// Dimension(int index) {
// this.index = index;
// }
//
// Dimension() {
// }
//
// @Override
// public String toString() {
// String name = super.toString();
// return name.substring(0, 1) + name.substring(1).toLowerCase();
// }
//
// private boolean isNamed(String name) {
// return super.toString().equals(name.toUpperCase());
// }
//
// public int index() {
// return index;
// }
//
// public static Dimension get(int index) {
// for (Dimension dim : Dimension.values()) {
// if (dim.index == index) {
// return dim;
// }
// }
// return Dimension.LIMBO;
// }
//
// public static Dimension get(String name) {
// for (Dimension dim : Dimension.values()) {
// if (dim.isNamed(name)) {
// return dim;
// }
// }
// return Dimension.LIMBO;
// }
//
// }
//
// Path: src/simpleserver/nbt/NBTByte.java
// public class NBTByte extends NBTag {
// private Byte value;
//
// NBTByte() {
// super();
// }
//
// NBTByte(DataInputStream in, Boolean named) throws Exception {
// super(in, named);
// }
//
// public NBTByte(byte value) {
// set(value);
// }
//
// public NBTByte(String name, byte value) {
// super(name);
// set(value);
// }
//
// @Override
// protected byte id() {
// return 1;
// }
//
// @Override
// public Byte get() {
// return value;
// }
//
// @Override
// void set(String value) {
// if (value.startsWith("0x")) {
// this.value = Integer.valueOf(value.substring(2), 16).byteValue();
// } else {
// this.value = Integer.valueOf(value).byteValue();
// }
// }
//
// public void set(byte value) {
// this.value = value;
// }
//
// @Override
// protected void loadValue(DataInputStream in) throws IOException {
// value = in.readByte();
// }
//
// @Override
// protected void saveValue(DataOutputStream out) throws IOException {
// out.writeByte(value);
// }
//
// @Override
// protected String valueToString(int level) {
// return String.format("0x%1$02x (%1$d)", get());
// }
// }
| import java.io.DataOutputStream;
import java.io.IOException;
import simpleserver.Coordinate.Dimension;
import simpleserver.nbt.NBTByte;
import simpleserver.nbt.NBTCompound;
import simpleserver.nbt.NBTDouble;
import simpleserver.nbt.NBTFloat;
import simpleserver.nbt.NBTInt; | /*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package simpleserver;
public class Position {
private final static String DIMENSION = "dimension";
private final static String X = "x";
private final static String Y = "y";
private final static String Z = "z";
private final static String YAW = "yaw";
private final static String PITCH = "pitch";
private static final String POSITION = "position";
public double x;
public double y;
public double z;
public double stance; | // Path: src/simpleserver/Coordinate.java
// public enum Dimension {
// EARTH(0),
// NETHER(-1),
// END(1),
// LIMBO;
//
// private int index;
//
// Dimension(int index) {
// this.index = index;
// }
//
// Dimension() {
// }
//
// @Override
// public String toString() {
// String name = super.toString();
// return name.substring(0, 1) + name.substring(1).toLowerCase();
// }
//
// private boolean isNamed(String name) {
// return super.toString().equals(name.toUpperCase());
// }
//
// public int index() {
// return index;
// }
//
// public static Dimension get(int index) {
// for (Dimension dim : Dimension.values()) {
// if (dim.index == index) {
// return dim;
// }
// }
// return Dimension.LIMBO;
// }
//
// public static Dimension get(String name) {
// for (Dimension dim : Dimension.values()) {
// if (dim.isNamed(name)) {
// return dim;
// }
// }
// return Dimension.LIMBO;
// }
//
// }
//
// Path: src/simpleserver/nbt/NBTByte.java
// public class NBTByte extends NBTag {
// private Byte value;
//
// NBTByte() {
// super();
// }
//
// NBTByte(DataInputStream in, Boolean named) throws Exception {
// super(in, named);
// }
//
// public NBTByte(byte value) {
// set(value);
// }
//
// public NBTByte(String name, byte value) {
// super(name);
// set(value);
// }
//
// @Override
// protected byte id() {
// return 1;
// }
//
// @Override
// public Byte get() {
// return value;
// }
//
// @Override
// void set(String value) {
// if (value.startsWith("0x")) {
// this.value = Integer.valueOf(value.substring(2), 16).byteValue();
// } else {
// this.value = Integer.valueOf(value).byteValue();
// }
// }
//
// public void set(byte value) {
// this.value = value;
// }
//
// @Override
// protected void loadValue(DataInputStream in) throws IOException {
// value = in.readByte();
// }
//
// @Override
// protected void saveValue(DataOutputStream out) throws IOException {
// out.writeByte(value);
// }
//
// @Override
// protected String valueToString(int level) {
// return String.format("0x%1$02x (%1$d)", get());
// }
// }
// Path: src/simpleserver/Position.java
import java.io.DataOutputStream;
import java.io.IOException;
import simpleserver.Coordinate.Dimension;
import simpleserver.nbt.NBTByte;
import simpleserver.nbt.NBTCompound;
import simpleserver.nbt.NBTDouble;
import simpleserver.nbt.NBTFloat;
import simpleserver.nbt.NBTInt;
/*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package simpleserver;
public class Position {
private final static String DIMENSION = "dimension";
private final static String X = "x";
private final static String Y = "y";
private final static String Z = "z";
private final static String YAW = "yaw";
private final static String PITCH = "pitch";
private static final String POSITION = "position";
public double x;
public double y;
public double z;
public double stance; | public Dimension dimension; |
SimpleServer/SimpleServer | src/simpleserver/Position.java | // Path: src/simpleserver/Coordinate.java
// public enum Dimension {
// EARTH(0),
// NETHER(-1),
// END(1),
// LIMBO;
//
// private int index;
//
// Dimension(int index) {
// this.index = index;
// }
//
// Dimension() {
// }
//
// @Override
// public String toString() {
// String name = super.toString();
// return name.substring(0, 1) + name.substring(1).toLowerCase();
// }
//
// private boolean isNamed(String name) {
// return super.toString().equals(name.toUpperCase());
// }
//
// public int index() {
// return index;
// }
//
// public static Dimension get(int index) {
// for (Dimension dim : Dimension.values()) {
// if (dim.index == index) {
// return dim;
// }
// }
// return Dimension.LIMBO;
// }
//
// public static Dimension get(String name) {
// for (Dimension dim : Dimension.values()) {
// if (dim.isNamed(name)) {
// return dim;
// }
// }
// return Dimension.LIMBO;
// }
//
// }
//
// Path: src/simpleserver/nbt/NBTByte.java
// public class NBTByte extends NBTag {
// private Byte value;
//
// NBTByte() {
// super();
// }
//
// NBTByte(DataInputStream in, Boolean named) throws Exception {
// super(in, named);
// }
//
// public NBTByte(byte value) {
// set(value);
// }
//
// public NBTByte(String name, byte value) {
// super(name);
// set(value);
// }
//
// @Override
// protected byte id() {
// return 1;
// }
//
// @Override
// public Byte get() {
// return value;
// }
//
// @Override
// void set(String value) {
// if (value.startsWith("0x")) {
// this.value = Integer.valueOf(value.substring(2), 16).byteValue();
// } else {
// this.value = Integer.valueOf(value).byteValue();
// }
// }
//
// public void set(byte value) {
// this.value = value;
// }
//
// @Override
// protected void loadValue(DataInputStream in) throws IOException {
// value = in.readByte();
// }
//
// @Override
// protected void saveValue(DataOutputStream out) throws IOException {
// out.writeByte(value);
// }
//
// @Override
// protected String valueToString(int level) {
// return String.format("0x%1$02x (%1$d)", get());
// }
// }
| import java.io.DataOutputStream;
import java.io.IOException;
import simpleserver.Coordinate.Dimension;
import simpleserver.nbt.NBTByte;
import simpleserver.nbt.NBTCompound;
import simpleserver.nbt.NBTDouble;
import simpleserver.nbt.NBTFloat;
import simpleserver.nbt.NBTInt; | public Position() {
dimension = Dimension.EARTH;
onGround = true;
}
public Position(double x, double y, double z, Dimension dimension) {
this(x, y, z, dimension, 0, 0);
}
public Position(double x, double y, double z, Dimension dimension, float yaw, float pitch) {
this.x = x;
this.y = y;
this.z = z;
this.dimension = dimension;
this.yaw = yaw;
this.pitch = pitch;
onGround = true;
}
public Position(Coordinate coordinate) {
this(coordinate.x(), coordinate.y(), coordinate.z(), coordinate.dimension());
}
public Position(NBTCompound tag) {
x = tag.getDouble(X).get();
y = tag.getDouble(Y).get();
z = tag.getDouble(Z).get();
if (tag.containsKey("Dimension")) {
tag.rename("Dimension", DIMENSION);
} | // Path: src/simpleserver/Coordinate.java
// public enum Dimension {
// EARTH(0),
// NETHER(-1),
// END(1),
// LIMBO;
//
// private int index;
//
// Dimension(int index) {
// this.index = index;
// }
//
// Dimension() {
// }
//
// @Override
// public String toString() {
// String name = super.toString();
// return name.substring(0, 1) + name.substring(1).toLowerCase();
// }
//
// private boolean isNamed(String name) {
// return super.toString().equals(name.toUpperCase());
// }
//
// public int index() {
// return index;
// }
//
// public static Dimension get(int index) {
// for (Dimension dim : Dimension.values()) {
// if (dim.index == index) {
// return dim;
// }
// }
// return Dimension.LIMBO;
// }
//
// public static Dimension get(String name) {
// for (Dimension dim : Dimension.values()) {
// if (dim.isNamed(name)) {
// return dim;
// }
// }
// return Dimension.LIMBO;
// }
//
// }
//
// Path: src/simpleserver/nbt/NBTByte.java
// public class NBTByte extends NBTag {
// private Byte value;
//
// NBTByte() {
// super();
// }
//
// NBTByte(DataInputStream in, Boolean named) throws Exception {
// super(in, named);
// }
//
// public NBTByte(byte value) {
// set(value);
// }
//
// public NBTByte(String name, byte value) {
// super(name);
// set(value);
// }
//
// @Override
// protected byte id() {
// return 1;
// }
//
// @Override
// public Byte get() {
// return value;
// }
//
// @Override
// void set(String value) {
// if (value.startsWith("0x")) {
// this.value = Integer.valueOf(value.substring(2), 16).byteValue();
// } else {
// this.value = Integer.valueOf(value).byteValue();
// }
// }
//
// public void set(byte value) {
// this.value = value;
// }
//
// @Override
// protected void loadValue(DataInputStream in) throws IOException {
// value = in.readByte();
// }
//
// @Override
// protected void saveValue(DataOutputStream out) throws IOException {
// out.writeByte(value);
// }
//
// @Override
// protected String valueToString(int level) {
// return String.format("0x%1$02x (%1$d)", get());
// }
// }
// Path: src/simpleserver/Position.java
import java.io.DataOutputStream;
import java.io.IOException;
import simpleserver.Coordinate.Dimension;
import simpleserver.nbt.NBTByte;
import simpleserver.nbt.NBTCompound;
import simpleserver.nbt.NBTDouble;
import simpleserver.nbt.NBTFloat;
import simpleserver.nbt.NBTInt;
public Position() {
dimension = Dimension.EARTH;
onGround = true;
}
public Position(double x, double y, double z, Dimension dimension) {
this(x, y, z, dimension, 0, 0);
}
public Position(double x, double y, double z, Dimension dimension, float yaw, float pitch) {
this.x = x;
this.y = y;
this.z = z;
this.dimension = dimension;
this.yaw = yaw;
this.pitch = pitch;
onGround = true;
}
public Position(Coordinate coordinate) {
this(coordinate.x(), coordinate.y(), coordinate.z(), coordinate.dimension());
}
public Position(NBTCompound tag) {
x = tag.getDouble(X).get();
y = tag.getDouble(Y).get();
z = tag.getDouble(Z).get();
if (tag.containsKey("Dimension")) {
tag.rename("Dimension", DIMENSION);
} | if (tag.get(DIMENSION) instanceof NBTByte) { |
SimpleServer/SimpleServer | src/simpleserver/Main.java | // Path: src/simpleserver/util/Util.java
// public static void println(Object o) {
// System.out.println("[SimpleServer] " + o);
// }
| import static simpleserver.util.Util.println;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; | public static final int protocolVersion = 78;
public static final String minecraftVersion = "1.6.4";
public static final String version;
static {
String extendedVersion = baseVersion;
if (release) {
extendedVersion += "-" + releaseState;
} else {
String commitversion = getVersionString("VERSION");
if (commitversion != null) {
extendedVersion += "-" + commitversion;
}
}
version = extendedVersion;
}
private static String getVersionString(String file) {
InputStream input = Main.class.getResourceAsStream(file);
String retversion = null;
if (input != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
try {
try {
retversion = reader.readLine();
} finally {
reader.close();
}
} catch (IOException e) { | // Path: src/simpleserver/util/Util.java
// public static void println(Object o) {
// System.out.println("[SimpleServer] " + o);
// }
// Path: src/simpleserver/Main.java
import static simpleserver.util.Util.println;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public static final int protocolVersion = 78;
public static final String minecraftVersion = "1.6.4";
public static final String version;
static {
String extendedVersion = baseVersion;
if (release) {
extendedVersion += "-" + releaseState;
} else {
String commitversion = getVersionString("VERSION");
if (commitversion != null) {
extendedVersion += "-" + commitversion;
}
}
version = extendedVersion;
}
private static String getVersionString(String file) {
InputStream input = Main.class.getResourceAsStream(file);
String retversion = null;
if (input != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
try {
try {
retversion = reader.readLine();
} finally {
reader.close();
}
} catch (IOException e) { | println(e); |
googleapis/google-auth-library-java | oauth2_http/java/com/google/auth/oauth2/AwsRequestSigner.java | // Path: credentials/java/com/google/auth/ServiceAccountSigner.java
// class SigningException extends RuntimeException {
//
// private static final long serialVersionUID = -6503954300538947223L;
//
// public SigningException(String message, Exception cause) {
// super(message, cause);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof SigningException)) {
// return false;
// }
// SigningException other = (SigningException) obj;
// return Objects.equals(getCause(), other.getCause())
// && Objects.equals(getMessage(), other.getMessage());
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(getMessage(), getCause());
// }
// }
| import static com.google.common.base.Preconditions.checkNotNull;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.auth.ServiceAccountSigner.SigningException;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.io.BaseEncoding;
import java.net.URI;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nullable;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec; | Map<String, String> headers = new HashMap<>();
headers.put("host", uri.getHost());
// Only add the date if it hasn't been specified through the "date" header.
if (!additionalHeaders.containsKey("date")) {
headers.put("x-amz-date", defaultDate);
}
if (awsSecurityCredentials.getToken() != null && !awsSecurityCredentials.getToken().isEmpty()) {
headers.put("x-amz-security-token", awsSecurityCredentials.getToken());
}
// Add all additional headers.
for (String key : additionalHeaders.keySet()) {
// Header keys need to be lowercase.
headers.put(key.toLowerCase(Locale.US), additionalHeaders.get(key));
}
return headers;
}
private static byte[] sign(byte[] key, byte[] value) {
try {
String algorithm = "HmacSHA256";
Mac mac = Mac.getInstance(algorithm);
mac.init(new SecretKeySpec(key, algorithm));
return mac.doFinal(value);
} catch (NoSuchAlgorithmException e) {
// Will not occur as HmacSHA256 is supported. We may allow other algorithms in the future.
throw new RuntimeException("HmacSHA256 must be supported by the JVM.", e);
} catch (InvalidKeyException e) { | // Path: credentials/java/com/google/auth/ServiceAccountSigner.java
// class SigningException extends RuntimeException {
//
// private static final long serialVersionUID = -6503954300538947223L;
//
// public SigningException(String message, Exception cause) {
// super(message, cause);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof SigningException)) {
// return false;
// }
// SigningException other = (SigningException) obj;
// return Objects.equals(getCause(), other.getCause())
// && Objects.equals(getMessage(), other.getMessage());
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(getMessage(), getCause());
// }
// }
// Path: oauth2_http/java/com/google/auth/oauth2/AwsRequestSigner.java
import static com.google.common.base.Preconditions.checkNotNull;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.auth.ServiceAccountSigner.SigningException;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.io.BaseEncoding;
import java.net.URI;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nullable;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
Map<String, String> headers = new HashMap<>();
headers.put("host", uri.getHost());
// Only add the date if it hasn't been specified through the "date" header.
if (!additionalHeaders.containsKey("date")) {
headers.put("x-amz-date", defaultDate);
}
if (awsSecurityCredentials.getToken() != null && !awsSecurityCredentials.getToken().isEmpty()) {
headers.put("x-amz-security-token", awsSecurityCredentials.getToken());
}
// Add all additional headers.
for (String key : additionalHeaders.keySet()) {
// Header keys need to be lowercase.
headers.put(key.toLowerCase(Locale.US), additionalHeaders.get(key));
}
return headers;
}
private static byte[] sign(byte[] key, byte[] value) {
try {
String algorithm = "HmacSHA256";
Mac mac = Mac.getInstance(algorithm);
mac.init(new SecretKeySpec(key, algorithm));
return mac.doFinal(value);
} catch (NoSuchAlgorithmException e) {
// Will not occur as HmacSHA256 is supported. We may allow other algorithms in the future.
throw new RuntimeException("HmacSHA256 must be supported by the JVM.", e);
} catch (InvalidKeyException e) { | throw new SigningException("Invalid key used when calculating the AWS V4 Signature", e); |
googleapis/google-auth-library-java | oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java | // Path: oauth2_http/java/com/google/auth/http/HttpTransportFactory.java
// public interface HttpTransportFactory {
//
// /**
// * Creates a {@code HttpTransport} instance.
// *
// * @return The HttpTransport instance.
// */
// HttpTransport create();
// }
| import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.Preconditions;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | /*
* Copyright 2015, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.auth.oauth2;
/** Base type for credentials for authorizing calls to Google APIs using OAuth2. */
public class GoogleCredentials extends OAuth2Credentials {
private static final long serialVersionUID = -1522852442442473691L;
static final String QUOTA_PROJECT_ID_HEADER_KEY = "x-goog-user-project";
static final String USER_FILE_TYPE = "authorized_user";
static final String SERVICE_ACCOUNT_FILE_TYPE = "service_account";
private static final DefaultCredentialsProvider defaultCredentialsProvider =
new DefaultCredentialsProvider();
/**
* Returns the credentials instance from the given access token.
*
* @param accessToken the access token
* @return the credentials instance
*/
public static GoogleCredentials create(AccessToken accessToken) {
return GoogleCredentials.newBuilder().setAccessToken(accessToken).build();
}
/**
* Returns the Application Default Credentials.
*
* <p>Returns the Application Default Credentials which are used to identify and authorize the
* whole application. The following are searched (in order) to find the Application Default
* Credentials:
*
* <ol>
* <li>Credentials file pointed to by the {@code GOOGLE_APPLICATION_CREDENTIALS} environment
* variable
* <li>Credentials provided by the Google Cloud SDK.
* <ol>
* <li>{@code gcloud auth application-default login} for user account credentials.
* <li>{@code gcloud auth application-default login --impersonate-service-account} for
* impersonated service account credentials.
* </ol>
* <li>Google App Engine built-in credentials
* <li>Google Cloud Shell built-in credentials
* <li>Google Compute Engine built-in credentials
* </ol>
*
* @return the credentials instance.
* @throws IOException if the credentials cannot be created in the current environment.
*/
public static GoogleCredentials getApplicationDefault() throws IOException {
return getApplicationDefault(OAuth2Utils.HTTP_TRANSPORT_FACTORY);
}
/**
* Returns the Application Default Credentials.
*
* <p>Returns the Application Default Credentials which are used to identify and authorize the
* whole application. The following are searched (in order) to find the Application Default
* Credentials:
*
* <ol>
* <li>Credentials file pointed to by the {@code GOOGLE_APPLICATION_CREDENTIALS} environment
* variable
* <li>Credentials provided by the Google Cloud SDK {@code gcloud auth application-default
* login} command
* <li>Google App Engine built-in credentials
* <li>Google Cloud Shell built-in credentials
* <li>Google Compute Engine built-in credentials
* </ol>
*
* @param transportFactory HTTP transport factory, creates the transport used to get access
* tokens.
* @return the credentials instance.
* @throws IOException if the credentials cannot be created in the current environment.
*/ | // Path: oauth2_http/java/com/google/auth/http/HttpTransportFactory.java
// public interface HttpTransportFactory {
//
// /**
// * Creates a {@code HttpTransport} instance.
// *
// * @return The HttpTransport instance.
// */
// HttpTransport create();
// }
// Path: oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.Preconditions;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* Copyright 2015, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.auth.oauth2;
/** Base type for credentials for authorizing calls to Google APIs using OAuth2. */
public class GoogleCredentials extends OAuth2Credentials {
private static final long serialVersionUID = -1522852442442473691L;
static final String QUOTA_PROJECT_ID_HEADER_KEY = "x-goog-user-project";
static final String USER_FILE_TYPE = "authorized_user";
static final String SERVICE_ACCOUNT_FILE_TYPE = "service_account";
private static final DefaultCredentialsProvider defaultCredentialsProvider =
new DefaultCredentialsProvider();
/**
* Returns the credentials instance from the given access token.
*
* @param accessToken the access token
* @return the credentials instance
*/
public static GoogleCredentials create(AccessToken accessToken) {
return GoogleCredentials.newBuilder().setAccessToken(accessToken).build();
}
/**
* Returns the Application Default Credentials.
*
* <p>Returns the Application Default Credentials which are used to identify and authorize the
* whole application. The following are searched (in order) to find the Application Default
* Credentials:
*
* <ol>
* <li>Credentials file pointed to by the {@code GOOGLE_APPLICATION_CREDENTIALS} environment
* variable
* <li>Credentials provided by the Google Cloud SDK.
* <ol>
* <li>{@code gcloud auth application-default login} for user account credentials.
* <li>{@code gcloud auth application-default login --impersonate-service-account} for
* impersonated service account credentials.
* </ol>
* <li>Google App Engine built-in credentials
* <li>Google Cloud Shell built-in credentials
* <li>Google Compute Engine built-in credentials
* </ol>
*
* @return the credentials instance.
* @throws IOException if the credentials cannot be created in the current environment.
*/
public static GoogleCredentials getApplicationDefault() throws IOException {
return getApplicationDefault(OAuth2Utils.HTTP_TRANSPORT_FACTORY);
}
/**
* Returns the Application Default Credentials.
*
* <p>Returns the Application Default Credentials which are used to identify and authorize the
* whole application. The following are searched (in order) to find the Application Default
* Credentials:
*
* <ol>
* <li>Credentials file pointed to by the {@code GOOGLE_APPLICATION_CREDENTIALS} environment
* variable
* <li>Credentials provided by the Google Cloud SDK {@code gcloud auth application-default
* login} command
* <li>Google App Engine built-in credentials
* <li>Google Cloud Shell built-in credentials
* <li>Google Compute Engine built-in credentials
* </ol>
*
* @param transportFactory HTTP transport factory, creates the transport used to get access
* tokens.
* @return the credentials instance.
* @throws IOException if the credentials cannot be created in the current environment.
*/ | public static GoogleCredentials getApplicationDefault(HttpTransportFactory transportFactory) |
googleapis/google-auth-library-java | oauth2_http/java/com/google/auth/oauth2/IdentityPoolCredentials.java | // Path: oauth2_http/java/com/google/auth/oauth2/IdentityPoolCredentials.java
// enum CredentialFormatType {
// TEXT,
// JSON
// }
| import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonObjectParser;
import com.google.auth.oauth2.IdentityPoolCredentials.IdentityPoolCredentialSource.CredentialFormatType;
import com.google.common.io.CharStreams;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nullable; | /*
* Copyright 2021 Google LLC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.auth.oauth2;
/**
* Url-sourced and file-sourced external account credentials.
*
* <p>By default, attempts to exchange the external credential for a GCP access token.
*/
public class IdentityPoolCredentials extends ExternalAccountCredentials {
/**
* The IdentityPool credential source. Dictates the retrieval method of the external credential,
* which can either be through a metadata server or a local file.
*/
static class IdentityPoolCredentialSource extends ExternalAccountCredentials.CredentialSource {
enum IdentityPoolCredentialSourceType {
FILE,
URL
}
| // Path: oauth2_http/java/com/google/auth/oauth2/IdentityPoolCredentials.java
// enum CredentialFormatType {
// TEXT,
// JSON
// }
// Path: oauth2_http/java/com/google/auth/oauth2/IdentityPoolCredentials.java
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonObjectParser;
import com.google.auth.oauth2.IdentityPoolCredentials.IdentityPoolCredentialSource.CredentialFormatType;
import com.google.common.io.CharStreams;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nullable;
/*
* Copyright 2021 Google LLC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.auth.oauth2;
/**
* Url-sourced and file-sourced external account credentials.
*
* <p>By default, attempts to exchange the external credential for a GCP access token.
*/
public class IdentityPoolCredentials extends ExternalAccountCredentials {
/**
* The IdentityPool credential source. Dictates the retrieval method of the external credential,
* which can either be through a metadata server or a local file.
*/
static class IdentityPoolCredentialSource extends ExternalAccountCredentials.CredentialSource {
enum IdentityPoolCredentialSourceType {
FILE,
URL
}
| enum CredentialFormatType { |
googleapis/google-auth-library-java | oauth2_http/java/com/google/auth/oauth2/DownscopedCredentials.java | // Path: oauth2_http/java/com/google/auth/http/HttpTransportFactory.java
// public interface HttpTransportFactory {
//
// /**
// * Creates a {@code HttpTransport} instance.
// *
// * @return The HttpTransport instance.
// */
// HttpTransport create();
// }
| import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException; | /*
* Copyright 2021 Google LLC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.auth.oauth2;
/**
* DownscopedCredentials enables the ability to downscope, or restrict, the Identity and Access
* Management (IAM) permissions that a short-lived credential can use for Cloud Storage.
*
* <p>To downscope permissions you must define a {@link CredentialAccessBoundary} which specifies
* the upper bound of permissions that the credential can access. You must also provide a source
* credential which will be used to acquire the downscoped credential.
*
* <p>See <a href='https://cloud.google.com/iam/docs/downscoping-short-lived-credentials'>for more
* information.</a>
*
* <p>Usage:
*
* <pre><code>
* GoogleCredentials sourceCredentials = GoogleCredentials.getApplicationDefault()
* .createScoped("https://www.googleapis.com/auth/cloud-platform");
*
* CredentialAccessBoundary.AccessBoundaryRule rule =
* CredentialAccessBoundary.AccessBoundaryRule.newBuilder()
* .setAvailableResource(
* "//storage.googleapis.com/projects/_/buckets/bucket")
* .addAvailablePermission("inRole:roles/storage.objectViewer")
* .build();
*
* DownscopedCredentials downscopedCredentials =
* DownscopedCredentials.newBuilder()
* .setSourceCredential(sourceCredentials)
* .setCredentialAccessBoundary(
* CredentialAccessBoundary.newBuilder().addRule(rule).build())
* .build();
*
* AccessToken accessToken = downscopedCredentials.refreshAccessToken();
*
* OAuth2Credentials credentials = OAuth2Credentials.create(accessToken);
*
* Storage storage =
* StorageOptions.newBuilder().setCredentials(credentials).build().getService();
*
* Blob blob = storage.get(BlobId.of("bucket", "object"));
* System.out.printf("Blob %s retrieved.", blob.getBlobId());
* </code></pre>
*
* Note that {@link OAuth2CredentialsWithRefresh} can instead be used to consume the downscoped
* token, allowing for automatic token refreshes by providing a {@link
* OAuth2CredentialsWithRefresh.OAuth2RefreshHandler}.
*/
public final class DownscopedCredentials extends OAuth2Credentials {
private static final String TOKEN_EXCHANGE_ENDPOINT = "https://sts.googleapis.com/v1/token";
private final GoogleCredentials sourceCredential;
private final CredentialAccessBoundary credentialAccessBoundary; | // Path: oauth2_http/java/com/google/auth/http/HttpTransportFactory.java
// public interface HttpTransportFactory {
//
// /**
// * Creates a {@code HttpTransport} instance.
// *
// * @return The HttpTransport instance.
// */
// HttpTransport create();
// }
// Path: oauth2_http/java/com/google/auth/oauth2/DownscopedCredentials.java
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
/*
* Copyright 2021 Google LLC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.auth.oauth2;
/**
* DownscopedCredentials enables the ability to downscope, or restrict, the Identity and Access
* Management (IAM) permissions that a short-lived credential can use for Cloud Storage.
*
* <p>To downscope permissions you must define a {@link CredentialAccessBoundary} which specifies
* the upper bound of permissions that the credential can access. You must also provide a source
* credential which will be used to acquire the downscoped credential.
*
* <p>See <a href='https://cloud.google.com/iam/docs/downscoping-short-lived-credentials'>for more
* information.</a>
*
* <p>Usage:
*
* <pre><code>
* GoogleCredentials sourceCredentials = GoogleCredentials.getApplicationDefault()
* .createScoped("https://www.googleapis.com/auth/cloud-platform");
*
* CredentialAccessBoundary.AccessBoundaryRule rule =
* CredentialAccessBoundary.AccessBoundaryRule.newBuilder()
* .setAvailableResource(
* "//storage.googleapis.com/projects/_/buckets/bucket")
* .addAvailablePermission("inRole:roles/storage.objectViewer")
* .build();
*
* DownscopedCredentials downscopedCredentials =
* DownscopedCredentials.newBuilder()
* .setSourceCredential(sourceCredentials)
* .setCredentialAccessBoundary(
* CredentialAccessBoundary.newBuilder().addRule(rule).build())
* .build();
*
* AccessToken accessToken = downscopedCredentials.refreshAccessToken();
*
* OAuth2Credentials credentials = OAuth2Credentials.create(accessToken);
*
* Storage storage =
* StorageOptions.newBuilder().setCredentials(credentials).build().getService();
*
* Blob blob = storage.get(BlobId.of("bucket", "object"));
* System.out.printf("Blob %s retrieved.", blob.getBlobId());
* </code></pre>
*
* Note that {@link OAuth2CredentialsWithRefresh} can instead be used to consume the downscoped
* token, allowing for automatic token refreshes by providing a {@link
* OAuth2CredentialsWithRefresh.OAuth2RefreshHandler}.
*/
public final class DownscopedCredentials extends OAuth2Credentials {
private static final String TOKEN_EXCHANGE_ENDPOINT = "https://sts.googleapis.com/v1/token";
private final GoogleCredentials sourceCredential;
private final CredentialAccessBoundary credentialAccessBoundary; | private final transient HttpTransportFactory transportFactory; |
googleapis/google-auth-library-java | oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java | // Path: oauth2_http/java/com/google/auth/http/AuthHttpConstants.java
// public class AuthHttpConstants {
// /** HTTP "Bearer" authentication scheme */
// public static final String BEARER = "Bearer";
//
// /** HTTP "Authentication" header */
// public static final String AUTHORIZATION = "Authorization";
// }
| import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.json.webtoken.JsonWebSignature;
import com.google.api.client.util.Clock;
import com.google.auth.http.AuthHttpConstants;
import java.io.IOException;
import java.security.PrivateKey;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test; |
Map<String, List<String>> metadata = credentials.getRequestMetadata();
verifyJwtAccess(metadata, "some-audience", "some-issuer", "some-subject", null);
}
private void verifyJwtAccess(
Map<String, List<String>> metadata,
String expectedAudience,
String expectedIssuer,
String expectedSubject,
String expectedKeyId)
throws IOException {
verifyJwtAccess(
metadata,
expectedAudience,
expectedIssuer,
expectedSubject,
expectedKeyId,
Collections.emptyMap());
}
private void verifyJwtAccess(
Map<String, List<String>> metadata,
String expectedAudience,
String expectedIssuer,
String expectedSubject,
String expectedKeyId,
Map<String, String> expectedAdditionalClaims)
throws IOException {
assertNotNull(metadata); | // Path: oauth2_http/java/com/google/auth/http/AuthHttpConstants.java
// public class AuthHttpConstants {
// /** HTTP "Bearer" authentication scheme */
// public static final String BEARER = "Bearer";
//
// /** HTTP "Authentication" header */
// public static final String AUTHORIZATION = "Authorization";
// }
// Path: oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.json.webtoken.JsonWebSignature;
import com.google.api.client.util.Clock;
import com.google.auth.http.AuthHttpConstants;
import java.io.IOException;
import java.security.PrivateKey;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
Map<String, List<String>> metadata = credentials.getRequestMetadata();
verifyJwtAccess(metadata, "some-audience", "some-issuer", "some-subject", null);
}
private void verifyJwtAccess(
Map<String, List<String>> metadata,
String expectedAudience,
String expectedIssuer,
String expectedSubject,
String expectedKeyId)
throws IOException {
verifyJwtAccess(
metadata,
expectedAudience,
expectedIssuer,
expectedSubject,
expectedKeyId,
Collections.emptyMap());
}
private void verifyJwtAccess(
Map<String, List<String>> metadata,
String expectedAudience,
String expectedIssuer,
String expectedSubject,
String expectedKeyId,
Map<String, String> expectedAdditionalClaims)
throws IOException {
assertNotNull(metadata); | List<String> authorizations = metadata.get(AuthHttpConstants.AUTHORIZATION); |
googleapis/google-auth-library-java | oauth2_http/java/com/google/auth/oauth2/TokenVerifier.java | // Path: oauth2_http/java/com/google/auth/http/HttpTransportFactory.java
// public interface HttpTransportFactory {
//
// /**
// * Creates a {@code HttpTransport} instance.
// *
// * @return The HttpTransport instance.
// */
// HttpTransport create();
// }
| import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.webtoken.JsonWebSignature;
import com.google.api.client.util.Base64;
import com.google.api.client.util.Clock;
import com.google.api.client.util.Key;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit; | try {
if (jsonWebSignature.verifySignature(publicKeyToUse)) {
return jsonWebSignature;
}
throw new VerificationException("Invalid signature");
} catch (GeneralSecurityException e) {
throw new VerificationException("Error validating token", e);
}
}
private String getCertificateLocation(JsonWebSignature jsonWebSignature)
throws VerificationException {
if (certificatesLocation != null) return certificatesLocation;
switch (jsonWebSignature.getHeader().getAlgorithm()) {
case "RS256":
return FEDERATED_SIGNON_CERT_URL;
case "ES256":
return IAP_CERT_URL;
}
throw new VerificationException("Unknown algorithm");
}
public static class Builder {
private String audience;
private String certificatesLocation;
private String issuer;
private PublicKey publicKey;
private Clock clock; | // Path: oauth2_http/java/com/google/auth/http/HttpTransportFactory.java
// public interface HttpTransportFactory {
//
// /**
// * Creates a {@code HttpTransport} instance.
// *
// * @return The HttpTransport instance.
// */
// HttpTransport create();
// }
// Path: oauth2_http/java/com/google/auth/oauth2/TokenVerifier.java
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.webtoken.JsonWebSignature;
import com.google.api.client.util.Base64;
import com.google.api.client.util.Clock;
import com.google.api.client.util.Key;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
try {
if (jsonWebSignature.verifySignature(publicKeyToUse)) {
return jsonWebSignature;
}
throw new VerificationException("Invalid signature");
} catch (GeneralSecurityException e) {
throw new VerificationException("Error validating token", e);
}
}
private String getCertificateLocation(JsonWebSignature jsonWebSignature)
throws VerificationException {
if (certificatesLocation != null) return certificatesLocation;
switch (jsonWebSignature.getHeader().getAlgorithm()) {
case "RS256":
return FEDERATED_SIGNON_CERT_URL;
case "ES256":
return IAP_CERT_URL;
}
throw new VerificationException("Unknown algorithm");
}
public static class Builder {
private String audience;
private String certificatesLocation;
private String issuer;
private PublicKey publicKey;
private Clock clock; | private HttpTransportFactory httpTransportFactory; |
googleapis/google-auth-library-java | credentials/javatests/com/google/auth/SigningExceptionTest.java | // Path: credentials/java/com/google/auth/ServiceAccountSigner.java
// class SigningException extends RuntimeException {
//
// private static final long serialVersionUID = -6503954300538947223L;
//
// public SigningException(String message, Exception cause) {
// super(message, cause);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof SigningException)) {
// return false;
// }
// SigningException other = (SigningException) obj;
// return Objects.equals(getCause(), other.getCause())
// && Objects.equals(getMessage(), other.getMessage());
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(getMessage(), getCause());
// }
// }
| import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.auth.ServiceAccountSigner.SigningException;
import org.junit.jupiter.api.Test; | /*
* Copyright 2016, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.auth;
class SigningExceptionTest {
private static final String EXPECTED_MESSAGE = "message";
private static final RuntimeException EXPECTED_CAUSE = new RuntimeException();
@Test
void constructor() { | // Path: credentials/java/com/google/auth/ServiceAccountSigner.java
// class SigningException extends RuntimeException {
//
// private static final long serialVersionUID = -6503954300538947223L;
//
// public SigningException(String message, Exception cause) {
// super(message, cause);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof SigningException)) {
// return false;
// }
// SigningException other = (SigningException) obj;
// return Objects.equals(getCause(), other.getCause())
// && Objects.equals(getMessage(), other.getMessage());
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(getMessage(), getCause());
// }
// }
// Path: credentials/javatests/com/google/auth/SigningExceptionTest.java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.auth.ServiceAccountSigner.SigningException;
import org.junit.jupiter.api.Test;
/*
* Copyright 2016, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.auth;
class SigningExceptionTest {
private static final String EXPECTED_MESSAGE = "message";
private static final RuntimeException EXPECTED_CAUSE = new RuntimeException();
@Test
void constructor() { | SigningException signingException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); |
googleapis/google-auth-library-java | oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java | // Path: oauth2_http/javatests/com/google/auth/TestUtils.java
// public class TestUtils {
//
// private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
//
// public static void assertContainsBearerToken(Map<String, List<String>> metadata, String token) {
// assertNotNull(metadata);
// assertNotNull(token);
// assertTrue(hasBearerToken(metadata, token), "Bearer token not found");
// }
//
// public static void assertNotContainsBearerToken(
// Map<String, List<String>> metadata, String token) {
// assertNotNull(metadata);
// assertNotNull(token);
// assertFalse(hasBearerToken(metadata, token), "Bearer token found");
// }
//
// private static boolean hasBearerToken(Map<String, List<String>> metadata, String token) {
// String expectedValue = AuthHttpConstants.BEARER + " " + token;
// List<String> authorizations = metadata.get(AuthHttpConstants.AUTHORIZATION);
// assertNotNull(authorizations, "Authorization headers not found");
// return authorizations.contains(expectedValue);
// }
//
// public static InputStream jsonToInputStream(GenericJson json) throws IOException {
// json.setFactory(JSON_FACTORY);
// String text = json.toPrettyString();
// return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
// }
//
// public static InputStream stringToInputStream(String text) {
// return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
// }
//
// public static Map<String, String> parseQuery(String query) throws IOException {
// Map<String, String> map = new HashMap<>();
// Iterable<String> entries = Splitter.on('&').split(query);
// for (String entry : entries) {
// List<String> sides = Lists.newArrayList(Splitter.on('=').split(entry));
// if (sides.size() != 2) {
// throw new IOException("Invalid Query String");
// }
// String key = URLDecoder.decode(sides.get(0), "UTF-8");
// String value = URLDecoder.decode(sides.get(1), "UTF-8");
// map.put(key, value);
// }
// return map;
// }
//
// public static String errorJson(String message) throws IOException {
// GenericJson errorResponse = new GenericJson();
// errorResponse.setFactory(JSON_FACTORY);
// GenericJson errorObject = new GenericJson();
// errorObject.put("message", message);
// errorResponse.put("error", errorObject);
// return errorResponse.toPrettyString();
// }
//
// public static HttpResponseException buildHttpResponseException(
// String error, @Nullable String errorDescription, @Nullable String errorUri)
// throws IOException {
// GenericJson json = new GenericJson();
// json.setFactory(GsonFactory.getDefaultInstance());
// json.set("error", error);
// if (errorDescription != null) {
// json.set("error_description", errorDescription);
// }
// if (errorUri != null) {
// json.set("error_uri", errorUri);
// }
// return new HttpResponseException.Builder(
// /* statusCode= */ 400, /* statusMessage= */ "statusMessage", new HttpHeaders())
// .setContent(json.toPrettyString())
// .build();
// }
//
// public static String getDefaultExpireTime() {
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(new Date());
// calendar.add(Calendar.SECOND, 300);
// return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(calendar.getTime());
// }
//
// private TestUtils() {}
// }
| import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.http.LowLevelHttpResponse;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.Json;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.auth.TestUtils;
import com.google.common.base.Joiner;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Queue; | GenericJson response = new GenericJson();
response.setFactory(JSON_FACTORY);
response.put("AccessKeyId", "accessKeyId");
response.put("SecretAccessKey", "secretAccessKey");
response.put("Token", "token");
return new MockLowLevelHttpResponse()
.setContentType(Json.MEDIA_TYPE)
.setContent(response.toString());
}
if (METADATA_SERVER_URL.equals(url)) {
String metadataRequestHeader = getFirstHeaderValue("Metadata-Flavor");
if (!"Google".equals(metadataRequestHeader)) {
throw new IOException("Metadata request header not found.");
}
if (metadataServerContentType != null && metadataServerContentType.equals("json")) {
GenericJson response = new GenericJson();
response.setFactory(JSON_FACTORY);
response.put("subjectToken", SUBJECT_TOKEN);
return new MockLowLevelHttpResponse()
.setContentType(Json.MEDIA_TYPE)
.setContent(response.toString());
}
return new MockLowLevelHttpResponse()
.setContentType("text/html")
.setContent(SUBJECT_TOKEN);
}
if (STS_URL.equals(url)) { | // Path: oauth2_http/javatests/com/google/auth/TestUtils.java
// public class TestUtils {
//
// private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
//
// public static void assertContainsBearerToken(Map<String, List<String>> metadata, String token) {
// assertNotNull(metadata);
// assertNotNull(token);
// assertTrue(hasBearerToken(metadata, token), "Bearer token not found");
// }
//
// public static void assertNotContainsBearerToken(
// Map<String, List<String>> metadata, String token) {
// assertNotNull(metadata);
// assertNotNull(token);
// assertFalse(hasBearerToken(metadata, token), "Bearer token found");
// }
//
// private static boolean hasBearerToken(Map<String, List<String>> metadata, String token) {
// String expectedValue = AuthHttpConstants.BEARER + " " + token;
// List<String> authorizations = metadata.get(AuthHttpConstants.AUTHORIZATION);
// assertNotNull(authorizations, "Authorization headers not found");
// return authorizations.contains(expectedValue);
// }
//
// public static InputStream jsonToInputStream(GenericJson json) throws IOException {
// json.setFactory(JSON_FACTORY);
// String text = json.toPrettyString();
// return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
// }
//
// public static InputStream stringToInputStream(String text) {
// return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
// }
//
// public static Map<String, String> parseQuery(String query) throws IOException {
// Map<String, String> map = new HashMap<>();
// Iterable<String> entries = Splitter.on('&').split(query);
// for (String entry : entries) {
// List<String> sides = Lists.newArrayList(Splitter.on('=').split(entry));
// if (sides.size() != 2) {
// throw new IOException("Invalid Query String");
// }
// String key = URLDecoder.decode(sides.get(0), "UTF-8");
// String value = URLDecoder.decode(sides.get(1), "UTF-8");
// map.put(key, value);
// }
// return map;
// }
//
// public static String errorJson(String message) throws IOException {
// GenericJson errorResponse = new GenericJson();
// errorResponse.setFactory(JSON_FACTORY);
// GenericJson errorObject = new GenericJson();
// errorObject.put("message", message);
// errorResponse.put("error", errorObject);
// return errorResponse.toPrettyString();
// }
//
// public static HttpResponseException buildHttpResponseException(
// String error, @Nullable String errorDescription, @Nullable String errorUri)
// throws IOException {
// GenericJson json = new GenericJson();
// json.setFactory(GsonFactory.getDefaultInstance());
// json.set("error", error);
// if (errorDescription != null) {
// json.set("error_description", errorDescription);
// }
// if (errorUri != null) {
// json.set("error_uri", errorUri);
// }
// return new HttpResponseException.Builder(
// /* statusCode= */ 400, /* statusMessage= */ "statusMessage", new HttpHeaders())
// .setContent(json.toPrettyString())
// .build();
// }
//
// public static String getDefaultExpireTime() {
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(new Date());
// calendar.add(Calendar.SECOND, 300);
// return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(calendar.getTime());
// }
//
// private TestUtils() {}
// }
// Path: oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.http.LowLevelHttpResponse;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.Json;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.auth.TestUtils;
import com.google.common.base.Joiner;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Queue;
GenericJson response = new GenericJson();
response.setFactory(JSON_FACTORY);
response.put("AccessKeyId", "accessKeyId");
response.put("SecretAccessKey", "secretAccessKey");
response.put("Token", "token");
return new MockLowLevelHttpResponse()
.setContentType(Json.MEDIA_TYPE)
.setContent(response.toString());
}
if (METADATA_SERVER_URL.equals(url)) {
String metadataRequestHeader = getFirstHeaderValue("Metadata-Flavor");
if (!"Google".equals(metadataRequestHeader)) {
throw new IOException("Metadata request header not found.");
}
if (metadataServerContentType != null && metadataServerContentType.equals("json")) {
GenericJson response = new GenericJson();
response.setFactory(JSON_FACTORY);
response.put("subjectToken", SUBJECT_TOKEN);
return new MockLowLevelHttpResponse()
.setContentType(Json.MEDIA_TYPE)
.setContent(response.toString());
}
return new MockLowLevelHttpResponse()
.setContentType("text/html")
.setContent(SUBJECT_TOKEN);
}
if (STS_URL.equals(url)) { | Map<String, String> query = TestUtils.parseQuery(getContentAsString()); |
googleapis/google-auth-library-java | oauth2_http/java/com/google/auth/oauth2/DefaultCredentialsProvider.java | // Path: oauth2_http/java/com/google/auth/http/HttpTransportFactory.java
// public interface HttpTransportFactory {
//
// /**
// * Creates a {@code HttpTransport} instance.
// *
// * @return The HttpTransport instance.
// */
// HttpTransport create();
// }
| import com.google.auth.http.HttpTransportFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessControlException;
import java.util.Collections;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger; |
// These variables should only be accessed inside a synchronized block
private GoogleCredentials cachedCredentials = null;
private boolean checkedAppEngine = false;
private boolean checkedComputeEngine = false;
DefaultCredentialsProvider() {}
/**
* Returns the Application Default Credentials.
*
* <p>Returns the Application Default Credentials which are used to identify and authorize the
* whole application. The following are searched (in order) to find the Application Default
* Credentials:
*
* <ol>
* <li>Credentials file pointed to by the {@code GOOGLE_APPLICATION_CREDENTIALS} environment
* variable
* <li>Credentials provided by the Google Cloud SDK {@code gcloud auth application-default
* login} command
* <li>Google App Engine built-in credentials
* <li>Google Cloud Shell built-in credentials
* <li>Google Compute Engine built-in credentials
* </ol>
*
* @param transportFactory HTTP transport factory, creates the transport used to get access
* tokens.
* @return the credentials instance.
* @throws IOException if the credentials cannot be created in the current environment.
*/ | // Path: oauth2_http/java/com/google/auth/http/HttpTransportFactory.java
// public interface HttpTransportFactory {
//
// /**
// * Creates a {@code HttpTransport} instance.
// *
// * @return The HttpTransport instance.
// */
// HttpTransport create();
// }
// Path: oauth2_http/java/com/google/auth/oauth2/DefaultCredentialsProvider.java
import com.google.auth.http.HttpTransportFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessControlException;
import java.util.Collections;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
// These variables should only be accessed inside a synchronized block
private GoogleCredentials cachedCredentials = null;
private boolean checkedAppEngine = false;
private boolean checkedComputeEngine = false;
DefaultCredentialsProvider() {}
/**
* Returns the Application Default Credentials.
*
* <p>Returns the Application Default Credentials which are used to identify and authorize the
* whole application. The following are searched (in order) to find the Application Default
* Credentials:
*
* <ol>
* <li>Credentials file pointed to by the {@code GOOGLE_APPLICATION_CREDENTIALS} environment
* variable
* <li>Credentials provided by the Google Cloud SDK {@code gcloud auth application-default
* login} command
* <li>Google App Engine built-in credentials
* <li>Google Cloud Shell built-in credentials
* <li>Google Compute Engine built-in credentials
* </ol>
*
* @param transportFactory HTTP transport factory, creates the transport used to get access
* tokens.
* @return the credentials instance.
* @throws IOException if the credentials cannot be created in the current environment.
*/ | final GoogleCredentials getDefaultCredentials(HttpTransportFactory transportFactory) |
googleapis/google-auth-library-java | oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java | // Path: oauth2_http/java/com/google/auth/http/HttpTransportFactory.java
// public interface HttpTransportFactory {
//
// /**
// * Creates a {@code HttpTransport} instance.
// *
// * @return The HttpTransport instance.
// */
// HttpTransport create();
// }
| import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.http.LowLevelHttpResponse;
import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.api.client.util.Clock;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.io.CharStreams;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test; | @Test
void verifyExpectedAudience() {
TokenVerifier tokenVerifier =
TokenVerifier.newBuilder().setAudience("expected audience").build();
for (String token : ALL_TOKENS) {
TokenVerifier.VerificationException exception =
assertThrows(
TokenVerifier.VerificationException.class,
() -> tokenVerifier.verify(token),
"Should have thrown a VerificationException");
assertTrue(exception.getMessage().contains("audience does not match"));
}
}
@Test
void verifyExpectedIssuer() {
TokenVerifier tokenVerifier = TokenVerifier.newBuilder().setIssuer("expected issuer").build();
for (String token : ALL_TOKENS) {
TokenVerifier.VerificationException exception =
assertThrows(
TokenVerifier.VerificationException.class,
() -> tokenVerifier.verify(token),
"Should have thrown a VerificationException");
assertTrue(exception.getMessage().contains("issuer does not match"));
}
}
@Test
void verifyEs256Token404CertificateUrl() {
// Mock HTTP requests | // Path: oauth2_http/java/com/google/auth/http/HttpTransportFactory.java
// public interface HttpTransportFactory {
//
// /**
// * Creates a {@code HttpTransport} instance.
// *
// * @return The HttpTransport instance.
// */
// HttpTransport create();
// }
// Path: oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.http.LowLevelHttpResponse;
import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.api.client.util.Clock;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.io.CharStreams;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
@Test
void verifyExpectedAudience() {
TokenVerifier tokenVerifier =
TokenVerifier.newBuilder().setAudience("expected audience").build();
for (String token : ALL_TOKENS) {
TokenVerifier.VerificationException exception =
assertThrows(
TokenVerifier.VerificationException.class,
() -> tokenVerifier.verify(token),
"Should have thrown a VerificationException");
assertTrue(exception.getMessage().contains("audience does not match"));
}
}
@Test
void verifyExpectedIssuer() {
TokenVerifier tokenVerifier = TokenVerifier.newBuilder().setIssuer("expected issuer").build();
for (String token : ALL_TOKENS) {
TokenVerifier.VerificationException exception =
assertThrows(
TokenVerifier.VerificationException.class,
() -> tokenVerifier.verify(token),
"Should have thrown a VerificationException");
assertTrue(exception.getMessage().contains("issuer does not match"));
}
}
@Test
void verifyEs256Token404CertificateUrl() {
// Mock HTTP requests | HttpTransportFactory httpTransportFactory = |
googleapis/google-auth-library-java | oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java | // Path: credentials/java/com/google/auth/RequestMetadataCallback.java
// public interface RequestMetadataCallback {
// /**
// * Called when metadata is successfully produced.
// *
// * @param metadata Metadata returned for the request.
// */
// void onSuccess(Map<String, List<String>> metadata);
//
// /**
// * Called when metadata generation failed.
// *
// * @param exception The thrown exception which caused the request metadata fetch to fail.
// */
// void onFailure(Throwable exception);
// }
//
// Path: credentials/java/com/google/auth/ServiceAccountSigner.java
// public interface ServiceAccountSigner {
//
// class SigningException extends RuntimeException {
//
// private static final long serialVersionUID = -6503954300538947223L;
//
// public SigningException(String message, Exception cause) {
// super(message, cause);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof SigningException)) {
// return false;
// }
// SigningException other = (SigningException) obj;
// return Objects.equals(getCause(), other.getCause())
// && Objects.equals(getMessage(), other.getMessage());
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(getMessage(), getCause());
// }
// }
//
// /**
// * Returns the service account associated with the signer.
// *
// * @return The service account associated with the signer.
// */
// String getAccount();
//
// /**
// * Signs the provided bytes using the private key associated with the service account.
// *
// * @param toSign bytes to sign
// * @return signed bytes
// * @throws SigningException if the attempt to sign the provided bytes failed
// */
// byte[] sign(byte[] toSign);
// }
//
// Path: oauth2_http/java/com/google/auth/http/HttpTransportFactory.java
// public interface HttpTransportFactory {
//
// /**
// * Creates a {@code HttpTransport} instance.
// *
// * @return The HttpTransport instance.
// */
// HttpTransport create();
// }
| import static com.google.common.base.MoreObjects.firstNonNull;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler.BackOffRequired;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.UrlEncodedContent;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.webtoken.JsonWebSignature;
import com.google.api.client.json.webtoken.JsonWebToken;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Joiner;
import com.google.api.client.util.PemReader;
import com.google.api.client.util.PemReader.Section;
import com.google.api.client.util.Preconditions;
import com.google.api.client.util.SecurityUtils;
import com.google.auth.RequestMetadataCallback;
import com.google.auth.ServiceAccountSigner;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executor; |
@VisibleForTesting
JwtCredentials createSelfSignedJwtCredentials(final URI uri) {
// Create a JwtCredentials for self signed JWT. See https://google.aip.dev/auth/4111.
JwtClaims.Builder claimsBuilder =
JwtClaims.newBuilder().setIssuer(clientEmail).setSubject(clientEmail);
if (uri == null) {
// If uri is null, use scopes.
String scopeClaim = "";
if (!scopes.isEmpty()) {
scopeClaim = Joiner.on(' ').join(scopes);
} else {
scopeClaim = Joiner.on(' ').join(defaultScopes);
}
claimsBuilder.setAdditionalClaims(Collections.singletonMap("scope", scopeClaim));
} else {
// otherwise, use audience with the uri.
claimsBuilder.setAudience(getUriForSelfSignedJWT(uri).toString());
}
return JwtCredentials.newBuilder()
.setPrivateKey(privateKey)
.setPrivateKeyId(privateKeyId)
.setJwtClaims(claimsBuilder.build())
.setClock(clock)
.build();
}
@Override
public void getRequestMetadata( | // Path: credentials/java/com/google/auth/RequestMetadataCallback.java
// public interface RequestMetadataCallback {
// /**
// * Called when metadata is successfully produced.
// *
// * @param metadata Metadata returned for the request.
// */
// void onSuccess(Map<String, List<String>> metadata);
//
// /**
// * Called when metadata generation failed.
// *
// * @param exception The thrown exception which caused the request metadata fetch to fail.
// */
// void onFailure(Throwable exception);
// }
//
// Path: credentials/java/com/google/auth/ServiceAccountSigner.java
// public interface ServiceAccountSigner {
//
// class SigningException extends RuntimeException {
//
// private static final long serialVersionUID = -6503954300538947223L;
//
// public SigningException(String message, Exception cause) {
// super(message, cause);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof SigningException)) {
// return false;
// }
// SigningException other = (SigningException) obj;
// return Objects.equals(getCause(), other.getCause())
// && Objects.equals(getMessage(), other.getMessage());
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(getMessage(), getCause());
// }
// }
//
// /**
// * Returns the service account associated with the signer.
// *
// * @return The service account associated with the signer.
// */
// String getAccount();
//
// /**
// * Signs the provided bytes using the private key associated with the service account.
// *
// * @param toSign bytes to sign
// * @return signed bytes
// * @throws SigningException if the attempt to sign the provided bytes failed
// */
// byte[] sign(byte[] toSign);
// }
//
// Path: oauth2_http/java/com/google/auth/http/HttpTransportFactory.java
// public interface HttpTransportFactory {
//
// /**
// * Creates a {@code HttpTransport} instance.
// *
// * @return The HttpTransport instance.
// */
// HttpTransport create();
// }
// Path: oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java
import static com.google.common.base.MoreObjects.firstNonNull;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler.BackOffRequired;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.UrlEncodedContent;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.webtoken.JsonWebSignature;
import com.google.api.client.json.webtoken.JsonWebToken;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Joiner;
import com.google.api.client.util.PemReader;
import com.google.api.client.util.PemReader.Section;
import com.google.api.client.util.Preconditions;
import com.google.api.client.util.SecurityUtils;
import com.google.auth.RequestMetadataCallback;
import com.google.auth.ServiceAccountSigner;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executor;
@VisibleForTesting
JwtCredentials createSelfSignedJwtCredentials(final URI uri) {
// Create a JwtCredentials for self signed JWT. See https://google.aip.dev/auth/4111.
JwtClaims.Builder claimsBuilder =
JwtClaims.newBuilder().setIssuer(clientEmail).setSubject(clientEmail);
if (uri == null) {
// If uri is null, use scopes.
String scopeClaim = "";
if (!scopes.isEmpty()) {
scopeClaim = Joiner.on(' ').join(scopes);
} else {
scopeClaim = Joiner.on(' ').join(defaultScopes);
}
claimsBuilder.setAdditionalClaims(Collections.singletonMap("scope", scopeClaim));
} else {
// otherwise, use audience with the uri.
claimsBuilder.setAudience(getUriForSelfSignedJWT(uri).toString());
}
return JwtCredentials.newBuilder()
.setPrivateKey(privateKey)
.setPrivateKeyId(privateKeyId)
.setJwtClaims(claimsBuilder.build())
.setClock(clock)
.build();
}
@Override
public void getRequestMetadata( | final URI uri, Executor executor, final RequestMetadataCallback callback) { |
googleapis/google-auth-library-java | oauth2_http/java/com/google/auth/oauth2/UserCredentials.java | // Path: oauth2_http/java/com/google/auth/oauth2/OAuth2Utils.java
// static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
//
// Path: oauth2_http/java/com/google/auth/http/HttpTransportFactory.java
// public interface HttpTransportFactory {
//
// /**
// * Creates a {@code HttpTransport} instance.
// *
// * @return The HttpTransport instance.
// */
// HttpTransport create();
// }
| import static com.google.auth.oauth2.OAuth2Utils.JSON_FACTORY;
import static com.google.common.base.MoreObjects.firstNonNull;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.UrlEncodedContent;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Preconditions;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.base.MoreObjects;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects; | .setTokenServerUri(null)
.setQuotaProjectId(quotaProjectId)
.build();
}
/**
* Returns credentials defined by a JSON file stream using the format supported by the Cloud SDK.
*
* @param credentialsStream the stream with the credential definition.
* @return the credential defined by the credentialsStream.
* @throws IOException if the credential cannot be created from the stream.
*/
public static UserCredentials fromStream(InputStream credentialsStream) throws IOException {
return fromStream(credentialsStream, OAuth2Utils.HTTP_TRANSPORT_FACTORY);
}
/**
* Returns credentials defined by a JSON file stream using the format supported by the Cloud SDK.
*
* @param credentialsStream the stream with the credential definition.
* @param transportFactory HTTP transport factory, creates the transport used to get access
* tokens.
* @return the credential defined by the credentialsStream.
* @throws IOException if the credential cannot be created from the stream.
*/
public static UserCredentials fromStream(
InputStream credentialsStream, HttpTransportFactory transportFactory) throws IOException {
Preconditions.checkNotNull(credentialsStream);
Preconditions.checkNotNull(transportFactory);
| // Path: oauth2_http/java/com/google/auth/oauth2/OAuth2Utils.java
// static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
//
// Path: oauth2_http/java/com/google/auth/http/HttpTransportFactory.java
// public interface HttpTransportFactory {
//
// /**
// * Creates a {@code HttpTransport} instance.
// *
// * @return The HttpTransport instance.
// */
// HttpTransport create();
// }
// Path: oauth2_http/java/com/google/auth/oauth2/UserCredentials.java
import static com.google.auth.oauth2.OAuth2Utils.JSON_FACTORY;
import static com.google.common.base.MoreObjects.firstNonNull;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.UrlEncodedContent;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Preconditions;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.base.MoreObjects;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
.setTokenServerUri(null)
.setQuotaProjectId(quotaProjectId)
.build();
}
/**
* Returns credentials defined by a JSON file stream using the format supported by the Cloud SDK.
*
* @param credentialsStream the stream with the credential definition.
* @return the credential defined by the credentialsStream.
* @throws IOException if the credential cannot be created from the stream.
*/
public static UserCredentials fromStream(InputStream credentialsStream) throws IOException {
return fromStream(credentialsStream, OAuth2Utils.HTTP_TRANSPORT_FACTORY);
}
/**
* Returns credentials defined by a JSON file stream using the format supported by the Cloud SDK.
*
* @param credentialsStream the stream with the credential definition.
* @param transportFactory HTTP transport factory, creates the transport used to get access
* tokens.
* @return the credential defined by the credentialsStream.
* @throws IOException if the credential cannot be created from the stream.
*/
public static UserCredentials fromStream(
InputStream credentialsStream, HttpTransportFactory transportFactory) throws IOException {
Preconditions.checkNotNull(credentialsStream);
Preconditions.checkNotNull(transportFactory);
| JsonFactory jsonFactory = JSON_FACTORY; |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/utils/HttpUtils.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public class ChatMessage {
//
// private String name;
//
// private String msg;
//
// private Type type;
//
// private Date date;
//
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// public ChatMessage() {
// }
//
// public ChatMessage(String msg, Type type, Date date) {
// this.msg = msg;
// this.type = type;
// this.date = date;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
//
//
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/Result.java
// public class Result {
//
// private String code;
//
//
// private String text;
//
//
// public String getCode() {
// return code;
// }
//
//
// public void setCode(String code) {
// this.code = code;
// }
//
//
// public String getText() {
// return text;
// }
//
//
// public void setText(String text) {
// this.text = text;
// }
//
//
//
//
//
// }
| import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ustc.dystu.dandelion.bean.ChatMessage;
import com.ustc.dystu.dandelion.bean.ChatMessage.Type;
import com.ustc.dystu.dandelion.bean.Result; | package com.ustc.dystu.dandelion.utils;
public class HttpUtils {
private static final String URLSTR = "http://www.tuling123.com/openapi/api";
private static final String API_KEY = "28404da63d36c39b90880a484c37aaff";
private static InputStream is = null;
private static ByteArrayOutputStream baos = null;
| // Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public class ChatMessage {
//
// private String name;
//
// private String msg;
//
// private Type type;
//
// private Date date;
//
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// public ChatMessage() {
// }
//
// public ChatMessage(String msg, Type type, Date date) {
// this.msg = msg;
// this.type = type;
// this.date = date;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
//
//
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/Result.java
// public class Result {
//
// private String code;
//
//
// private String text;
//
//
// public String getCode() {
// return code;
// }
//
//
// public void setCode(String code) {
// this.code = code;
// }
//
//
// public String getText() {
// return text;
// }
//
//
// public void setText(String text) {
// this.text = text;
// }
//
//
//
//
//
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/HttpUtils.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ustc.dystu.dandelion.bean.ChatMessage;
import com.ustc.dystu.dandelion.bean.ChatMessage.Type;
import com.ustc.dystu.dandelion.bean.Result;
package com.ustc.dystu.dandelion.utils;
public class HttpUtils {
private static final String URLSTR = "http://www.tuling123.com/openapi/api";
private static final String API_KEY = "28404da63d36c39b90880a484c37aaff";
private static InputStream is = null;
private static ByteArrayOutputStream baos = null;
| public static ChatMessage sendMessage(String msg){ |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/utils/HttpUtils.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public class ChatMessage {
//
// private String name;
//
// private String msg;
//
// private Type type;
//
// private Date date;
//
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// public ChatMessage() {
// }
//
// public ChatMessage(String msg, Type type, Date date) {
// this.msg = msg;
// this.type = type;
// this.date = date;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
//
//
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/Result.java
// public class Result {
//
// private String code;
//
//
// private String text;
//
//
// public String getCode() {
// return code;
// }
//
//
// public void setCode(String code) {
// this.code = code;
// }
//
//
// public String getText() {
// return text;
// }
//
//
// public void setText(String text) {
// this.text = text;
// }
//
//
//
//
//
// }
| import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ustc.dystu.dandelion.bean.ChatMessage;
import com.ustc.dystu.dandelion.bean.ChatMessage.Type;
import com.ustc.dystu.dandelion.bean.Result; | package com.ustc.dystu.dandelion.utils;
public class HttpUtils {
private static final String URLSTR = "http://www.tuling123.com/openapi/api";
private static final String API_KEY = "28404da63d36c39b90880a484c37aaff";
private static InputStream is = null;
private static ByteArrayOutputStream baos = null;
public static ChatMessage sendMessage(String msg){
ChatMessage chatMessage = new ChatMessage();
String jsonRes = doGet(msg);
Gson gson = new Gson();
| // Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public class ChatMessage {
//
// private String name;
//
// private String msg;
//
// private Type type;
//
// private Date date;
//
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// public ChatMessage() {
// }
//
// public ChatMessage(String msg, Type type, Date date) {
// this.msg = msg;
// this.type = type;
// this.date = date;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
//
//
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/Result.java
// public class Result {
//
// private String code;
//
//
// private String text;
//
//
// public String getCode() {
// return code;
// }
//
//
// public void setCode(String code) {
// this.code = code;
// }
//
//
// public String getText() {
// return text;
// }
//
//
// public void setText(String text) {
// this.text = text;
// }
//
//
//
//
//
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/HttpUtils.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ustc.dystu.dandelion.bean.ChatMessage;
import com.ustc.dystu.dandelion.bean.ChatMessage.Type;
import com.ustc.dystu.dandelion.bean.Result;
package com.ustc.dystu.dandelion.utils;
public class HttpUtils {
private static final String URLSTR = "http://www.tuling123.com/openapi/api";
private static final String API_KEY = "28404da63d36c39b90880a484c37aaff";
private static InputStream is = null;
private static ByteArrayOutputStream baos = null;
public static ChatMessage sendMessage(String msg){
ChatMessage chatMessage = new ChatMessage();
String jsonRes = doGet(msg);
Gson gson = new Gson();
| Result result = null; |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/utils/HttpUtils.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public class ChatMessage {
//
// private String name;
//
// private String msg;
//
// private Type type;
//
// private Date date;
//
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// public ChatMessage() {
// }
//
// public ChatMessage(String msg, Type type, Date date) {
// this.msg = msg;
// this.type = type;
// this.date = date;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
//
//
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/Result.java
// public class Result {
//
// private String code;
//
//
// private String text;
//
//
// public String getCode() {
// return code;
// }
//
//
// public void setCode(String code) {
// this.code = code;
// }
//
//
// public String getText() {
// return text;
// }
//
//
// public void setText(String text) {
// this.text = text;
// }
//
//
//
//
//
// }
| import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ustc.dystu.dandelion.bean.ChatMessage;
import com.ustc.dystu.dandelion.bean.ChatMessage.Type;
import com.ustc.dystu.dandelion.bean.Result; | package com.ustc.dystu.dandelion.utils;
public class HttpUtils {
private static final String URLSTR = "http://www.tuling123.com/openapi/api";
private static final String API_KEY = "28404da63d36c39b90880a484c37aaff";
private static InputStream is = null;
private static ByteArrayOutputStream baos = null;
public static ChatMessage sendMessage(String msg){
ChatMessage chatMessage = new ChatMessage();
String jsonRes = doGet(msg);
Gson gson = new Gson();
Result result = null;
try {
result = gson.fromJson(jsonRes, Result.class);
chatMessage.setMsg(result.getText());
} catch (JsonSyntaxException e) {
// TODO Auto-generated catch block
chatMessage.setMsg("服务器繁忙,请稍后重试");
}
chatMessage.setDate(new Date());
| // Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public class ChatMessage {
//
// private String name;
//
// private String msg;
//
// private Type type;
//
// private Date date;
//
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// public ChatMessage() {
// }
//
// public ChatMessage(String msg, Type type, Date date) {
// this.msg = msg;
// this.type = type;
// this.date = date;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
//
//
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/Result.java
// public class Result {
//
// private String code;
//
//
// private String text;
//
//
// public String getCode() {
// return code;
// }
//
//
// public void setCode(String code) {
// this.code = code;
// }
//
//
// public String getText() {
// return text;
// }
//
//
// public void setText(String text) {
// this.text = text;
// }
//
//
//
//
//
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/HttpUtils.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ustc.dystu.dandelion.bean.ChatMessage;
import com.ustc.dystu.dandelion.bean.ChatMessage.Type;
import com.ustc.dystu.dandelion.bean.Result;
package com.ustc.dystu.dandelion.utils;
public class HttpUtils {
private static final String URLSTR = "http://www.tuling123.com/openapi/api";
private static final String API_KEY = "28404da63d36c39b90880a484c37aaff";
private static InputStream is = null;
private static ByteArrayOutputStream baos = null;
public static ChatMessage sendMessage(String msg){
ChatMessage chatMessage = new ChatMessage();
String jsonRes = doGet(msg);
Gson gson = new Gson();
Result result = null;
try {
result = gson.fromJson(jsonRes, Result.class);
chatMessage.setMsg(result.getText());
} catch (JsonSyntaxException e) {
// TODO Auto-generated catch block
chatMessage.setMsg("服务器繁忙,请稍后重试");
}
chatMessage.setDate(new Date());
| chatMessage.setType(Type.INCOMING); |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/app/DandelionApplication.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
| import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.ustc.dystu.dandelion.utils.Logger;
import android.app.Application; | package com.ustc.dystu.dandelion.app;
public class DandelionApplication extends Application {
public static final String TAG = "DandelionApplication";
private static DandelionApplication mInstance = null;
public LocationClient mLocationClient = null;
public MyLocationListener myListener;
public static double latitude;
public static double longtitude;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
mLocationClient = new LocationClient(getApplicationContext());
myListener = new MyLocationListener();
mLocationClient.registerLocationListener(myListener);
}
public static DandelionApplication getInstance(){
return mInstance;
}
public class MyLocationListener implements BDLocationListener{
@Override
public void onReceiveLocation(BDLocation location) {
if (location == null) {
return;
}
latitude = location.getLatitude();
longtitude = location.getLongitude(); | // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/app/DandelionApplication.java
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.ustc.dystu.dandelion.utils.Logger;
import android.app.Application;
package com.ustc.dystu.dandelion.app;
public class DandelionApplication extends Application {
public static final String TAG = "DandelionApplication";
private static DandelionApplication mInstance = null;
public LocationClient mLocationClient = null;
public MyLocationListener myListener;
public static double latitude;
public static double longtitude;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
mLocationClient = new LocationClient(getApplicationContext());
myListener = new MyLocationListener();
mLocationClient.registerLocationListener(myListener);
}
public static DandelionApplication getInstance(){
return mInstance;
}
public class MyLocationListener implements BDLocationListener{
@Override
public void onReceiveLocation(BDLocation location) {
if (location == null) {
return;
}
latitude = location.getLatitude();
longtitude = location.getLongitude(); | Logger.i(TAG, "latitude=" + latitude + ";longitude="+longtitude); |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/bean/CommentInfo.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Utils.java
// public class Utils {
//
// public static void share(Context ctx) {
// try {
// Intent intent = new Intent(Intent.ACTION_SEND);
//
// intent.setType("text/plain");
// intent.putExtra(Intent.EXTRA_SUBJECT, "蒲公英");
// intent.putExtra(Intent.EXTRA_TEXT,
// "5秒钟取回你的游记,旅游要低调,分享要奢华,制作游记就用蒲公英。 http://t.cn/8kAQZvD ");
// ctx.startActivity(Intent.createChooser(intent, "分享"));
// } catch (ActivityNotFoundException e) {
// e.printStackTrace();
// Toast.makeText(ctx, "没有找到相关应用!", Toast.LENGTH_SHORT).show();
// }
// }
//
// public static String getTimeBefore(Date date) {
// long delta = System.currentTimeMillis() - date.getTime();
//
// long min = delta / (1000 * 60);
// if (min < 1) {
// return "刚刚";
// }
//
// long hour = min / 60;
// if (hour < 24) {
// return hour + "小时前";
// }
//
// long day = hour / 24;
// if (day < 7) {
// return day + "天前";
// }
//
// long week = day / 7;
// if (week < 5) {
// return week + "周前";
// }
//
// long month = day / 30;
// if (month < 12) {
// return month + "月前";
// }
//
// long year = month / 12;
// return year + "年前";
// }
//
// public static long getWeiboTextLength(String text) {
//
// double len = 0;
// for (int i = 0; i < text.length(); i++) {
// int temp = (int) text.charAt(i);
// if (temp > 0 && temp < 127) {
// len += 0.5;
// } else {
// len++;
// }
// }
// return Math.round(len);
// }
//
// }
| import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ustc.dystu.dandelion.utils.Utils; | }
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
public static CommentInfo create(JSONObject jo) {
try {
CommentInfo info = new CommentInfo();
info.created_at = jo.getString("created_at");
info.id = jo.getString("id");
info.text = jo.getString("text");
info.userInfo = UserInfo.create(jo.getJSONObject("user"));
return info;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
static final DateFormat dateFormat = new SimpleDateFormat(
"EEE MMM dd kk:mm:ss ZZZ yyyy", Locale.US);
public String getFormatTime() {
try {
Date date = dateFormat.parse(created_at); | // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Utils.java
// public class Utils {
//
// public static void share(Context ctx) {
// try {
// Intent intent = new Intent(Intent.ACTION_SEND);
//
// intent.setType("text/plain");
// intent.putExtra(Intent.EXTRA_SUBJECT, "蒲公英");
// intent.putExtra(Intent.EXTRA_TEXT,
// "5秒钟取回你的游记,旅游要低调,分享要奢华,制作游记就用蒲公英。 http://t.cn/8kAQZvD ");
// ctx.startActivity(Intent.createChooser(intent, "分享"));
// } catch (ActivityNotFoundException e) {
// e.printStackTrace();
// Toast.makeText(ctx, "没有找到相关应用!", Toast.LENGTH_SHORT).show();
// }
// }
//
// public static String getTimeBefore(Date date) {
// long delta = System.currentTimeMillis() - date.getTime();
//
// long min = delta / (1000 * 60);
// if (min < 1) {
// return "刚刚";
// }
//
// long hour = min / 60;
// if (hour < 24) {
// return hour + "小时前";
// }
//
// long day = hour / 24;
// if (day < 7) {
// return day + "天前";
// }
//
// long week = day / 7;
// if (week < 5) {
// return week + "周前";
// }
//
// long month = day / 30;
// if (month < 12) {
// return month + "月前";
// }
//
// long year = month / 12;
// return year + "年前";
// }
//
// public static long getWeiboTextLength(String text) {
//
// double len = 0;
// for (int i = 0; i < text.length(); i++) {
// int temp = (int) text.charAt(i);
// if (temp > 0 && temp < 127) {
// len += 0.5;
// } else {
// len++;
// }
// }
// return Math.round(len);
// }
//
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/CommentInfo.java
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ustc.dystu.dandelion.utils.Utils;
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
public static CommentInfo create(JSONObject jo) {
try {
CommentInfo info = new CommentInfo();
info.created_at = jo.getString("created_at");
info.id = jo.getString("id");
info.text = jo.getString("text");
info.userInfo = UserInfo.create(jo.getJSONObject("user"));
return info;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
static final DateFormat dateFormat = new SimpleDateFormat(
"EEE MMM dd kk:mm:ss ZZZ yyyy", Locale.US);
public String getFormatTime() {
try {
Date date = dateFormat.parse(created_at); | return Utils.getTimeBefore(date); |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/fragment/BaseFragmentTabHost.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
| import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import java.util.ArrayList;
import com.ustc.dystu.dandelion.utils.Logger;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.AttributeSet;
import android.view.View; | tabSpec.setContent(new DummyTabFactory(mContext));
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
if (mAttached) {
// If we are already attached to the window, then check to make
// sure this tab's fragment is inactive if it exists. This shouldn't
// normally happen.
info.fragment = mFragmentManager.findFragmentByTag(tag);
if (info.fragment != null && !info.fragment.isDetached()) {
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.detach(info.fragment);
ft.commit();
}
}
mTabs.add(info);
addTab(tabSpec);
}
public BaseFragment getCurrentFragment() {
return (BaseFragment) mFragmentManager.findFragmentByTag(getCurrentTabTag());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
String currentTab = getCurrentTabTag(); | // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/fragment/BaseFragmentTabHost.java
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import java.util.ArrayList;
import com.ustc.dystu.dandelion.utils.Logger;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.AttributeSet;
import android.view.View;
tabSpec.setContent(new DummyTabFactory(mContext));
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
if (mAttached) {
// If we are already attached to the window, then check to make
// sure this tab's fragment is inactive if it exists. This shouldn't
// normally happen.
info.fragment = mFragmentManager.findFragmentByTag(tag);
if (info.fragment != null && !info.fragment.isDetached()) {
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.detach(info.fragment);
ft.commit();
}
}
mTabs.add(info);
addTab(tabSpec);
}
public BaseFragment getCurrentFragment() {
return (BaseFragment) mFragmentManager.findFragmentByTag(getCurrentTabTag());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
String currentTab = getCurrentTabTag(); | Logger.d("TAB", "currentTab:"+currentTab); |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/bean/FootInfo.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
| import java.io.Serializable;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ustc.dystu.dandelion.utils.Logger;
import android.text.TextUtils; | try {
if (!TextUtils.isEmpty(info.original_pic)) {
info.defaultPicId = info.original_pic.substring(
info.original_pic.lastIndexOf("/") + 1,
info.original_pic.lastIndexOf("."));
}
} catch (Exception e) {
e.printStackTrace();
}
if (needUserInfo) {
JSONObject userJo = jo.getJSONObject("user");
UserInfo user = UserInfo.create(userJo);
info.userInfo = user;
}
return info;
}
private static String[] makePicIds(JSONArray array) {
try {
String[] str = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
JSONObject j = array.getJSONObject(i);
String url = j.getString("thumbnail_pic");
if (!TextUtils.isEmpty(url)) {
String id = url.substring(url.lastIndexOf("/") + 1,
url.lastIndexOf("."));
str[i] = id;
| // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/FootInfo.java
import java.io.Serializable;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ustc.dystu.dandelion.utils.Logger;
import android.text.TextUtils;
try {
if (!TextUtils.isEmpty(info.original_pic)) {
info.defaultPicId = info.original_pic.substring(
info.original_pic.lastIndexOf("/") + 1,
info.original_pic.lastIndexOf("."));
}
} catch (Exception e) {
e.printStackTrace();
}
if (needUserInfo) {
JSONObject userJo = jo.getJSONObject("user");
UserInfo user = UserInfo.create(userJo);
info.userInfo = user;
}
return info;
}
private static String[] makePicIds(JSONArray array) {
try {
String[] str = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
JSONObject j = array.getJSONObject(i);
String url = j.getString("thumbnail_pic");
if (!TextUtils.isEmpty(url)) {
String id = url.substring(url.lastIndexOf("/") + 1,
url.lastIndexOf("."));
str[i] = id;
| Logger.d("FootInfo", "make pic ids-->" + id); |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/utils/image/ImageResizer.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
| import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.ustc.dystu.dandelion.BuildConfig;
import com.ustc.dystu.dandelion.utils.Logger; | BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
/**
* Decode and sample down a bitmap from a file to the requested width and height.
*
* @param filename The full path of the file to decode
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return A bitmap sampled down from the original with the same aspect ratio and dimensions
* that are equal to or greater than the requested width and height
*/
public static synchronized Bitmap decodeSampledBitmapFromFile(String filename,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
| // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/image/ImageResizer.java
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.ustc.dystu.dandelion.BuildConfig;
import com.ustc.dystu.dandelion.utils.Logger;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
/**
* Decode and sample down a bitmap from a file to the requested width and height.
*
* @param filename The full path of the file to decode
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return A bitmap sampled down from the original with the same aspect ratio and dimensions
* that are equal to or greater than the requested width and height
*/
public static synchronized Bitmap decodeSampledBitmapFromFile(String filename,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
| Logger.d(TAG, "options.inSampleSize-->" + options.inSampleSize); |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/adapter/ChatMessageAdapter.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public class ChatMessage {
//
// private String name;
//
// private String msg;
//
// private Type type;
//
// private Date date;
//
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// public ChatMessage() {
// }
//
// public ChatMessage(String msg, Type type, Date date) {
// this.msg = msg;
// this.type = type;
// this.date = date;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
//
//
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public enum Type{
// INCOMING,OUTCOMING
//
// }
| import java.text.SimpleDateFormat;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.ustc.dystu.dandelion.R;
import com.ustc.dystu.dandelion.bean.ChatMessage;
import com.ustc.dystu.dandelion.bean.ChatMessage.Type; | package com.ustc.dystu.dandelion.adapter;
public class ChatMessageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
| // Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public class ChatMessage {
//
// private String name;
//
// private String msg;
//
// private Type type;
//
// private Date date;
//
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// public ChatMessage() {
// }
//
// public ChatMessage(String msg, Type type, Date date) {
// this.msg = msg;
// this.type = type;
// this.date = date;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
//
//
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public enum Type{
// INCOMING,OUTCOMING
//
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/adapter/ChatMessageAdapter.java
import java.text.SimpleDateFormat;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.ustc.dystu.dandelion.R;
import com.ustc.dystu.dandelion.bean.ChatMessage;
import com.ustc.dystu.dandelion.bean.ChatMessage.Type;
package com.ustc.dystu.dandelion.adapter;
public class ChatMessageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
| private List<ChatMessage> mDatas; |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/adapter/ChatMessageAdapter.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public class ChatMessage {
//
// private String name;
//
// private String msg;
//
// private Type type;
//
// private Date date;
//
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// public ChatMessage() {
// }
//
// public ChatMessage(String msg, Type type, Date date) {
// this.msg = msg;
// this.type = type;
// this.date = date;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
//
//
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public enum Type{
// INCOMING,OUTCOMING
//
// }
| import java.text.SimpleDateFormat;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.ustc.dystu.dandelion.R;
import com.ustc.dystu.dandelion.bean.ChatMessage;
import com.ustc.dystu.dandelion.bean.ChatMessage.Type; | package com.ustc.dystu.dandelion.adapter;
public class ChatMessageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<ChatMessage> mDatas;
public ChatMessageAdapter(Context context, List<ChatMessage> mDatas) {
mInflater = LayoutInflater.from(context);
this.mDatas = mDatas;
}
@Override
public int getCount() {
return mDatas.size();
}
@Override
public Object getItem(int position) {
return mDatas.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
ChatMessage chatMessage = mDatas.get(position); | // Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public class ChatMessage {
//
// private String name;
//
// private String msg;
//
// private Type type;
//
// private Date date;
//
// public enum Type{
// INCOMING,OUTCOMING
//
// }
//
// public ChatMessage() {
// }
//
// public ChatMessage(String msg, Type type, Date date) {
// this.msg = msg;
// this.type = type;
// this.date = date;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
//
//
//
// }
//
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/ChatMessage.java
// public enum Type{
// INCOMING,OUTCOMING
//
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/adapter/ChatMessageAdapter.java
import java.text.SimpleDateFormat;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.ustc.dystu.dandelion.R;
import com.ustc.dystu.dandelion.bean.ChatMessage;
import com.ustc.dystu.dandelion.bean.ChatMessage.Type;
package com.ustc.dystu.dandelion.adapter;
public class ChatMessageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<ChatMessage> mDatas;
public ChatMessageAdapter(Context context, List<ChatMessage> mDatas) {
mInflater = LayoutInflater.from(context);
this.mDatas = mDatas;
}
@Override
public int getCount() {
return mDatas.size();
}
@Override
public Object getItem(int position) {
return mDatas.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
ChatMessage chatMessage = mDatas.get(position); | if (chatMessage.getType() == Type.INCOMING) { |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/bean/GeoInfo.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
| import java.io.Serializable;
import org.json.JSONException;
import org.json.JSONObject;
import com.ustc.dystu.dandelion.utils.Logger; | package com.ustc.dystu.dandelion.bean;
public class GeoInfo implements Serializable{
public String type;
public String longitude;// 经度
public String latitude;// 纬度
public static GeoInfo create(JSONObject jo){
GeoInfo info;
try {
info = new GeoInfo();
info.type = jo.getString("type");
String coordinates = jo.getString("coordinates"); // [26.66926,100.24685]
coordinates = coordinates.substring(1, coordinates.length() - 1);
| // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/bean/GeoInfo.java
import java.io.Serializable;
import org.json.JSONException;
import org.json.JSONObject;
import com.ustc.dystu.dandelion.utils.Logger;
package com.ustc.dystu.dandelion.bean;
public class GeoInfo implements Serializable{
public String type;
public String longitude;// 经度
public String latitude;// 纬度
public static GeoInfo create(JSONObject jo){
GeoInfo info;
try {
info = new GeoInfo();
info.type = jo.getString("type");
String coordinates = jo.getString("coordinates"); // [26.66926,100.24685]
coordinates = coordinates.substring(1, coordinates.length() - 1);
| Logger.d("GeoInfo", "coordinates-->" + coordinates); |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/net/DandRequestListener.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/fragment/BaseFragment.java
// public abstract class BaseFragment extends Fragment {
//
// private final String TAG = BaseFragment.class.getSimpleName();
//
// public static final int ERROR_RESPONSE = 0x99;
//
// @Override
// public void onAttach(Activity activity) {
// super.onAttach(activity);
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// setHasOptionsMenu(true);
// setMenuVisibility(true);
// super.onCreate(savedInstanceState);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// return super.onCreateView(inflater, container, savedInstanceState);
// }
//
// @Override
// public void onActivityCreated(Bundle savedInstanceState) {
// // onAttach(getActivity());
// afterActivityCreated();
// super.onActivityCreated(savedInstanceState);
// onFragmentShow();
// }
//
// @Override
// public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Logger.d(TAG, "requestCode:"+requestCode);
// super.onActivityResult(requestCode, resultCode, data);
// }
//
// public void onFragmentShow() {
// Logger.d(TAG, "onFragmentShow: " + this.getClass().getName());
// }
//
// public void onFragmentHide() {
// Logger.d(TAG, "onFragmentHide: " + this.getClass().getName());
// }
//
// @Override
// public void onHiddenChanged(boolean hidden) {
// super.onHiddenChanged(hidden);
//
// Logger.d(TAG, "onHiddenChanged: " + this.getClass().getName());
//
// if (!hidden) {
// onFragmentShow();
// } else {
// onFragmentHide();
// }
// }
//
// @Override
// public void onStart() {
// super.onStart();
// }
//
// @Override
// public void onResume() {
// Logger.d(TAG, "onResume: " + this.getClass().getName());
// super.onResume();
// // onFragmentResume();
// }
//
// protected void afterActivityCreated() {
// }
//
// @Override
// public void onPause() {
// Logger.d(TAG, "onPause: " + this.getClass().getName());
// super.onPause();
// // onFragmentPause();
// }
//
// @Override
// public void onStop() {
// super.onStop();
// }
//
// public boolean onBackPressed() {
// return false;
// }
//
// @Override
// public void onDestroyView() {
// super.onDestroyView();
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// }
//
// @Override
// public void onDetach() {
// super.onDetach();
// }
// }
| import android.os.Handler;
import android.os.Message;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.ustc.dystu.dandelion.fragment.BaseFragment; | package com.ustc.dystu.dandelion.net;
public abstract class DandRequestListener implements RequestListener {
private Handler mHandler;
public DandRequestListener(Handler handler) {
mHandler = handler;
}
@Override
public void onComplete(String arg0) {
}
@Override
public void onWeiboException(WeiboException arg0) {
arg0.printStackTrace();
Message msg = Message.obtain(); | // Path: DandelionPro/src/com/ustc/dystu/dandelion/fragment/BaseFragment.java
// public abstract class BaseFragment extends Fragment {
//
// private final String TAG = BaseFragment.class.getSimpleName();
//
// public static final int ERROR_RESPONSE = 0x99;
//
// @Override
// public void onAttach(Activity activity) {
// super.onAttach(activity);
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// setHasOptionsMenu(true);
// setMenuVisibility(true);
// super.onCreate(savedInstanceState);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// return super.onCreateView(inflater, container, savedInstanceState);
// }
//
// @Override
// public void onActivityCreated(Bundle savedInstanceState) {
// // onAttach(getActivity());
// afterActivityCreated();
// super.onActivityCreated(savedInstanceState);
// onFragmentShow();
// }
//
// @Override
// public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Logger.d(TAG, "requestCode:"+requestCode);
// super.onActivityResult(requestCode, resultCode, data);
// }
//
// public void onFragmentShow() {
// Logger.d(TAG, "onFragmentShow: " + this.getClass().getName());
// }
//
// public void onFragmentHide() {
// Logger.d(TAG, "onFragmentHide: " + this.getClass().getName());
// }
//
// @Override
// public void onHiddenChanged(boolean hidden) {
// super.onHiddenChanged(hidden);
//
// Logger.d(TAG, "onHiddenChanged: " + this.getClass().getName());
//
// if (!hidden) {
// onFragmentShow();
// } else {
// onFragmentHide();
// }
// }
//
// @Override
// public void onStart() {
// super.onStart();
// }
//
// @Override
// public void onResume() {
// Logger.d(TAG, "onResume: " + this.getClass().getName());
// super.onResume();
// // onFragmentResume();
// }
//
// protected void afterActivityCreated() {
// }
//
// @Override
// public void onPause() {
// Logger.d(TAG, "onPause: " + this.getClass().getName());
// super.onPause();
// // onFragmentPause();
// }
//
// @Override
// public void onStop() {
// super.onStop();
// }
//
// public boolean onBackPressed() {
// return false;
// }
//
// @Override
// public void onDestroyView() {
// super.onDestroyView();
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// }
//
// @Override
// public void onDetach() {
// super.onDetach();
// }
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/net/DandRequestListener.java
import android.os.Handler;
import android.os.Message;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.ustc.dystu.dandelion.fragment.BaseFragment;
package com.ustc.dystu.dandelion.net;
public abstract class DandRequestListener implements RequestListener {
private Handler mHandler;
public DandRequestListener(Handler handler) {
mHandler = handler;
}
@Override
public void onComplete(String arg0) {
}
@Override
public void onWeiboException(WeiboException arg0) {
arg0.printStackTrace();
Message msg = Message.obtain(); | msg.what = BaseFragment.ERROR_RESPONSE; |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/utils/image/ImageFetcher.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
| import android.net.NetworkInfo;
import com.ustc.dystu.dandelion.BuildConfig;
import com.ustc.dystu.dandelion.utils.Logger;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager; |
return null;
}
@Override
protected Bitmap processBitmap(Object data) {
return processBitmap(String.valueOf(data));
}
/**
* Download a bitmap from a URL, write it to a disk and return the File
* pointer. This implementation uses a simple disk cache.
*
* @param context
* The context to use
* @param urlString
* The URL to fetch
* @return A File pointing to the fetched bitmap
*/
public static File downloadBitmap(Context context, String urlString) {
final File cacheDir = DiskLruCache.getDiskCacheDir(context,
HTTP_CACHE_DIR);
final DiskLruCache cache = DiskLruCache.openCache(context, cacheDir,
HTTP_CACHE_SIZE);
if (cache == null) {
return null;
}
| // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/image/ImageFetcher.java
import android.net.NetworkInfo;
import com.ustc.dystu.dandelion.BuildConfig;
import com.ustc.dystu.dandelion.utils.Logger;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
return null;
}
@Override
protected Bitmap processBitmap(Object data) {
return processBitmap(String.valueOf(data));
}
/**
* Download a bitmap from a URL, write it to a disk and return the File
* pointer. This implementation uses a simple disk cache.
*
* @param context
* The context to use
* @param urlString
* The URL to fetch
* @return A File pointing to the fetched bitmap
*/
public static File downloadBitmap(Context context, String urlString) {
final File cacheDir = DiskLruCache.getDiskCacheDir(context,
HTTP_CACHE_DIR);
final DiskLruCache cache = DiskLruCache.openCache(context, cacheDir,
HTTP_CACHE_SIZE);
if (cache == null) {
return null;
}
| Logger.d(TAG, "downloadBitmap urlString: " + urlString); |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/utils/image/Utils.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
| import java.io.File;
import com.ustc.dystu.dandelion.utils.Logger;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.util.DisplayMetrics;
import android.view.WindowManager; | */
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
public static int[] getScreenWidthAndHeight(Context ctx) {
WindowManager mWm = (WindowManager) ctx
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
// 获取屏幕信息
mWm.getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels;
int screenHeigh = dm.heightPixels;
return new int[] { screenWidth, screenHeigh };
}
public static int[] getMidPicWidthAndHeight(Context ctx){
int[] wh = getScreenWidthAndHeight(ctx);
//return new int[]{wh[0], wh[0]};
return new int[]{300,300};
}
public static int[] getBigPicWidthAndHeight(Context ctx){
int[] wh = getScreenWidthAndHeight(ctx);
| // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/image/Utils.java
import java.io.File;
import com.ustc.dystu.dandelion.utils.Logger;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.util.DisplayMetrics;
import android.view.WindowManager;
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
public static int[] getScreenWidthAndHeight(Context ctx) {
WindowManager mWm = (WindowManager) ctx
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
// 获取屏幕信息
mWm.getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels;
int screenHeigh = dm.heightPixels;
return new int[] { screenWidth, screenHeigh };
}
public static int[] getMidPicWidthAndHeight(Context ctx){
int[] wh = getScreenWidthAndHeight(ctx);
//return new int[]{wh[0], wh[0]};
return new int[]{300,300};
}
public static int[] getBigPicWidthAndHeight(Context ctx){
int[] wh = getScreenWidthAndHeight(ctx);
| Logger.d("Test", "width-->" + wh[0]); |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/utils/image/DiskLruCache.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
| import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import com.sina.weibo.sdk.utils.MD5;
import com.ustc.dystu.dandelion.BuildConfig;
import com.ustc.dystu.dandelion.utils.Logger; | for (int i = 0; i < files.length; i++) {
files[i].delete();
}
} catch (Exception e) {
}
}
/**
* Get a usable cache directory (external if available, internal otherwise).
*
* @param context
* The context to use
* @param uniqueName
* A unique directory name to append to the cache dir
* @return The cache dir
*/
public static File getDiskCacheDir(Context context, String uniqueName) {
// Check if media is mounted or storage is built-in, if so, try and use
// external cache dir
// otherwise use internal cache dir
String cachePath;
try {
cachePath = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED) ? Utils.getExternalCacheDir(
context).getPath() : context.getCacheDir().getPath();
} catch (Exception e) {
cachePath = "/sdcard/sina/vdisk/cache";
}
| // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/image/DiskLruCache.java
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import com.sina.weibo.sdk.utils.MD5;
import com.ustc.dystu.dandelion.BuildConfig;
import com.ustc.dystu.dandelion.utils.Logger;
for (int i = 0; i < files.length; i++) {
files[i].delete();
}
} catch (Exception e) {
}
}
/**
* Get a usable cache directory (external if available, internal otherwise).
*
* @param context
* The context to use
* @param uniqueName
* A unique directory name to append to the cache dir
* @return The cache dir
*/
public static File getDiskCacheDir(Context context, String uniqueName) {
// Check if media is mounted or storage is built-in, if so, try and use
// external cache dir
// otherwise use internal cache dir
String cachePath;
try {
cachePath = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED) ? Utils.getExternalCacheDir(
context).getPath() : context.getCacheDir().getPath();
} catch (Exception e) {
cachePath = "/sdcard/sina/vdisk/cache";
}
| Logger.d(TAG, "cache path-->" + cachePath); |
leerduo/travelinfo | DandelionPro/src/com/ustc/dystu/dandelion/fragment/BaseFragment.java | // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
| import com.ustc.dystu.dandelion.utils.Logger;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; | package com.ustc.dystu.dandelion.fragment;
public abstract class BaseFragment extends Fragment {
private final String TAG = BaseFragment.class.getSimpleName();
public static final int ERROR_RESPONSE = 0x99;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
setMenuVisibility(true);
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// onAttach(getActivity());
afterActivityCreated();
super.onActivityCreated(savedInstanceState);
onFragmentShow();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { | // Path: DandelionPro/src/com/ustc/dystu/dandelion/utils/Logger.java
// public class Logger {
//
// public static int DEBUG_LEVEL = 6;// ÆÁ±Îlog,ÐÞ¸ÄΪ0
//
// private static final int VERBOSE = 5;
// private static final int DEBUG = 4;
// private static final int INFO = 3;
// private static final int WARN = 2;
// private static final int ERROR = 1;
//
// public static int v(String tag, String msg) {
// if (DEBUG_LEVEL > VERBOSE) {
// return Log.v(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int v(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > VERBOSE) { return Log.v(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int d(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > DEBUG) {
// return Log.d(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int i(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > INFO) {
// return Log.i(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int w(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > WARN) {
// return Log.w(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg);
// } else {
// return 0;
// }
// }
//
// public static int e(String tag, String msg, Throwable e) {
// if (DEBUG_LEVEL > ERROR) {
// return Log.e(tag, msg, e);
// } else {
// return 0;
// }
// }
//
// }
// Path: DandelionPro/src/com/ustc/dystu/dandelion/fragment/BaseFragment.java
import com.ustc.dystu.dandelion.utils.Logger;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
package com.ustc.dystu.dandelion.fragment;
public abstract class BaseFragment extends Fragment {
private final String TAG = BaseFragment.class.getSimpleName();
public static final int ERROR_RESPONSE = 0x99;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
setMenuVisibility(true);
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// onAttach(getActivity());
afterActivityCreated();
super.onActivityCreated(savedInstanceState);
onFragmentShow();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { | Logger.d(TAG, "requestCode:"+requestCode); |
ieg-vienna/EvalBench | src/evaluation/evalBench/panel/DateQuestionPanelStrategy.java | // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/DateQuestion.java
// public class DateQuestion extends Question {
//
// private Date m_correctAnswer = null;
// private Date m_givenAnswer = null;
//
// public DateQuestion() {
// this("", "");
// }
//
// public DateQuestion(String aQuestionId, String aQuestionText) {
// super(aQuestionId, aQuestionText);
// }
//
// @Override
// @XmlElement
// public Date getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public void setCorrectAnswer(Date m_correctAnswer) {
// this.m_correctAnswer = m_correctAnswer;
// }
//
// @Override
// @XmlElement
// public Date getGivenAnswer() {
// return m_givenAnswer;
// }
//
// public void setGivenAnswer(Date m_givenAnswer) {
// this.m_givenAnswer = m_givenAnswer;
// }
//
// @Override
// public Question clone() {
// DateQuestion clone = (DateQuestion) super.clone();
//
// if (m_correctAnswer != null) {
// clone.m_correctAnswer = new Date(m_correctAnswer.getTime());
// }
//
// if (m_givenAnswer != null) {
// clone.m_givenAnswer = new Date(m_givenAnswer.getTime());
// }
//
// return clone;
// }
// }
| import java.util.Date;
import javax.swing.JComponent;
import com.toedter.calendar.JCalendar;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.DateQuestion; | package evaluation.evalBench.panel;
public class DateQuestionPanelStrategy extends QuestionPanelStrategy {
//private JPanel answeringPanel;
private JCalendar calendar;
| // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/DateQuestion.java
// public class DateQuestion extends Question {
//
// private Date m_correctAnswer = null;
// private Date m_givenAnswer = null;
//
// public DateQuestion() {
// this("", "");
// }
//
// public DateQuestion(String aQuestionId, String aQuestionText) {
// super(aQuestionId, aQuestionText);
// }
//
// @Override
// @XmlElement
// public Date getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public void setCorrectAnswer(Date m_correctAnswer) {
// this.m_correctAnswer = m_correctAnswer;
// }
//
// @Override
// @XmlElement
// public Date getGivenAnswer() {
// return m_givenAnswer;
// }
//
// public void setGivenAnswer(Date m_givenAnswer) {
// this.m_givenAnswer = m_givenAnswer;
// }
//
// @Override
// public Question clone() {
// DateQuestion clone = (DateQuestion) super.clone();
//
// if (m_correctAnswer != null) {
// clone.m_correctAnswer = new Date(m_correctAnswer.getTime());
// }
//
// if (m_givenAnswer != null) {
// clone.m_givenAnswer = new Date(m_givenAnswer.getTime());
// }
//
// return clone;
// }
// }
// Path: src/evaluation/evalBench/panel/DateQuestionPanelStrategy.java
import java.util.Date;
import javax.swing.JComponent;
import com.toedter.calendar.JCalendar;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.DateQuestion;
package evaluation.evalBench.panel;
public class DateQuestionPanelStrategy extends QuestionPanelStrategy {
//private JPanel answeringPanel;
private JCalendar calendar;
| public DateQuestionPanelStrategy(DateQuestion aQuestion) { |
ieg-vienna/EvalBench | src/evaluation/evalBench/panel/DateQuestionPanelStrategy.java | // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/DateQuestion.java
// public class DateQuestion extends Question {
//
// private Date m_correctAnswer = null;
// private Date m_givenAnswer = null;
//
// public DateQuestion() {
// this("", "");
// }
//
// public DateQuestion(String aQuestionId, String aQuestionText) {
// super(aQuestionId, aQuestionText);
// }
//
// @Override
// @XmlElement
// public Date getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public void setCorrectAnswer(Date m_correctAnswer) {
// this.m_correctAnswer = m_correctAnswer;
// }
//
// @Override
// @XmlElement
// public Date getGivenAnswer() {
// return m_givenAnswer;
// }
//
// public void setGivenAnswer(Date m_givenAnswer) {
// this.m_givenAnswer = m_givenAnswer;
// }
//
// @Override
// public Question clone() {
// DateQuestion clone = (DateQuestion) super.clone();
//
// if (m_correctAnswer != null) {
// clone.m_correctAnswer = new Date(m_correctAnswer.getTime());
// }
//
// if (m_givenAnswer != null) {
// clone.m_givenAnswer = new Date(m_givenAnswer.getTime());
// }
//
// return clone;
// }
// }
| import java.util.Date;
import javax.swing.JComponent;
import com.toedter.calendar.JCalendar;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.DateQuestion; | package evaluation.evalBench.panel;
public class DateQuestionPanelStrategy extends QuestionPanelStrategy {
//private JPanel answeringPanel;
private JCalendar calendar;
public DateQuestionPanelStrategy(DateQuestion aQuestion) {
super(aQuestion);
}
@Override
public boolean checkForCorrectInput() {
if (calendar.getDate() != null) {
Date selectedDate = calendar.getDate();
// DateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
// String formatedDate = formatDate.format(selectedDate);
((DateQuestion) super.getQuestion()).setGivenAnswer(selectedDate);
setErrorMessage("");
return true;
}
| // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/DateQuestion.java
// public class DateQuestion extends Question {
//
// private Date m_correctAnswer = null;
// private Date m_givenAnswer = null;
//
// public DateQuestion() {
// this("", "");
// }
//
// public DateQuestion(String aQuestionId, String aQuestionText) {
// super(aQuestionId, aQuestionText);
// }
//
// @Override
// @XmlElement
// public Date getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public void setCorrectAnswer(Date m_correctAnswer) {
// this.m_correctAnswer = m_correctAnswer;
// }
//
// @Override
// @XmlElement
// public Date getGivenAnswer() {
// return m_givenAnswer;
// }
//
// public void setGivenAnswer(Date m_givenAnswer) {
// this.m_givenAnswer = m_givenAnswer;
// }
//
// @Override
// public Question clone() {
// DateQuestion clone = (DateQuestion) super.clone();
//
// if (m_correctAnswer != null) {
// clone.m_correctAnswer = new Date(m_correctAnswer.getTime());
// }
//
// if (m_givenAnswer != null) {
// clone.m_givenAnswer = new Date(m_givenAnswer.getTime());
// }
//
// return clone;
// }
// }
// Path: src/evaluation/evalBench/panel/DateQuestionPanelStrategy.java
import java.util.Date;
import javax.swing.JComponent;
import com.toedter.calendar.JCalendar;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.DateQuestion;
package evaluation.evalBench.panel;
public class DateQuestionPanelStrategy extends QuestionPanelStrategy {
//private JPanel answeringPanel;
private JCalendar calendar;
public DateQuestionPanelStrategy(DateQuestion aQuestion) {
super(aQuestion);
}
@Override
public boolean checkForCorrectInput() {
if (calendar.getDate() != null) {
Date selectedDate = calendar.getDate();
// DateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
// String formatedDate = formatDate.format(selectedDate);
((DateQuestion) super.getQuestion()).setGivenAnswer(selectedDate);
setErrorMessage("");
return true;
}
| setErrorMessage(EvaluationResources.getString("datequestion.errorNull")); |
ieg-vienna/EvalBench | src/evaluation/evalBench/panel/TextInputQuestionPanelStrategy.java | // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/TextInputQuestion.java
// public class TextInputQuestion extends Question {
//
// // TODO property ignore case?
//
// private String m_correctAnswer = null;
// private String m_givenAnswer = null;
// private boolean m_singleLine = true;
//
// private String m_regEx = null;
//
// public TextInputQuestion() {
// this("", "");
// }
//
// /**
// * @param aQuestionId
// * @param aQuestionText
// */
// public TextInputQuestion(String aQuestionId, String aQuestionText) {
// super(aQuestionId, aQuestionText);
// }
//
// @Override
// @XmlElement
// public String getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public TextInputQuestion(String aQuestionId, String aQuestionText,
// String correctAnswer, boolean singleLine, String regEx) {
// super(aQuestionId, aQuestionText);
// this.m_correctAnswer = correctAnswer;
// this.m_singleLine = singleLine;
// this.m_regEx = regEx;
// }
//
// public void setCorrectAnswer(String m_correctAnswer) {
// this.m_correctAnswer = m_correctAnswer;
// }
//
// @Override
// @XmlElement
// public String getGivenAnswer() {
// return m_givenAnswer;
// }
//
// /**
// * @param givenAnswer
// * - The string that was written by the user
// */
// public void setGivenAnswer(String givenAnswer) {
// this.m_givenAnswer = givenAnswer;
// }
//
// /**
// * @param regEx
// * - sets the regular expression
// */
// public void setRegEx(String regEx) {
// m_regEx = regEx;
// }
//
// /**
// * @return gets the regular expression
// */
// public String getRegEx() {
// return m_regEx;
// }
//
// /**
// * @param value
// * - TRUE for a single-lined textbox, FALSE for a multi-lined
// * textfield
// */
// public void setSingleLine(boolean value) {
// m_singleLine = value;
// }
//
// /**
// * @return singleLine - If this value is TRUE a single-lined textbox will be
// * presented to the user
// */
// @XmlElement (defaultValue = "true")
// public boolean getSingleLine() {
// return m_singleLine;
// }
//
// }
| import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.text.JTextComponent;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.TextInputQuestion;
| package evaluation.evalBench.panel;
/**
* @author David
*
*/
public class TextInputQuestionPanelStrategy extends QuestionPanelStrategy {
private JTextComponent textInputField;
/**
* @param aQuestion
*/
| // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/TextInputQuestion.java
// public class TextInputQuestion extends Question {
//
// // TODO property ignore case?
//
// private String m_correctAnswer = null;
// private String m_givenAnswer = null;
// private boolean m_singleLine = true;
//
// private String m_regEx = null;
//
// public TextInputQuestion() {
// this("", "");
// }
//
// /**
// * @param aQuestionId
// * @param aQuestionText
// */
// public TextInputQuestion(String aQuestionId, String aQuestionText) {
// super(aQuestionId, aQuestionText);
// }
//
// @Override
// @XmlElement
// public String getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public TextInputQuestion(String aQuestionId, String aQuestionText,
// String correctAnswer, boolean singleLine, String regEx) {
// super(aQuestionId, aQuestionText);
// this.m_correctAnswer = correctAnswer;
// this.m_singleLine = singleLine;
// this.m_regEx = regEx;
// }
//
// public void setCorrectAnswer(String m_correctAnswer) {
// this.m_correctAnswer = m_correctAnswer;
// }
//
// @Override
// @XmlElement
// public String getGivenAnswer() {
// return m_givenAnswer;
// }
//
// /**
// * @param givenAnswer
// * - The string that was written by the user
// */
// public void setGivenAnswer(String givenAnswer) {
// this.m_givenAnswer = givenAnswer;
// }
//
// /**
// * @param regEx
// * - sets the regular expression
// */
// public void setRegEx(String regEx) {
// m_regEx = regEx;
// }
//
// /**
// * @return gets the regular expression
// */
// public String getRegEx() {
// return m_regEx;
// }
//
// /**
// * @param value
// * - TRUE for a single-lined textbox, FALSE for a multi-lined
// * textfield
// */
// public void setSingleLine(boolean value) {
// m_singleLine = value;
// }
//
// /**
// * @return singleLine - If this value is TRUE a single-lined textbox will be
// * presented to the user
// */
// @XmlElement (defaultValue = "true")
// public boolean getSingleLine() {
// return m_singleLine;
// }
//
// }
// Path: src/evaluation/evalBench/panel/TextInputQuestionPanelStrategy.java
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.text.JTextComponent;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.TextInputQuestion;
package evaluation.evalBench.panel;
/**
* @author David
*
*/
public class TextInputQuestionPanelStrategy extends QuestionPanelStrategy {
private JTextComponent textInputField;
/**
* @param aQuestion
*/
| public TextInputQuestionPanelStrategy(TextInputQuestion aQuestion) {
|
ieg-vienna/EvalBench | src/evaluation/evalBench/panel/TextInputQuestionPanelStrategy.java | // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/TextInputQuestion.java
// public class TextInputQuestion extends Question {
//
// // TODO property ignore case?
//
// private String m_correctAnswer = null;
// private String m_givenAnswer = null;
// private boolean m_singleLine = true;
//
// private String m_regEx = null;
//
// public TextInputQuestion() {
// this("", "");
// }
//
// /**
// * @param aQuestionId
// * @param aQuestionText
// */
// public TextInputQuestion(String aQuestionId, String aQuestionText) {
// super(aQuestionId, aQuestionText);
// }
//
// @Override
// @XmlElement
// public String getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public TextInputQuestion(String aQuestionId, String aQuestionText,
// String correctAnswer, boolean singleLine, String regEx) {
// super(aQuestionId, aQuestionText);
// this.m_correctAnswer = correctAnswer;
// this.m_singleLine = singleLine;
// this.m_regEx = regEx;
// }
//
// public void setCorrectAnswer(String m_correctAnswer) {
// this.m_correctAnswer = m_correctAnswer;
// }
//
// @Override
// @XmlElement
// public String getGivenAnswer() {
// return m_givenAnswer;
// }
//
// /**
// * @param givenAnswer
// * - The string that was written by the user
// */
// public void setGivenAnswer(String givenAnswer) {
// this.m_givenAnswer = givenAnswer;
// }
//
// /**
// * @param regEx
// * - sets the regular expression
// */
// public void setRegEx(String regEx) {
// m_regEx = regEx;
// }
//
// /**
// * @return gets the regular expression
// */
// public String getRegEx() {
// return m_regEx;
// }
//
// /**
// * @param value
// * - TRUE for a single-lined textbox, FALSE for a multi-lined
// * textfield
// */
// public void setSingleLine(boolean value) {
// m_singleLine = value;
// }
//
// /**
// * @return singleLine - If this value is TRUE a single-lined textbox will be
// * presented to the user
// */
// @XmlElement (defaultValue = "true")
// public boolean getSingleLine() {
// return m_singleLine;
// }
//
// }
| import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.text.JTextComponent;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.TextInputQuestion;
| package evaluation.evalBench.panel;
/**
* @author David
*
*/
public class TextInputQuestionPanelStrategy extends QuestionPanelStrategy {
private JTextComponent textInputField;
/**
* @param aQuestion
*/
public TextInputQuestionPanelStrategy(TextInputQuestion aQuestion) {
super(aQuestion);
}
@Override
public boolean checkForCorrectInput() {
TextInputQuestion textQuestion = (TextInputQuestion) super.getQuestion();
if (!textInputField.getText().equals("")) {
if (textQuestion.getRegEx() != null
&& textQuestion.getRegEx().length() > 0
&& !textInputField.getText().matches(
textQuestion.getRegEx())) {
| // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/TextInputQuestion.java
// public class TextInputQuestion extends Question {
//
// // TODO property ignore case?
//
// private String m_correctAnswer = null;
// private String m_givenAnswer = null;
// private boolean m_singleLine = true;
//
// private String m_regEx = null;
//
// public TextInputQuestion() {
// this("", "");
// }
//
// /**
// * @param aQuestionId
// * @param aQuestionText
// */
// public TextInputQuestion(String aQuestionId, String aQuestionText) {
// super(aQuestionId, aQuestionText);
// }
//
// @Override
// @XmlElement
// public String getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public TextInputQuestion(String aQuestionId, String aQuestionText,
// String correctAnswer, boolean singleLine, String regEx) {
// super(aQuestionId, aQuestionText);
// this.m_correctAnswer = correctAnswer;
// this.m_singleLine = singleLine;
// this.m_regEx = regEx;
// }
//
// public void setCorrectAnswer(String m_correctAnswer) {
// this.m_correctAnswer = m_correctAnswer;
// }
//
// @Override
// @XmlElement
// public String getGivenAnswer() {
// return m_givenAnswer;
// }
//
// /**
// * @param givenAnswer
// * - The string that was written by the user
// */
// public void setGivenAnswer(String givenAnswer) {
// this.m_givenAnswer = givenAnswer;
// }
//
// /**
// * @param regEx
// * - sets the regular expression
// */
// public void setRegEx(String regEx) {
// m_regEx = regEx;
// }
//
// /**
// * @return gets the regular expression
// */
// public String getRegEx() {
// return m_regEx;
// }
//
// /**
// * @param value
// * - TRUE for a single-lined textbox, FALSE for a multi-lined
// * textfield
// */
// public void setSingleLine(boolean value) {
// m_singleLine = value;
// }
//
// /**
// * @return singleLine - If this value is TRUE a single-lined textbox will be
// * presented to the user
// */
// @XmlElement (defaultValue = "true")
// public boolean getSingleLine() {
// return m_singleLine;
// }
//
// }
// Path: src/evaluation/evalBench/panel/TextInputQuestionPanelStrategy.java
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.text.JTextComponent;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.TextInputQuestion;
package evaluation.evalBench.panel;
/**
* @author David
*
*/
public class TextInputQuestionPanelStrategy extends QuestionPanelStrategy {
private JTextComponent textInputField;
/**
* @param aQuestion
*/
public TextInputQuestionPanelStrategy(TextInputQuestion aQuestion) {
super(aQuestion);
}
@Override
public boolean checkForCorrectInput() {
TextInputQuestion textQuestion = (TextInputQuestion) super.getQuestion();
if (!textInputField.getText().equals("")) {
if (textQuestion.getRegEx() != null
&& textQuestion.getRegEx().length() > 0
&& !textInputField.getText().matches(
textQuestion.getRegEx())) {
| setErrorMessage(EvaluationResources.getString("textinputquestion.errorPattern"));
|
ieg-vienna/EvalBench | src/evaluation/evalBench/task/EmptyQuestion.java | // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
| import evaluation.evalBench.EvaluationResources; | package evaluation.evalBench.task;
/**
* An empty subclass of {@link Task}.
*/
public class EmptyQuestion extends Question{
public EmptyQuestion(){ | // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
// Path: src/evaluation/evalBench/task/EmptyQuestion.java
import evaluation.evalBench.EvaluationResources;
package evaluation.evalBench.task;
/**
* An empty subclass of {@link Task}.
*/
public class EmptyQuestion extends Question{
public EmptyQuestion(){ | super("emptyTask", EvaluationResources.getString("emptytask.description")); |
ieg-vienna/EvalBench | src/evaluation/evalBench/panel/ItemSelectionQuestionPanelStrategy.java | // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/ItemSelectionQuestion.java
// public class ItemSelectionQuestion extends Question{
// private static final String SEPARATOR = ", ";
//
// protected SortedSet<String> m_answeredSelected_Item_ID = null;
// protected SortedSet<String> m_correctSelected_Item_ID = null;
//
// public ItemSelectionQuestion(){
// super();
// }
//
// public ItemSelectionQuestion(String aQuestionId, String aQuestionText){
// super(aQuestionId, aQuestionText);
// }
//
// public ItemSelectionQuestion(String aQuestionId, String aQuestionText, SortedSet<String> correctItemIDs){
// super(aQuestionId, aQuestionText);
// // m_answeredSelected_Item_ID = new TreeSet<String>();
// m_correctSelected_Item_ID = correctItemIDs;
// }
//
// @Override
// @XmlElementWrapper(name = "givenAnswers")
// @XmlElement(name = "givenAnswer")
// public SortedSet<String> getGivenAnswer() {
// return m_answeredSelected_Item_ID;
// }
//
// public void setGivenAnswer(SortedSet<String> answeredSelectedItemID) {
// m_answeredSelected_Item_ID = answeredSelectedItemID;
// }
//
// @XmlElementWrapper(name = "correctAnswers")
// @XmlElement(name = "correctAnswer")
// public SortedSet<String> getCorrectAnswer() {
// return m_correctSelected_Item_ID;
// }
//
// public void setCorrectAnswer(SortedSet<String> mCorrectSelectedItemID) {
// m_correctSelected_Item_ID = mCorrectSelectedItemID;
// }
//
// @Override
// public String exportCorrectAnswer() {
// return StringUtils.join(m_correctSelected_Item_ID, SEPARATOR);
// }
//
// @Override
// public String exportGivenAnswer() {
// return StringUtils.join(m_answeredSelected_Item_ID, SEPARATOR);
// }
//
// @Override
// public Question clone() {
// // TODO convert shallow copy to a deep copy
// return super.clone();
// }
// }
| import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import org.apache.commons.lang3.StringUtils;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.ItemSelectionQuestion;
| package evaluation.evalBench.panel;
public class ItemSelectionQuestionPanelStrategy extends QuestionPanelStrategy{
JTextPane itemPane;
//JToggleButton jStartSelectionButton;
SortedSet<String> selectedItems;
| // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/ItemSelectionQuestion.java
// public class ItemSelectionQuestion extends Question{
// private static final String SEPARATOR = ", ";
//
// protected SortedSet<String> m_answeredSelected_Item_ID = null;
// protected SortedSet<String> m_correctSelected_Item_ID = null;
//
// public ItemSelectionQuestion(){
// super();
// }
//
// public ItemSelectionQuestion(String aQuestionId, String aQuestionText){
// super(aQuestionId, aQuestionText);
// }
//
// public ItemSelectionQuestion(String aQuestionId, String aQuestionText, SortedSet<String> correctItemIDs){
// super(aQuestionId, aQuestionText);
// // m_answeredSelected_Item_ID = new TreeSet<String>();
// m_correctSelected_Item_ID = correctItemIDs;
// }
//
// @Override
// @XmlElementWrapper(name = "givenAnswers")
// @XmlElement(name = "givenAnswer")
// public SortedSet<String> getGivenAnswer() {
// return m_answeredSelected_Item_ID;
// }
//
// public void setGivenAnswer(SortedSet<String> answeredSelectedItemID) {
// m_answeredSelected_Item_ID = answeredSelectedItemID;
// }
//
// @XmlElementWrapper(name = "correctAnswers")
// @XmlElement(name = "correctAnswer")
// public SortedSet<String> getCorrectAnswer() {
// return m_correctSelected_Item_ID;
// }
//
// public void setCorrectAnswer(SortedSet<String> mCorrectSelectedItemID) {
// m_correctSelected_Item_ID = mCorrectSelectedItemID;
// }
//
// @Override
// public String exportCorrectAnswer() {
// return StringUtils.join(m_correctSelected_Item_ID, SEPARATOR);
// }
//
// @Override
// public String exportGivenAnswer() {
// return StringUtils.join(m_answeredSelected_Item_ID, SEPARATOR);
// }
//
// @Override
// public Question clone() {
// // TODO convert shallow copy to a deep copy
// return super.clone();
// }
// }
// Path: src/evaluation/evalBench/panel/ItemSelectionQuestionPanelStrategy.java
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import org.apache.commons.lang3.StringUtils;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.ItemSelectionQuestion;
package evaluation.evalBench.panel;
public class ItemSelectionQuestionPanelStrategy extends QuestionPanelStrategy{
JTextPane itemPane;
//JToggleButton jStartSelectionButton;
SortedSet<String> selectedItems;
| public ItemSelectionQuestionPanelStrategy(ItemSelectionQuestion aTask) {
|
ieg-vienna/EvalBench | src/evaluation/evalBench/panel/ItemSelectionQuestionPanelStrategy.java | // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/ItemSelectionQuestion.java
// public class ItemSelectionQuestion extends Question{
// private static final String SEPARATOR = ", ";
//
// protected SortedSet<String> m_answeredSelected_Item_ID = null;
// protected SortedSet<String> m_correctSelected_Item_ID = null;
//
// public ItemSelectionQuestion(){
// super();
// }
//
// public ItemSelectionQuestion(String aQuestionId, String aQuestionText){
// super(aQuestionId, aQuestionText);
// }
//
// public ItemSelectionQuestion(String aQuestionId, String aQuestionText, SortedSet<String> correctItemIDs){
// super(aQuestionId, aQuestionText);
// // m_answeredSelected_Item_ID = new TreeSet<String>();
// m_correctSelected_Item_ID = correctItemIDs;
// }
//
// @Override
// @XmlElementWrapper(name = "givenAnswers")
// @XmlElement(name = "givenAnswer")
// public SortedSet<String> getGivenAnswer() {
// return m_answeredSelected_Item_ID;
// }
//
// public void setGivenAnswer(SortedSet<String> answeredSelectedItemID) {
// m_answeredSelected_Item_ID = answeredSelectedItemID;
// }
//
// @XmlElementWrapper(name = "correctAnswers")
// @XmlElement(name = "correctAnswer")
// public SortedSet<String> getCorrectAnswer() {
// return m_correctSelected_Item_ID;
// }
//
// public void setCorrectAnswer(SortedSet<String> mCorrectSelectedItemID) {
// m_correctSelected_Item_ID = mCorrectSelectedItemID;
// }
//
// @Override
// public String exportCorrectAnswer() {
// return StringUtils.join(m_correctSelected_Item_ID, SEPARATOR);
// }
//
// @Override
// public String exportGivenAnswer() {
// return StringUtils.join(m_answeredSelected_Item_ID, SEPARATOR);
// }
//
// @Override
// public Question clone() {
// // TODO convert shallow copy to a deep copy
// return super.clone();
// }
// }
| import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import org.apache.commons.lang3.StringUtils;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.ItemSelectionQuestion;
| package evaluation.evalBench.panel;
public class ItemSelectionQuestionPanelStrategy extends QuestionPanelStrategy{
JTextPane itemPane;
//JToggleButton jStartSelectionButton;
SortedSet<String> selectedItems;
public ItemSelectionQuestionPanelStrategy(ItemSelectionQuestion aTask) {
super(aTask);
selectedItems = new TreeSet<String>();
}
@Override
public boolean checkForCorrectInput() {
this.setErrorMessage((""));
if (selectedItems != null && selectedItems.size()>0){
//jStartSelectionButton.setSelected(false);
((ItemSelectionQuestion)super.getQuestion()).setGivenAnswer(selectedItems);
return true;
}
// otherwise show error msg
| // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/ItemSelectionQuestion.java
// public class ItemSelectionQuestion extends Question{
// private static final String SEPARATOR = ", ";
//
// protected SortedSet<String> m_answeredSelected_Item_ID = null;
// protected SortedSet<String> m_correctSelected_Item_ID = null;
//
// public ItemSelectionQuestion(){
// super();
// }
//
// public ItemSelectionQuestion(String aQuestionId, String aQuestionText){
// super(aQuestionId, aQuestionText);
// }
//
// public ItemSelectionQuestion(String aQuestionId, String aQuestionText, SortedSet<String> correctItemIDs){
// super(aQuestionId, aQuestionText);
// // m_answeredSelected_Item_ID = new TreeSet<String>();
// m_correctSelected_Item_ID = correctItemIDs;
// }
//
// @Override
// @XmlElementWrapper(name = "givenAnswers")
// @XmlElement(name = "givenAnswer")
// public SortedSet<String> getGivenAnswer() {
// return m_answeredSelected_Item_ID;
// }
//
// public void setGivenAnswer(SortedSet<String> answeredSelectedItemID) {
// m_answeredSelected_Item_ID = answeredSelectedItemID;
// }
//
// @XmlElementWrapper(name = "correctAnswers")
// @XmlElement(name = "correctAnswer")
// public SortedSet<String> getCorrectAnswer() {
// return m_correctSelected_Item_ID;
// }
//
// public void setCorrectAnswer(SortedSet<String> mCorrectSelectedItemID) {
// m_correctSelected_Item_ID = mCorrectSelectedItemID;
// }
//
// @Override
// public String exportCorrectAnswer() {
// return StringUtils.join(m_correctSelected_Item_ID, SEPARATOR);
// }
//
// @Override
// public String exportGivenAnswer() {
// return StringUtils.join(m_answeredSelected_Item_ID, SEPARATOR);
// }
//
// @Override
// public Question clone() {
// // TODO convert shallow copy to a deep copy
// return super.clone();
// }
// }
// Path: src/evaluation/evalBench/panel/ItemSelectionQuestionPanelStrategy.java
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import org.apache.commons.lang3.StringUtils;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.ItemSelectionQuestion;
package evaluation.evalBench.panel;
public class ItemSelectionQuestionPanelStrategy extends QuestionPanelStrategy{
JTextPane itemPane;
//JToggleButton jStartSelectionButton;
SortedSet<String> selectedItems;
public ItemSelectionQuestionPanelStrategy(ItemSelectionQuestion aTask) {
super(aTask);
selectedItems = new TreeSet<String>();
}
@Override
public boolean checkForCorrectInput() {
this.setErrorMessage((""));
if (selectedItems != null && selectedItems.size()>0){
//jStartSelectionButton.setSelected(false);
((ItemSelectionQuestion)super.getQuestion()).setGivenAnswer(selectedItems);
return true;
}
// otherwise show error msg
| this.setErrorMessage(EvaluationResources.getString("itemsel.taskpanel.error"));
|
ieg-vienna/EvalBench | src/evaluation/evalBench/panel/YesNoQuestionPanelStrategy.java | // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/YesNoQuestion.java
// public class YesNoQuestion extends Question {
//
// private Boolean m_correctAnswer = null;
// private Boolean m_givenAnswer = null;
//
// public YesNoQuestion() {
// this("", "");
// }
//
// /**
// * @param aQuestionId
// * @param aQuestionText
// */
// public YesNoQuestion(String aQuestionId, String aQuestionText) {
// super(aQuestionId, aQuestionText);
// }
//
// public YesNoQuestion(String aQuestionId, String aQuestionText,
// Boolean correctAnswer) {
// super(aQuestionId, aQuestionText);
// this.m_correctAnswer = correctAnswer;
// }
//
// @Override
// @XmlElement
// public Boolean getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public void setCorrectAnswer(Boolean correctAnswer) {
// this.m_correctAnswer = correctAnswer;
// }
//
// @Override
// @XmlElement
// public Boolean getGivenAnswer() {
// return m_givenAnswer;
// }
//
// /**
// * @param givenAnswer
// * - The answer selected by the user
// */
// public void setGivenAnswer(Boolean givenAnswer) {
// this.m_givenAnswer = givenAnswer;
// }
// }
| import java.awt.FlowLayout;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.YesNoQuestion;
| package evaluation.evalBench.panel;
/**
* @author David
*
*/
public class YesNoQuestionPanelStrategy extends QuestionPanelStrategy {
private ButtonGroup radioButtonGroup;
private JRadioButton yesButton, noButton;
/**
* @param aTask
*/
| // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/YesNoQuestion.java
// public class YesNoQuestion extends Question {
//
// private Boolean m_correctAnswer = null;
// private Boolean m_givenAnswer = null;
//
// public YesNoQuestion() {
// this("", "");
// }
//
// /**
// * @param aQuestionId
// * @param aQuestionText
// */
// public YesNoQuestion(String aQuestionId, String aQuestionText) {
// super(aQuestionId, aQuestionText);
// }
//
// public YesNoQuestion(String aQuestionId, String aQuestionText,
// Boolean correctAnswer) {
// super(aQuestionId, aQuestionText);
// this.m_correctAnswer = correctAnswer;
// }
//
// @Override
// @XmlElement
// public Boolean getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public void setCorrectAnswer(Boolean correctAnswer) {
// this.m_correctAnswer = correctAnswer;
// }
//
// @Override
// @XmlElement
// public Boolean getGivenAnswer() {
// return m_givenAnswer;
// }
//
// /**
// * @param givenAnswer
// * - The answer selected by the user
// */
// public void setGivenAnswer(Boolean givenAnswer) {
// this.m_givenAnswer = givenAnswer;
// }
// }
// Path: src/evaluation/evalBench/panel/YesNoQuestionPanelStrategy.java
import java.awt.FlowLayout;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.YesNoQuestion;
package evaluation.evalBench.panel;
/**
* @author David
*
*/
public class YesNoQuestionPanelStrategy extends QuestionPanelStrategy {
private ButtonGroup radioButtonGroup;
private JRadioButton yesButton, noButton;
/**
* @param aTask
*/
| public YesNoQuestionPanelStrategy(YesNoQuestion aTask) {
|
ieg-vienna/EvalBench | src/evaluation/evalBench/panel/YesNoQuestionPanelStrategy.java | // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/YesNoQuestion.java
// public class YesNoQuestion extends Question {
//
// private Boolean m_correctAnswer = null;
// private Boolean m_givenAnswer = null;
//
// public YesNoQuestion() {
// this("", "");
// }
//
// /**
// * @param aQuestionId
// * @param aQuestionText
// */
// public YesNoQuestion(String aQuestionId, String aQuestionText) {
// super(aQuestionId, aQuestionText);
// }
//
// public YesNoQuestion(String aQuestionId, String aQuestionText,
// Boolean correctAnswer) {
// super(aQuestionId, aQuestionText);
// this.m_correctAnswer = correctAnswer;
// }
//
// @Override
// @XmlElement
// public Boolean getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public void setCorrectAnswer(Boolean correctAnswer) {
// this.m_correctAnswer = correctAnswer;
// }
//
// @Override
// @XmlElement
// public Boolean getGivenAnswer() {
// return m_givenAnswer;
// }
//
// /**
// * @param givenAnswer
// * - The answer selected by the user
// */
// public void setGivenAnswer(Boolean givenAnswer) {
// this.m_givenAnswer = givenAnswer;
// }
// }
| import java.awt.FlowLayout;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.YesNoQuestion;
| package evaluation.evalBench.panel;
/**
* @author David
*
*/
public class YesNoQuestionPanelStrategy extends QuestionPanelStrategy {
private ButtonGroup radioButtonGroup;
private JRadioButton yesButton, noButton;
/**
* @param aTask
*/
public YesNoQuestionPanelStrategy(YesNoQuestion aTask) {
super(aTask);
}
@Override
public boolean checkForCorrectInput() {
if (yesButton.isSelected()) {
((YesNoQuestion) super.getQuestion()).setGivenAnswer(true);
setErrorMessage("");
return true;
} else if (noButton.isSelected()) {
((YesNoQuestion) super.getQuestion()).setGivenAnswer(false);
setErrorMessage("");
return true;
} else {
| // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/YesNoQuestion.java
// public class YesNoQuestion extends Question {
//
// private Boolean m_correctAnswer = null;
// private Boolean m_givenAnswer = null;
//
// public YesNoQuestion() {
// this("", "");
// }
//
// /**
// * @param aQuestionId
// * @param aQuestionText
// */
// public YesNoQuestion(String aQuestionId, String aQuestionText) {
// super(aQuestionId, aQuestionText);
// }
//
// public YesNoQuestion(String aQuestionId, String aQuestionText,
// Boolean correctAnswer) {
// super(aQuestionId, aQuestionText);
// this.m_correctAnswer = correctAnswer;
// }
//
// @Override
// @XmlElement
// public Boolean getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public void setCorrectAnswer(Boolean correctAnswer) {
// this.m_correctAnswer = correctAnswer;
// }
//
// @Override
// @XmlElement
// public Boolean getGivenAnswer() {
// return m_givenAnswer;
// }
//
// /**
// * @param givenAnswer
// * - The answer selected by the user
// */
// public void setGivenAnswer(Boolean givenAnswer) {
// this.m_givenAnswer = givenAnswer;
// }
// }
// Path: src/evaluation/evalBench/panel/YesNoQuestionPanelStrategy.java
import java.awt.FlowLayout;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.YesNoQuestion;
package evaluation.evalBench.panel;
/**
* @author David
*
*/
public class YesNoQuestionPanelStrategy extends QuestionPanelStrategy {
private ButtonGroup radioButtonGroup;
private JRadioButton yesButton, noButton;
/**
* @param aTask
*/
public YesNoQuestionPanelStrategy(YesNoQuestion aTask) {
super(aTask);
}
@Override
public boolean checkForCorrectInput() {
if (yesButton.isSelected()) {
((YesNoQuestion) super.getQuestion()).setGivenAnswer(true);
setErrorMessage("");
return true;
} else if (noButton.isSelected()) {
((YesNoQuestion) super.getQuestion()).setGivenAnswer(false);
setErrorMessage("");
return true;
} else {
| setErrorMessage(EvaluationResources.getString("yesnoquestion.errorSelect"));
|
ieg-vienna/EvalBench | src/evaluation/evalBench/panel/LikertskalaQuestionPanelStrategy.java | // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/LikertskalaQuestion.java
// public class LikertskalaQuestion extends Question {
//
// private Integer m_givenAnswer = null;
//
// private Integer m_correctAnswer = null;
//
// /**
// * label for the left-most option on the likert scale. If <tt>null</tt> a
// * generic text should be used.
// */
// private String m_leftLabel = null;
//
// /**
// * label for the right-most option on the likert scale. If <tt>null</tt> a
// * generic text should be used.
// */
// private String m_rightLabel = null;
//
// private int m_countOptions;
//
// public LikertskalaQuestion() {
// this("", "", "low", "high", 4);
// }
//
// /**
// * @param aQuestionId
// * @param aQuestionText
// * @param leftLabel
// * @param aRightLabel
// * @param countOptions
// */
// public LikertskalaQuestion(String aQuestionId, String aQuestionText,
// String leftLabel, String rightLabel, int countOptions) {
// super(aQuestionId, aQuestionText);
//
// m_givenAnswer = null;
// m_leftLabel = leftLabel;
// m_rightLabel = rightLabel;
// m_countOptions = countOptions;
// }
//
// @Override
// @XmlElement
// public Integer getGivenAnswer() {
// return m_givenAnswer;
// }
//
// public void setGivenAnswer(Integer givenAnswer) {
// this.m_givenAnswer = givenAnswer;
// }
//
//
// @Override
// @XmlElement
// public Integer getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public void setCorrectAnswer(Integer correctAnswer) {
// this.m_correctAnswer = correctAnswer;
// }
//
// /**
// * @return countOptions - Number of options (JRadioButtons) that are
// * available to choose from
// */
// @XmlElement (name = "count-options", required = true)
// public int getCountOptions() {
// return m_countOptions;
// }
//
// public void setCountOptions(int countOptions) {
// this.m_countOptions = countOptions;
// }
//
// /**
// * @return a String that is printed at the left of the scale
// */
// @XmlElement (name = "left-label")
// public String getLeftLabel() {
// return m_leftLabel;
// }
//
// public void setLeftLabel(String leftLabel) {
// this.m_leftLabel = leftLabel;
// }
//
// /**
// * @return a String that is printed at the right of the scale
// */
// @XmlElement (name = "right-label")
// public String getRightLabel() {
// return m_rightLabel;
// }
//
// public void setRightLabel(String rightLabel) {
// this.m_rightLabel = rightLabel;
// }
// }
| import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.LikertskalaQuestion;
| package evaluation.evalBench.panel;
/**
* @author David, Alexander Rind
*
*/
public class LikertskalaQuestionPanelStrategy extends QuestionPanelStrategy {
private ButtonGroup radioGroup;
private ArrayList<JRadioButton> radioList;
/**
* @param aQuestion
*/
| // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/LikertskalaQuestion.java
// public class LikertskalaQuestion extends Question {
//
// private Integer m_givenAnswer = null;
//
// private Integer m_correctAnswer = null;
//
// /**
// * label for the left-most option on the likert scale. If <tt>null</tt> a
// * generic text should be used.
// */
// private String m_leftLabel = null;
//
// /**
// * label for the right-most option on the likert scale. If <tt>null</tt> a
// * generic text should be used.
// */
// private String m_rightLabel = null;
//
// private int m_countOptions;
//
// public LikertskalaQuestion() {
// this("", "", "low", "high", 4);
// }
//
// /**
// * @param aQuestionId
// * @param aQuestionText
// * @param leftLabel
// * @param aRightLabel
// * @param countOptions
// */
// public LikertskalaQuestion(String aQuestionId, String aQuestionText,
// String leftLabel, String rightLabel, int countOptions) {
// super(aQuestionId, aQuestionText);
//
// m_givenAnswer = null;
// m_leftLabel = leftLabel;
// m_rightLabel = rightLabel;
// m_countOptions = countOptions;
// }
//
// @Override
// @XmlElement
// public Integer getGivenAnswer() {
// return m_givenAnswer;
// }
//
// public void setGivenAnswer(Integer givenAnswer) {
// this.m_givenAnswer = givenAnswer;
// }
//
//
// @Override
// @XmlElement
// public Integer getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public void setCorrectAnswer(Integer correctAnswer) {
// this.m_correctAnswer = correctAnswer;
// }
//
// /**
// * @return countOptions - Number of options (JRadioButtons) that are
// * available to choose from
// */
// @XmlElement (name = "count-options", required = true)
// public int getCountOptions() {
// return m_countOptions;
// }
//
// public void setCountOptions(int countOptions) {
// this.m_countOptions = countOptions;
// }
//
// /**
// * @return a String that is printed at the left of the scale
// */
// @XmlElement (name = "left-label")
// public String getLeftLabel() {
// return m_leftLabel;
// }
//
// public void setLeftLabel(String leftLabel) {
// this.m_leftLabel = leftLabel;
// }
//
// /**
// * @return a String that is printed at the right of the scale
// */
// @XmlElement (name = "right-label")
// public String getRightLabel() {
// return m_rightLabel;
// }
//
// public void setRightLabel(String rightLabel) {
// this.m_rightLabel = rightLabel;
// }
// }
// Path: src/evaluation/evalBench/panel/LikertskalaQuestionPanelStrategy.java
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.LikertskalaQuestion;
package evaluation.evalBench.panel;
/**
* @author David, Alexander Rind
*
*/
public class LikertskalaQuestionPanelStrategy extends QuestionPanelStrategy {
private ButtonGroup radioGroup;
private ArrayList<JRadioButton> radioList;
/**
* @param aQuestion
*/
| public LikertskalaQuestionPanelStrategy(LikertskalaQuestion aQuestion) {
|
ieg-vienna/EvalBench | src/evaluation/evalBench/panel/LikertskalaQuestionPanelStrategy.java | // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/LikertskalaQuestion.java
// public class LikertskalaQuestion extends Question {
//
// private Integer m_givenAnswer = null;
//
// private Integer m_correctAnswer = null;
//
// /**
// * label for the left-most option on the likert scale. If <tt>null</tt> a
// * generic text should be used.
// */
// private String m_leftLabel = null;
//
// /**
// * label for the right-most option on the likert scale. If <tt>null</tt> a
// * generic text should be used.
// */
// private String m_rightLabel = null;
//
// private int m_countOptions;
//
// public LikertskalaQuestion() {
// this("", "", "low", "high", 4);
// }
//
// /**
// * @param aQuestionId
// * @param aQuestionText
// * @param leftLabel
// * @param aRightLabel
// * @param countOptions
// */
// public LikertskalaQuestion(String aQuestionId, String aQuestionText,
// String leftLabel, String rightLabel, int countOptions) {
// super(aQuestionId, aQuestionText);
//
// m_givenAnswer = null;
// m_leftLabel = leftLabel;
// m_rightLabel = rightLabel;
// m_countOptions = countOptions;
// }
//
// @Override
// @XmlElement
// public Integer getGivenAnswer() {
// return m_givenAnswer;
// }
//
// public void setGivenAnswer(Integer givenAnswer) {
// this.m_givenAnswer = givenAnswer;
// }
//
//
// @Override
// @XmlElement
// public Integer getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public void setCorrectAnswer(Integer correctAnswer) {
// this.m_correctAnswer = correctAnswer;
// }
//
// /**
// * @return countOptions - Number of options (JRadioButtons) that are
// * available to choose from
// */
// @XmlElement (name = "count-options", required = true)
// public int getCountOptions() {
// return m_countOptions;
// }
//
// public void setCountOptions(int countOptions) {
// this.m_countOptions = countOptions;
// }
//
// /**
// * @return a String that is printed at the left of the scale
// */
// @XmlElement (name = "left-label")
// public String getLeftLabel() {
// return m_leftLabel;
// }
//
// public void setLeftLabel(String leftLabel) {
// this.m_leftLabel = leftLabel;
// }
//
// /**
// * @return a String that is printed at the right of the scale
// */
// @XmlElement (name = "right-label")
// public String getRightLabel() {
// return m_rightLabel;
// }
//
// public void setRightLabel(String rightLabel) {
// this.m_rightLabel = rightLabel;
// }
// }
| import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.LikertskalaQuestion;
| package evaluation.evalBench.panel;
/**
* @author David, Alexander Rind
*
*/
public class LikertskalaQuestionPanelStrategy extends QuestionPanelStrategy {
private ButtonGroup radioGroup;
private ArrayList<JRadioButton> radioList;
/**
* @param aQuestion
*/
public LikertskalaQuestionPanelStrategy(LikertskalaQuestion aQuestion) {
super(aQuestion);
}
@Override
public boolean checkForCorrectInput() {
JRadioButton selectedButton = null;
for (JRadioButton button : radioList) {
if (button.isSelected())
selectedButton = button;
}
if (selectedButton != null) {
try {
((LikertskalaQuestion) super.getQuestion()).setGivenAnswer(Integer
.parseInt(selectedButton.getName()));
setErrorMessage("");
return true;
} catch (Exception e) {
| // Path: src/evaluation/evalBench/EvaluationResources.java
// public class EvaluationResources {
//
// private static final ResourceBundle resourceBundle = ResourceBundle
// .getBundle(EvaluationResources.class.getPackage().getName()
// + ".evaluationGui");
//
// /**
// * Prevent instantiation
// */
// private EvaluationResources() {
// }
//
// /**
// * Retrieves a string from the resource bundle
// */
// public static String getString(String key) {
// return resourceBundle.getString(key);
// }
// }
//
// Path: src/evaluation/evalBench/task/LikertskalaQuestion.java
// public class LikertskalaQuestion extends Question {
//
// private Integer m_givenAnswer = null;
//
// private Integer m_correctAnswer = null;
//
// /**
// * label for the left-most option on the likert scale. If <tt>null</tt> a
// * generic text should be used.
// */
// private String m_leftLabel = null;
//
// /**
// * label for the right-most option on the likert scale. If <tt>null</tt> a
// * generic text should be used.
// */
// private String m_rightLabel = null;
//
// private int m_countOptions;
//
// public LikertskalaQuestion() {
// this("", "", "low", "high", 4);
// }
//
// /**
// * @param aQuestionId
// * @param aQuestionText
// * @param leftLabel
// * @param aRightLabel
// * @param countOptions
// */
// public LikertskalaQuestion(String aQuestionId, String aQuestionText,
// String leftLabel, String rightLabel, int countOptions) {
// super(aQuestionId, aQuestionText);
//
// m_givenAnswer = null;
// m_leftLabel = leftLabel;
// m_rightLabel = rightLabel;
// m_countOptions = countOptions;
// }
//
// @Override
// @XmlElement
// public Integer getGivenAnswer() {
// return m_givenAnswer;
// }
//
// public void setGivenAnswer(Integer givenAnswer) {
// this.m_givenAnswer = givenAnswer;
// }
//
//
// @Override
// @XmlElement
// public Integer getCorrectAnswer() {
// return m_correctAnswer;
// }
//
// public void setCorrectAnswer(Integer correctAnswer) {
// this.m_correctAnswer = correctAnswer;
// }
//
// /**
// * @return countOptions - Number of options (JRadioButtons) that are
// * available to choose from
// */
// @XmlElement (name = "count-options", required = true)
// public int getCountOptions() {
// return m_countOptions;
// }
//
// public void setCountOptions(int countOptions) {
// this.m_countOptions = countOptions;
// }
//
// /**
// * @return a String that is printed at the left of the scale
// */
// @XmlElement (name = "left-label")
// public String getLeftLabel() {
// return m_leftLabel;
// }
//
// public void setLeftLabel(String leftLabel) {
// this.m_leftLabel = leftLabel;
// }
//
// /**
// * @return a String that is printed at the right of the scale
// */
// @XmlElement (name = "right-label")
// public String getRightLabel() {
// return m_rightLabel;
// }
//
// public void setRightLabel(String rightLabel) {
// this.m_rightLabel = rightLabel;
// }
// }
// Path: src/evaluation/evalBench/panel/LikertskalaQuestionPanelStrategy.java
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.LikertskalaQuestion;
package evaluation.evalBench.panel;
/**
* @author David, Alexander Rind
*
*/
public class LikertskalaQuestionPanelStrategy extends QuestionPanelStrategy {
private ButtonGroup radioGroup;
private ArrayList<JRadioButton> radioList;
/**
* @param aQuestion
*/
public LikertskalaQuestionPanelStrategy(LikertskalaQuestion aQuestion) {
super(aQuestion);
}
@Override
public boolean checkForCorrectInput() {
JRadioButton selectedButton = null;
for (JRadioButton button : radioList) {
if (button.isSelected())
selectedButton = button;
}
if (selectedButton != null) {
try {
((LikertskalaQuestion) super.getQuestion()).setGivenAnswer(Integer
.parseInt(selectedButton.getName()));
setErrorMessage("");
return true;
} catch (Exception e) {
| setErrorMessage(EvaluationResources.getString("likertskalaquestion.errorInt"));
|
samwho/jarvis | client_libs/java/src/jarvis/Jarvis.java | // Path: client_libs/java/src/jarvis/exceptions/JarvisException.java
// public class JarvisException extends Exception {
// public JarvisException(String message) {
// super(message);
// }
//
// public JarvisException(Throwable t) {
// super(t);
// }
//
// public JarvisException(String message, Throwable t) {
// super(message, t);
// }
// }
| import java.net.Socket;
import java.net.UnknownHostException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import jarvis.exceptions.JarvisException; | package jarvis;
public class Jarvis {
private Socket conn;
private PrintWriter out;
private BufferedReader server;
private char[] buffer;
private int bufsize = 4096;
private int chunksize = 512;
/**
* Initialise Jarvis with a host name and a port number.
*
* If the port is not supplied it will default to Jarvis's default port
* number of 1337.
*
* If there is no Jarvis server running, a JarvisException will be thrown.
*/ | // Path: client_libs/java/src/jarvis/exceptions/JarvisException.java
// public class JarvisException extends Exception {
// public JarvisException(String message) {
// super(message);
// }
//
// public JarvisException(Throwable t) {
// super(t);
// }
//
// public JarvisException(String message, Throwable t) {
// super(message, t);
// }
// }
// Path: client_libs/java/src/jarvis/Jarvis.java
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import jarvis.exceptions.JarvisException;
package jarvis;
public class Jarvis {
private Socket conn;
private PrintWriter out;
private BufferedReader server;
private char[] buffer;
private int bufsize = 4096;
private int chunksize = 512;
/**
* Initialise Jarvis with a host name and a port number.
*
* If the port is not supplied it will default to Jarvis's default port
* number of 1337.
*
* If there is no Jarvis server running, a JarvisException will be thrown.
*/ | public Jarvis(String host, int port) throws JarvisException { |
JimSeker/service | eclipse/ServiceDemoIPC/src/edu/cs4730/servicedemoipc/MainFragment.java | // Path: ServiceDemoIPC/app/src/main/java/edu/cs4730/servicedemoipc/RandNumService.java
// public class LocalBinder extends Binder {
// RandNumService getService() {
// // Return this instance of LocalService so clients can call public methods
// return RandNumService.this;
// }
// }
| import edu.cs4730.servicedemoipc.RandNumService.LocalBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Toast; | public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_main, container, false);
//setup the button, so it will call into the service and get a random number.
myView.findViewById(R.id.btn_gn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (mBound) {
// Call a method from the RandNumService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
//but getting a random number is really quick, so I'm doing it here instead.
int num = mService.getRandomNumber();
Toast.makeText(getActivity(), "number: " + num, Toast.LENGTH_SHORT).show();
}
}
});
return myView;
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance | // Path: ServiceDemoIPC/app/src/main/java/edu/cs4730/servicedemoipc/RandNumService.java
// public class LocalBinder extends Binder {
// RandNumService getService() {
// // Return this instance of LocalService so clients can call public methods
// return RandNumService.this;
// }
// }
// Path: eclipse/ServiceDemoIPC/src/edu/cs4730/servicedemoipc/MainFragment.java
import edu.cs4730.servicedemoipc.RandNumService.LocalBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Toast;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_main, container, false);
//setup the button, so it will call into the service and get a random number.
myView.findViewById(R.id.btn_gn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (mBound) {
// Call a method from the RandNumService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
//but getting a random number is really quick, so I'm doing it here instead.
int num = mService.getRandomNumber();
Toast.makeText(getActivity(), "number: " + num, Toast.LENGTH_SHORT).show();
}
}
});
return myView;
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance | LocalBinder binder = (LocalBinder) service; |
JimSeker/service | ServiceDemoIPC/app/src/main/java/edu/cs4730/servicedemoipc/MainFragment.java | // Path: ServiceDemoIPC/app/src/main/java/edu/cs4730/servicedemoipc/RandNumService.java
// public class LocalBinder extends Binder {
// RandNumService getService() {
// // Return this instance of LocalService so clients can call public methods
// return RandNumService.this;
// }
// }
| import edu.cs4730.servicedemoipc.RandNumService.LocalBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Toast; | // Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_main, container, false);
//setup the button, so it will call into the service and get a random number.
myView.findViewById(R.id.btn_gn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (mBound) {
// Call a method from the RandNumService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
//but getting a random number is really quick, so I'm doing it here instead.
int num = mService.getRandomNumber();
Toast.makeText(getActivity(), "number: " + num, Toast.LENGTH_SHORT).show();
}
}
});
return myView;
}
/**
* Defines callbacks for service binding, passed to bindService()
*/
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance | // Path: ServiceDemoIPC/app/src/main/java/edu/cs4730/servicedemoipc/RandNumService.java
// public class LocalBinder extends Binder {
// RandNumService getService() {
// // Return this instance of LocalService so clients can call public methods
// return RandNumService.this;
// }
// }
// Path: ServiceDemoIPC/app/src/main/java/edu/cs4730/servicedemoipc/MainFragment.java
import edu.cs4730.servicedemoipc.RandNumService.LocalBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Toast;
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_main, container, false);
//setup the button, so it will call into the service and get a random number.
myView.findViewById(R.id.btn_gn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (mBound) {
// Call a method from the RandNumService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
//but getting a random number is really quick, so I'm doing it here instead.
int num = mService.getRandomNumber();
Toast.makeText(getActivity(), "number: " + num, Toast.LENGTH_SHORT).show();
}
}
});
return myView;
}
/**
* Defines callbacks for service binding, passed to bindService()
*/
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance | LocalBinder binder = (LocalBinder) service; |
BladeRunnerJS/brjs | brjs-core/src/main/java/org/bladerunnerjs/plugin/utility/CommandList.java | // Path: brjs-core/src/main/java/org/bladerunnerjs/plugin/commands/core/VersionCommand.java
// public class VersionCommand extends JSAPArgsParsingCommandPlugin
// {
// // Note: ASCII art created using http://patorjk.com/software/taag/#p=display&h=1&f=Ivrit&t=%20%20%20%20BladeRunnerJS%20%20%20%20
// private static final String ASCII_ART_RESOURCE_PATH = "org/bladerunnerjs/core/plugin/command/core/bladerunner-ascii-art.txt";
//
// private BRJS brjs;
//
// private Logger logger;
//
// @Override
// protected void configureArgsParser(JSAP argsParser) throws JSAPException {
// // do nothing
// }
//
// @Override
// public void setBRJS(BRJS brjs)
// {
// this.brjs = brjs;
// this.logger = brjs.logger(this.getClass());
// }
//
// @Override
// public String getCommandName()
// {
// return "version";
// }
//
// @Override
// public String getCommandDescription()
// {
// return "Displays the BladeRunnerJS version.";
// }
//
// @Override
// protected int doCommand(JSAPResult parsedArgs) throws CommandArgumentsException, CommandOperationException {
// try (InputStream asciiArtInputStream = getClass().getClassLoader().getResourceAsStream( ASCII_ART_RESOURCE_PATH )) {
// StringWriter asciiArtWriter = new StringWriter();
// IOUtils.copy(asciiArtInputStream, asciiArtWriter, "UTF-8");
//
// logger.println( brjs.versionInfo().toString() );
// logger.println("");
// logger.println(asciiArtWriter.toString());
// logger.println("");
// }
// catch(IOException e) {
// throw new CommandOperationException("error reading ascii art resource file", e);
// }
//
// return 0;
// }
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.bladerunnerjs.api.BRJS;
import org.bladerunnerjs.api.plugin.CommandPlugin;
import org.bladerunnerjs.plugin.commands.core.HelpCommand;
import org.bladerunnerjs.plugin.commands.core.VersionCommand;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2; | package org.bladerunnerjs.plugin.utility;
public class CommandList
{
private List<CommandPlugin> coreCommands = new ArrayList<>();
private List<CommandPlugin> pluginCommands;
public CommandList(BRJS brjs, List<CommandPlugin> pluginCommands)
{
this.pluginCommands = pluginCommands;
CommandPlugin helpCommand = new HelpCommand(); | // Path: brjs-core/src/main/java/org/bladerunnerjs/plugin/commands/core/VersionCommand.java
// public class VersionCommand extends JSAPArgsParsingCommandPlugin
// {
// // Note: ASCII art created using http://patorjk.com/software/taag/#p=display&h=1&f=Ivrit&t=%20%20%20%20BladeRunnerJS%20%20%20%20
// private static final String ASCII_ART_RESOURCE_PATH = "org/bladerunnerjs/core/plugin/command/core/bladerunner-ascii-art.txt";
//
// private BRJS brjs;
//
// private Logger logger;
//
// @Override
// protected void configureArgsParser(JSAP argsParser) throws JSAPException {
// // do nothing
// }
//
// @Override
// public void setBRJS(BRJS brjs)
// {
// this.brjs = brjs;
// this.logger = brjs.logger(this.getClass());
// }
//
// @Override
// public String getCommandName()
// {
// return "version";
// }
//
// @Override
// public String getCommandDescription()
// {
// return "Displays the BladeRunnerJS version.";
// }
//
// @Override
// protected int doCommand(JSAPResult parsedArgs) throws CommandArgumentsException, CommandOperationException {
// try (InputStream asciiArtInputStream = getClass().getClassLoader().getResourceAsStream( ASCII_ART_RESOURCE_PATH )) {
// StringWriter asciiArtWriter = new StringWriter();
// IOUtils.copy(asciiArtInputStream, asciiArtWriter, "UTF-8");
//
// logger.println( brjs.versionInfo().toString() );
// logger.println("");
// logger.println(asciiArtWriter.toString());
// logger.println("");
// }
// catch(IOException e) {
// throw new CommandOperationException("error reading ascii art resource file", e);
// }
//
// return 0;
// }
// }
// Path: brjs-core/src/main/java/org/bladerunnerjs/plugin/utility/CommandList.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.bladerunnerjs.api.BRJS;
import org.bladerunnerjs.api.plugin.CommandPlugin;
import org.bladerunnerjs.plugin.commands.core.HelpCommand;
import org.bladerunnerjs.plugin.commands.core.VersionCommand;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
package org.bladerunnerjs.plugin.utility;
public class CommandList
{
private List<CommandPlugin> coreCommands = new ArrayList<>();
private List<CommandPlugin> pluginCommands;
public CommandList(BRJS brjs, List<CommandPlugin> pluginCommands)
{
this.pluginCommands = pluginCommands;
CommandPlugin helpCommand = new HelpCommand(); | CommandPlugin versionCommand = new VersionCommand(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.